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

fix(prod2u): correct active-high damper limits and motion state

Codex 4 месяцев назад
Родитель
Сommit
1feb1a231a
43 измененных файлов с 2886 добавлено и 293 удалено
  1. 2 1
      config/prod2u_p4_normal_host_contract_v3.json
  2. 2 2
      config/prod2u_p4_normal_v3_hw_binding.json
  3. 108 0
      config/prod2u_p4_normal_v3_resource_baseline.json
  4. 2 2
      constraints/prod2u_p4_normal_v3.adc
  5. 12 8
      docs/prod2u-p4-normal-v3-actuator-temp-runbook.zh-CN.md
  6. 2 1
      schemas/prod2u_p4_normal_host_contract_v3.schema.json
  7. 27 0
      schemas/prod2u_p4_normal_v3_resource_baseline.schema.json
  8. 10 0
      schemas/prod2u_p4_normal_v3_td_build_receipt.schema.json
  9. 563 0
      src/rtl/prod2u_p4_axis_executor.v
  10. 15 8
      src/rtl/prod2u_p4_limit_filter.v
  11. 34 13
      src/rtl/prod2u_p4_motor_hub.v
  12. 4 4
      src/top/prod2u_p4_normal_v3_top.v
  13. 4 4
      td/syn/prod2u_p4_normal_v3.tcl
  14. 14 0
      tests/formal/prod2u_p4_axis_motion_state.sby
  15. 235 0
      tests/formal/prod2u_p4_axis_motion_state_formal.v
  16. 90 3
      tests/formal/prod2u_p4_axis_safety_formal.v
  17. 7 6
      tests/sim/prod2u_p4_axis_executor_xy_tb.v
  18. 512 0
      tests/sim/prod2u_p4_axis_motion_state_tb.v
  19. 17 10
      tests/sim/prod2u_p4_limit_filter_tb.v
  20. 36 9
      tests/sim/prod2u_p4_limit_ready_motor_tb.v
  21. 288 0
      tests/sim/prod2u_p4_motor_hub_policy_tb.v
  22. 5 5
      tests/sim/prod2u_p4_motor_hub_tb.v
  23. 15 15
      tests/sim/prod2u_p4_normal_v3_core_tb.v
  24. 6 6
      tests/sim/prod2u_p4_normal_v3_top_e2e_tb.v
  25. 6 6
      tests/sim/prod2u_p4_normal_v3_top_tb.v
  26. 6 6
      tests/sim/prod2u_p4_temperature_e2e_tb.v
  27. 17 0
      tests/unit/test_pid_harness.py
  28. 4 4
      tests/unit/test_pin_inventory.py
  29. 108 6
      tests/unit/test_prod2u_p4_normal_v3_gate.py
  30. 93 6
      tests/unit/test_prod2u_p4_normal_v3_model.py
  31. 3 3
      tests/unit/test_prod2u_p4_normal_v3_receipts.py
  32. 103 0
      tests/unit/test_prod2u_p4_normal_v3_resources.py
  33. 25 2
      tests/unit/test_prod2u_p4_normal_v3_simplified_delivery.py
  34. 2 2
      tests/unit/test_prod2u_p4_normal_v3_td_files.py
  35. 16 0
      tests/unit/test_prod2u_p4_protocol_v3.py
  36. 4 4
      tests/unit/test_prod2u_p4_wrapper_v3.py
  37. 39 6
      tools/pid_harness.py
  38. 6 6
      tools/pin_inventory.py
  39. 4 4
      tools/prod2u.ps1
  40. 117 58
      tools/prod2u_p4_cli.py
  41. 118 0
      tools/prod2u_p4_normal_v3_build.py
  42. 203 81
      tools/prod2u_p4_normal_v3_model.py
  43. 2 2
      tools/prod2u_p4_protocol.py

+ 2 - 1
config/prod2u_p4_normal_host_contract_v3.json

@@ -263,7 +263,8 @@
         "fault_mask": 23,
         "crc": [24, 25]
       },
-      "position_values": [0, 100, 255],
+      "position_values": [0, 100, 254, 255],
+      "intermediate_position": 254,
       "unknown_position": 255,
       "flag_bits": {
         "any_busy": 0,

+ 2 - 2
config/prod2u_p4_normal_v3_hw_binding.json

@@ -33,10 +33,10 @@
     "enable_n_ball": "A10",
     "x_step_ball": "C11",
     "x_dir_ball": "B12",
-    "x_limit_n_ball": "A11",
+    "x_limit_raw_ball": "A11",
     "y_step_ball": "D15",
     "y_dir_ball": "H14",
-    "y_limit_n_ball": "A5",
+    "y_limit_raw_ball": "A5",
     "z_step_ball": "H12",
     "z_dir_ball": "F14",
     "z_hardware_status": "not_connected_protocol_reserved"

+ 108 - 0
config/prod2u_p4_normal_v3_resource_baseline.json

@@ -0,0 +1,108 @@
+{
+  "schema": "prod2u-p4-normal-v3-resource-baseline-v1",
+  "profile": "prod2u_p4_normal_v3",
+  "device": "EF2L45BG256B",
+  "snapshot_commit": "c9cf6a561f6ed16c001fcc08244827ac75f5c981",
+  "policy": {
+    "mode": "advisory_only",
+    "affects_build_status": false
+  },
+  "samples": [
+    {
+      "build_id": "6A5AE72C",
+      "overall": {
+        "lut": 3060,
+        "reg": 2476,
+        "packed_slices": 1743,
+        "mslice": 871,
+        "bram": 0,
+        "dsp": 0,
+        "io": 43
+      },
+      "timing": {
+        "fmax_mhz": 57.637,
+        "worst_setup_slack_ns": 22.65,
+        "worst_hold_slack_ns": 0.031
+      }
+    },
+    {
+      "build_id": "6A5B30C9",
+      "overall": {
+        "lut": 3047,
+        "reg": 2475,
+        "packed_slices": 1748,
+        "mslice": 874,
+        "bram": 0,
+        "dsp": 0,
+        "io": 43
+      },
+      "timing": {
+        "fmax_mhz": 63.179,
+        "worst_setup_slack_ns": 24.172,
+        "worst_hold_slack_ns": 0.038
+      }
+    }
+  ],
+  "envelope": {
+    "overall": {
+      "lut": {"min": 3047, "max": 3060},
+      "reg": {"min": 2475, "max": 2476},
+      "packed_slices": {"min": 1743, "max": 1748},
+      "mslice": {"min": 871, "max": 874},
+      "bram": {"min": 0, "max": 0},
+      "dsp": {"min": 0, "max": 0},
+      "io": {"min": 43, "max": 43}
+    },
+    "timing": {
+      "fmax_mhz": {"min": 57.637, "max": 63.179},
+      "worst_setup_slack_ns": {"min": 22.65, "max": 24.172},
+      "worst_hold_slack_ns": {"min": 0.031, "max": 0.038}
+    },
+    "hierarchy": {
+      "u_core": {
+        "lut": {"min": 1168, "max": 1171},
+        "seq": {"min": 918, "max": 922}
+      },
+      "u_motors": {
+        "lut": {"min": 443, "max": 453},
+        "seq": {"min": 230, "max": 235}
+      },
+      "u_x_axis": {
+        "lut": {"min": 180, "max": 191},
+        "seq": {"min": 82, "max": 86}
+      },
+      "u_y_axis": {
+        "lut": {"min": 152, "max": 174},
+        "seq": {"min": 75, "max": 77}
+      },
+      "u_z_axis": {
+        "lut": {"min": 88, "max": 90},
+        "seq": {"min": 62, "max": 64}
+      },
+      "u_outputs": {
+        "lut": {"min": 539, "max": 551},
+        "seq": {"min": 537, "max": 548}
+      },
+      "u_protocol_rx": {
+        "lut": {"min": 327, "max": 329},
+        "seq": {"min": 319, "max": 322}
+      },
+      "u_temp_scan": {
+        "lut": {"min": 372, "max": 379},
+        "seq": {"min": 370, "max": 372}
+      },
+      "u_temperature_frame": {
+        "lut": {"min": 402, "max": 404},
+        "seq": {"min": 399, "max": 402}
+      },
+      "u_x_limit": {
+        "lut": {"min": 24, "max": 28},
+        "seq": {"min": 21, "max": 24}
+      },
+      "u_y_limit": {
+        "lut": {"min": 24, "max": 26},
+        "seq": {"min": 22, "max": 22}
+      }
+    }
+  }
+}

+ 2 - 2
constraints/prod2u_p4_normal_v3.adc

@@ -40,7 +40,7 @@ set_pin_assignment { y_step } { LOCATION = D15; IOSTANDARD = LVCMOS33; PULLTYPE
 set_pin_assignment { y_dir } { LOCATION = H14; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { z_step } { LOCATION = H12; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { z_dir } { LOCATION = F14; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
-set_pin_assignment { x_limit_n } { LOCATION = A11; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }
-set_pin_assignment { y_limit_n } { LOCATION = A5; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }
+set_pin_assignment { x_limit_raw } { LOCATION = A11; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }
+set_pin_assignment { y_limit_raw } { LOCATION = A5; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }
 set_pin_assignment { temp_scl } { LOCATION = M8; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { temp_sda } { LOCATION = N9; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }

+ 12 - 8
docs/prod2u-p4-normal-v3-actuator-temp-runbook.zh-CN.md

@@ -7,7 +7,7 @@
 - P5 高电平:电磁铁吸合,关闭进风口。
 - P5 低电平:电磁铁断电,打开进风口,也是安全状态。
 - LS1=X,LS2=Y。
-- LS1/LS2 在关门端约为 0V,非关门端约为 3.3V。
+- LS1/LS2 在关门端约为 3.3V,开门端约为 0V。
 - Z 未接电。协议字段保留,硬件 gate 固定发送 Z=0,不执行 Z JOG、MARK_CLOSED 或机械验收。
 - PTC 验收期间固定 0%,FAN 安全值固定 30%。
 - CT7428 总线未确认时不发送温度请求,不阻塞 X/Y、电磁铁和串口核心验收。
@@ -116,7 +116,7 @@ CRC_LO CRC_HI
 | 45..47 | 3 | X/Y/Z,只允许 0 或 100 |
 | 48..49 | 2 | CRC16 小端,覆盖偏移 2..47 |
 
-PTC/FAN/电磁铁原子提交。X/Y/Z 逐轴接受,忙或位置无效的轴不排队。Z 当前保持 invalid,因此现场快照正常可能返回 PARTIAL,但 X/Y 和同步输出仍可成功提交。
+PTC/FAN/电磁铁原子提交。X/Y/Z 逐轴接受;同目标命令允许幂等成功,禁止的反向或位置无效轴不排队。Z 当前保持 invalid,因此现场快照正常可能返回 PARTIAL,但 X/Y 和同步输出仍可成功提交。
 
 ### 4.2 ACK、状态和温度
 
@@ -133,6 +133,8 @@ ok | command | status | detail | state_hash16_le | response_type | result_flags
 - `0x35 JOG`:`35 axis raw_dir speed_code steps_lo steps_hi 00 00`。
 - `0x36 MARK_CLOSED`:`36 02 close_dir 00 00 00 00 00`,当前只保留 Z 协议,不做实板操作。
 - `0x37 GET_MOTOR_STATUS`:`37 00 00 00 00 00 00 00`,先返回 ACK,再返回 10 字节 MOTION_STATUS payload。
+- X/Y 位置字节中,`00` 为关闭端点、`64` 为全开端点、`FE` 为已校准的中间位置或运动状态、`FF` 为未校准/未知/锁定;锁定同时置 fault bit。
+- X/Y 关闭运行 3200 步未见 LS 时进入 RECOVERY,只允许一次同方向且最多 160 步的恢复 JOG;仍未见 LS 后锁定且不再输出 STEP。
 
 温度请求 payload 为 `29 00 00 00`。温度响应是唯一紧凑帧,固定 61 字节:
 
@@ -153,7 +155,7 @@ BOOT_BUILD_ID 上电只发送一次,payload 为 embedded BUILD_ID 和 capabili
 3. PTC 负载不加热。
 4. 机构行程安全。
 5. P5 高电平确实关闭进风。
-6. LS1=X、LS2=Y,且关门约 0V、非关门约 3.3V。
+6. LS1=X、LS2=Y,且关门约 3.3V、开门约 0V。
 7. 已知 X/Y 的原始关门方向:`--x-close-dir` 和 `--y-close-dir`,值只能是 0 或 1。
 
 如果 LS 电平不符合,只阻塞对应 X/Y 电机测试。CT7428 总线未确认不阻塞核心 gate。
@@ -173,8 +175,8 @@ $GateArgs = @(
     "--confirm-ptc-load-disabled",
     "--confirm-mechanical-travel-safe",
     "--confirm-p5-active-high-closes-intake",
-    "--confirm-ls1-x-closed-low",
-    "--confirm-ls2-y-closed-low",
+    "--confirm-ls1-x-closed-high",
+    "--confirm-ls2-y-closed-high",
     "--x-close-dir", [string]$XCloseDir,
     "--y-close-dir", [string]$YCloseDir,
     "--run-id", $RunId
@@ -202,10 +204,12 @@ $GateArgs += @(
 编程成功后 gate 立即发送 DISABLE,不等待 BOOT_BUILD_ID。随后验证:
 
 - embedded BUILD_ID、ACK、CRC 和安全 state hash。
-- X/Y 短 JOG 和人工运动确认。
-- X/LS1、Y/LS2 关门校准。
+- X/LS1、Y/LS2 先按已确认的关门方向校准;若上电时 LS 已为高电平,该步必须零步完成,不能先用离开方向猜测关门方向。
+- 校准后执行 X/Y 离开关门端的短 JOG 和人工运动确认。
+- 每个短 JOG 确认后立即按已确认的关门方向重新校准;只有 X/Y 都回到关闭端点后才进入标准全开、全关验收。
 - X/Y 全开、全关。
-- 运动中反向目标返回 PARTIAL,当前动作不停止、不反转、不排队。
+- OPENING 重复 OPEN 幂等且不重启计数;CLOSING 收到 OPEN 返回 PARTIAL,当前关闭动作保持不变。
+- OPENING 收到 CLOSE 的安全反向由 RTL 仿真和 formal 覆盖:完整结束当前 STEP 和低电平后才切换 DIR,并重新等待 setup 时间。
 - 5 秒 watchdog 中止和安全回退。
 - P5 短时断电、吸合、断电。
 - 最终 DISABLE、STEP 全低、EN_N 高。

+ 2 - 1
schemas/prod2u_p4_normal_host_contract_v3.schema.json

@@ -300,7 +300,8 @@
             "fault_mask": 23,
             "crc": [24, 25]
           },
-          "position_values": [0, 100, 255],
+          "position_values": [0, 100, 254, 255],
+          "intermediate_position": 254,
           "unknown_position": 255,
           "flag_bits": {
             "any_busy": 0,

+ 27 - 0
schemas/prod2u_p4_normal_v3_resource_baseline.schema.json

@@ -0,0 +1,27 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-p4-normal-v3-resource-baseline-v1",
+  "type": "object",
+  "required": ["schema", "profile", "device", "snapshot_commit", "policy", "samples", "envelope"],
+  "properties": {
+    "schema": {"const": "prod2u-p4-normal-v3-resource-baseline-v1"},
+    "profile": {"const": "prod2u_p4_normal_v3"},
+    "device": {"const": "EF2L45BG256B"},
+    "snapshot_commit": {"type": "string", "pattern": "^[0-9a-f]{40}$"},
+    "policy": {
+      "type": "object",
+      "required": ["mode", "affects_build_status"],
+      "properties": {
+        "mode": {"const": "advisory_only"},
+        "affects_build_status": {"const": false}
+      },
+      "additionalProperties": false
+    },
+    "samples": {"type": "array", "minItems": 2},
+    "envelope": {
+      "type": "object",
+      "required": ["overall", "timing", "hierarchy"]
+    }
+  },
+  "additionalProperties": false
+}

+ 10 - 0
schemas/prod2u_p4_normal_v3_td_build_receipt.schema.json

@@ -36,6 +36,15 @@
     "timing": {"type": ["object", "null"], "additionalProperties": true},
     "timing_gate": {"type": ["object", "null"], "additionalProperties": true},
     "resource_gate": {"type": ["object", "null"], "additionalProperties": true},
+    "resource_delta": {
+      "type": ["object", "null"],
+      "properties": {
+        "schema": {"const": "prod2u-p4-normal-v3-resource-delta-v1"},
+        "advisory_only": {"const": true},
+        "affects_build_status": {"const": false}
+      },
+      "additionalProperties": true
+    },
     "clean": {"type": ["object", "null"], "additionalProperties": true},
     "pin_binding_gate": {"type": ["object", "null"], "additionalProperties": true},
     "binding_gate": {"type": ["object", "null"], "additionalProperties": true},
@@ -58,6 +67,7 @@
           "timing",
           "timing_gate",
           "resource_gate",
+          "resource_delta",
           "clean",
           "pin_binding_gate",
           "binding_gate",

+ 563 - 0
src/rtl/prod2u_p4_axis_executor.v

@@ -8,6 +8,568 @@ module prod2u_p4_axis_executor #(
     parameter integer SPEED1_HALF_US = 12500,
     parameter integer SPEED2_HALF_US = 5000,
     parameter integer SPEED3_HALF_US = 500
+) (
+    input  wire        clk,
+    input  wire        rst_n,
+    input  wire        tick_1us,
+    input  wire        force_stop,
+    input  wire        limit_active,
+    input  wire        jog_start,
+    input  wire        jog_dir,
+    input  wire [1:0]  jog_speed_code,
+    input  wire [12:0] jog_steps,
+    input  wire        standard_start,
+    input  wire        standard_target_open,
+    input  wire        mark_closed,
+    input  wire        mark_close_dir,
+    output wire        step_out,
+    output wire        dir_out,
+    output wire        busy,
+    output wire        position_valid,
+    output wire [7:0]  current_aperture,
+    output wire [7:0]  target_aperture,
+    output wire        close_dir,
+    output wire        fault,
+    output wire [1:0]  move_kind,
+    output wire [12:0] remaining_steps,
+    output wire [2:0]  axis_state,
+    output wire        jog_can_accept,
+    output wire        standard_can_accept
+);
+    generate
+        if (HAS_LIMIT) begin : g_limited_axis
+            prod2u_p4_axis_executor_limited #(
+                .STANDARD_STEPS(STANDARD_STEPS),
+                .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)
+            ) u_limited (
+                .clk(clk),
+                .rst_n(rst_n),
+                .tick_1us(tick_1us),
+                .force_stop(force_stop),
+                .limit_active(limit_active),
+                .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),
+                .position_valid(position_valid),
+                .current_aperture(current_aperture),
+                .target_aperture(target_aperture),
+                .close_dir(close_dir),
+                .fault(fault),
+                .move_kind(move_kind),
+                .remaining_steps(remaining_steps),
+                .axis_state(axis_state),
+                .jog_can_accept(jog_can_accept),
+                .standard_can_accept(standard_can_accept)
+            );
+        end else begin : g_unlimited_axis
+            prod2u_p4_axis_executor_legacy #(
+                .HAS_LIMIT(0),
+                .STANDARD_STEPS(STANDARD_STEPS),
+                .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)
+            ) u_unlimited (
+                .clk(clk),
+                .rst_n(rst_n),
+                .tick_1us(tick_1us),
+                .force_stop(force_stop),
+                .limit_active(limit_active),
+                .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),
+                .mark_closed(mark_closed),
+                .mark_close_dir(mark_close_dir),
+                .step_out(step_out),
+                .dir_out(dir_out),
+                .busy(busy),
+                .position_valid(position_valid),
+                .current_aperture(current_aperture),
+                .target_aperture(target_aperture),
+                .close_dir(close_dir),
+                .fault(fault),
+                .move_kind(move_kind),
+                .remaining_steps(remaining_steps)
+            );
+
+            assign axis_state = !position_valid ? 3'd0 :
+                (busy ? (target_aperture == 8'd100 ? 3'd2 : 3'd4) :
+                (current_aperture == 8'd100 ? 3'd3 : 3'd1));
+            assign jog_can_accept = !busy;
+            assign standard_can_accept = !busy && position_valid;
+        end
+    endgenerate
+endmodule
+
+/* verilator lint_off DECLFILENAME */
+module prod2u_p4_axis_executor_limited #(
+    parameter integer STANDARD_STEPS = 3200,
+    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
+) (
+    input  wire        clk,
+    input  wire        rst_n,
+    input  wire        tick_1us,
+    input  wire        force_stop,
+    input  wire        limit_active,
+    input  wire        jog_start,
+    input  wire        jog_dir,
+    input  wire [1:0]  jog_speed_code,
+    input  wire [12:0] jog_steps,
+    input  wire        standard_start,
+    input  wire        standard_target_open,
+    output reg         step_out,
+    output reg         dir_out,
+    output reg         busy,
+    output reg         close_dir,
+    output reg  [1:0]  move_kind,
+    output reg  [12:0] remaining_steps,
+    output reg  [2:0]  axis_state,
+    output reg         position_valid,
+    output reg  [7:0]  current_aperture,
+    output reg  [7:0]  target_aperture,
+    output reg         fault,
+    output reg         jog_can_accept,
+    output reg         standard_can_accept
+);
+    localparam [2:0] AXIS_UNCALIBRATED = 3'd0;
+    localparam [2:0] AXIS_CLOSED = 3'd1;
+    localparam [2:0] AXIS_OPENING = 3'd2;
+    localparam [2:0] AXIS_OPEN = 3'd3;
+    localparam [2:0] AXIS_CLOSING = 3'd4;
+    localparam [2:0] AXIS_INTERMEDIATE = 3'd5;
+    localparam [2:0] AXIS_RECOVERY = 3'd6;
+    localparam [2:0] AXIS_LOCKED_FAULT = 3'd7;
+
+    localparam [1:0] MOVE_IDLE = 2'd0;
+    localparam [1:0] MOVE_STANDARD = 2'd1;
+    localparam [1:0] MOVE_JOG = 2'd2;
+
+    localparam [1:0] PHASE_DIR_SETUP = 2'd0;
+    localparam [1:0] PHASE_STEP_HIGH = 2'd1;
+    localparam [1:0] PHASE_STEP_LOW = 2'd2;
+    localparam [1:0] PHASE_LIMIT_LOW = 2'd3;
+
+    reg [1:0] motion_phase;
+    reg [15:0] setup_remaining_us;
+    reg [15:0] half_remaining_us;
+    reg [15:0] active_half_period_us;
+    reg stop_pending;
+    reg stop_pending_is_limit;
+    reg limit_stop_enabled;
+    reg capture_close_dir_on_limit;
+    reg reverse_pending;
+
+    wire limit_stop_request;
+    wire reverse_request;
+    assign limit_stop_request = busy && limit_active && limit_stop_enabled;
+    assign reverse_request = busy && standard_start && standard_can_accept &&
+        (axis_state == AXIS_OPENING) && !standard_target_open;
+
+    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;
+                2'd1: half_period_for_speed = SPEED1_HALF_US;
+                2'd2: half_period_for_speed = SPEED2_HALF_US;
+                default: half_period_for_speed = SPEED3_HALF_US;
+            endcase
+        end
+    endfunction
+
+    always @(*) begin
+        position_valid = 1'b1;
+        current_aperture = 8'hfe;
+        target_aperture = 8'hfe;
+        fault = 1'b0;
+        case (axis_state)
+            AXIS_UNCALIBRATED: begin
+                position_valid = 1'b0;
+                current_aperture = 8'hff;
+                target_aperture = 8'hff;
+            end
+            AXIS_CLOSED: begin
+                current_aperture = 8'd0;
+                target_aperture = 8'd0;
+            end
+            AXIS_OPENING: begin
+                current_aperture = 8'hfe;
+                target_aperture = reverse_pending ? 8'd0 : 8'd100;
+            end
+            AXIS_OPEN: begin
+                current_aperture = 8'd100;
+                target_aperture = 8'd100;
+            end
+            AXIS_CLOSING: begin
+                current_aperture = 8'hfe;
+                target_aperture = 8'd0;
+            end
+            AXIS_INTERMEDIATE: begin
+                current_aperture = 8'hfe;
+                target_aperture = 8'hfe;
+            end
+            AXIS_RECOVERY: begin
+                current_aperture = 8'hfe;
+                target_aperture = 8'd0;
+            end
+            default: begin
+                position_valid = 1'b0;
+                current_aperture = 8'hff;
+                target_aperture = 8'hff;
+                fault = 1'b1;
+            end
+        endcase
+
+        jog_can_accept = 1'b0;
+        if (!busy) begin
+            case (axis_state)
+                AXIS_UNCALIBRATED: jog_can_accept = 1'b1;
+                AXIS_CLOSED: jog_can_accept = (jog_dir != close_dir);
+                AXIS_OPEN: jog_can_accept = (jog_dir == close_dir);
+                AXIS_INTERMEDIATE: jog_can_accept = 1'b1;
+                AXIS_RECOVERY: jog_can_accept = (jog_dir == close_dir);
+                default: jog_can_accept = 1'b0;
+            endcase
+        end
+
+        standard_can_accept = 1'b0;
+        case (axis_state)
+            AXIS_CLOSED,
+            AXIS_OPEN: standard_can_accept = !busy;
+            AXIS_OPENING: standard_can_accept = reverse_pending ?
+                !standard_target_open : 1'b1;
+            AXIS_CLOSING: standard_can_accept = !standard_target_open;
+            AXIS_INTERMEDIATE: standard_can_accept = !busy && !standard_target_open;
+            default: standard_can_accept = 1'b0;
+        endcase
+    end
+
+    task clear_motion;
+        begin
+            step_out <= 1'b0;
+            busy <= 1'b0;
+            move_kind <= MOVE_IDLE;
+            remaining_steps <= 13'd0;
+            motion_phase <= PHASE_DIR_SETUP;
+            setup_remaining_us <= 16'd0;
+            half_remaining_us <= 16'd0;
+            stop_pending <= 1'b0;
+            stop_pending_is_limit <= 1'b0;
+            limit_stop_enabled <= 1'b0;
+            capture_close_dir_on_limit <= 1'b0;
+            reverse_pending <= 1'b0;
+        end
+    endtask
+
+    task apply_safety_stop;
+        begin
+            if (busy) begin
+                if (axis_state == AXIS_RECOVERY) begin
+                    axis_state <= AXIS_LOCKED_FAULT;
+                end else if ((axis_state != AXIS_UNCALIBRATED) &&
+                             (axis_state != AXIS_LOCKED_FAULT)) begin
+                    axis_state <= AXIS_INTERMEDIATE;
+                end
+            end
+            clear_motion();
+        end
+    endtask
+
+    task apply_limit_stop;
+        begin
+            if (capture_close_dir_on_limit) begin
+                close_dir <= dir_out;
+            end
+            axis_state <= AXIS_CLOSED;
+            clear_motion();
+        end
+    endtask
+
+    task begin_limit_stop;
+        begin
+            step_out <= 1'b0;
+            remaining_steps <= 13'd0;
+            motion_phase <= PHASE_LIMIT_LOW;
+            half_remaining_us <= active_half_period_us;
+            stop_pending <= 1'b0;
+            stop_pending_is_limit <= 1'b0;
+            limit_stop_enabled <= 1'b0;
+        end
+    endtask
+
+    task start_standard_motion;
+        input direction;
+        input [2:0] next_state;
+        begin
+            step_out <= 1'b0;
+            dir_out <= direction;
+            busy <= 1'b1;
+            axis_state <= next_state;
+            move_kind <= MOVE_STANDARD;
+            remaining_steps <= STANDARD_STEPS;
+            motion_phase <= PHASE_DIR_SETUP;
+            setup_remaining_us <= DIR_SETUP_US;
+            active_half_period_us <= SPEED3_HALF_US;
+            half_remaining_us <= SPEED3_HALF_US;
+            stop_pending <= 1'b0;
+            stop_pending_is_limit <= 1'b0;
+            limit_stop_enabled <= (next_state == AXIS_CLOSING);
+            capture_close_dir_on_limit <= 1'b0;
+            reverse_pending <= 1'b0;
+        end
+    endtask
+
+    task switch_opening_to_close;
+        begin
+            step_out <= 1'b0;
+            dir_out <= close_dir;
+            axis_state <= AXIS_CLOSING;
+            move_kind <= MOVE_STANDARD;
+            remaining_steps <= STANDARD_STEPS;
+            motion_phase <= PHASE_DIR_SETUP;
+            setup_remaining_us <= DIR_SETUP_US;
+            active_half_period_us <= SPEED3_HALF_US;
+            half_remaining_us <= SPEED3_HALF_US;
+            limit_stop_enabled <= 1'b1;
+            capture_close_dir_on_limit <= 1'b0;
+            reverse_pending <= 1'b0;
+        end
+    endtask
+
+    task start_jog_motion;
+        begin
+            step_out <= 1'b0;
+            dir_out <= jog_dir;
+            busy <= 1'b1;
+            move_kind <= MOVE_JOG;
+            remaining_steps <= jog_steps;
+            motion_phase <= PHASE_DIR_SETUP;
+            setup_remaining_us <= DIR_SETUP_US;
+            active_half_period_us <= half_period_for_speed(jog_speed_code);
+            half_remaining_us <= half_period_for_speed(jog_speed_code);
+            stop_pending <= 1'b0;
+            stop_pending_is_limit <= 1'b0;
+            reverse_pending <= 1'b0;
+            case (axis_state)
+                AXIS_UNCALIBRATED: begin
+                    limit_stop_enabled <= 1'b1;
+                    capture_close_dir_on_limit <= 1'b1;
+                end
+                AXIS_CLOSED: begin
+                    axis_state <= AXIS_INTERMEDIATE;
+                    limit_stop_enabled <= 1'b0;
+                    capture_close_dir_on_limit <= 1'b0;
+                end
+                AXIS_OPEN: begin
+                    axis_state <= AXIS_INTERMEDIATE;
+                    limit_stop_enabled <= 1'b1;
+                    capture_close_dir_on_limit <= 1'b0;
+                end
+                AXIS_INTERMEDIATE: begin
+                    limit_stop_enabled <= (jog_dir == close_dir);
+                    capture_close_dir_on_limit <= 1'b0;
+                end
+                default: begin
+                    limit_stop_enabled <= 1'b1;
+                    capture_close_dir_on_limit <= 1'b0;
+                end
+            endcase
+        end
+    endtask
+
+    task finish_normal_motion;
+        begin
+            if (move_kind == MOVE_STANDARD) begin
+                if (axis_state == AXIS_OPENING) begin
+                    axis_state <= AXIS_OPEN;
+                end else if (axis_state == AXIS_CLOSING) begin
+                    axis_state <= AXIS_RECOVERY;
+                end
+            end else if ((move_kind == MOVE_JOG) && (axis_state == AXIS_RECOVERY)) begin
+                axis_state <= AXIS_LOCKED_FAULT;
+            end
+            clear_motion();
+        end
+    endtask
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            step_out <= 1'b0;
+            dir_out <= 1'b0;
+            busy <= 1'b0;
+            close_dir <= 1'b0;
+            move_kind <= MOVE_IDLE;
+            remaining_steps <= 13'd0;
+            axis_state <= AXIS_UNCALIBRATED;
+            motion_phase <= PHASE_DIR_SETUP;
+            setup_remaining_us <= 16'd0;
+            half_remaining_us <= 16'd0;
+            active_half_period_us <= SPEED3_HALF_US;
+            stop_pending <= 1'b0;
+            stop_pending_is_limit <= 1'b0;
+            limit_stop_enabled <= 1'b0;
+            capture_close_dir_on_limit <= 1'b0;
+            reverse_pending <= 1'b0;
+        end else if (force_stop) begin
+            if (busy && step_out && !tick_1us) begin
+                stop_pending <= 1'b1;
+                stop_pending_is_limit <= 1'b0;
+            end else begin
+                apply_safety_stop();
+            end
+        end else if (stop_pending) begin
+            if (!busy || !step_out || tick_1us) begin
+                if (stop_pending_is_limit) begin
+                    begin_limit_stop();
+                end else begin
+                    apply_safety_stop();
+                end
+            end
+        end else if (limit_stop_request) begin
+            if (step_out && !tick_1us) begin
+                stop_pending <= 1'b1;
+                stop_pending_is_limit <= 1'b1;
+            end else begin
+                begin_limit_stop();
+            end
+        end else if (!busy) begin
+            step_out <= 1'b0;
+            move_kind <= MOVE_IDLE;
+            remaining_steps <= 13'd0;
+
+            if (jog_start && jog_can_accept && (jog_steps != 13'd0)) begin
+                if (limit_active &&
+                    ((axis_state == AXIS_UNCALIBRATED) || (jog_dir == close_dir))) begin
+                    if (axis_state == AXIS_UNCALIBRATED) begin
+                        close_dir <= jog_dir;
+                    end
+                    axis_state <= AXIS_CLOSED;
+                end else begin
+                    start_jog_motion();
+                end
+            end else if (standard_start && standard_can_accept) begin
+                case (axis_state)
+                    AXIS_CLOSED: begin
+                        if (standard_target_open) begin
+                            start_standard_motion(!close_dir, AXIS_OPENING);
+                        end
+                    end
+                    AXIS_OPEN: begin
+                        if (!standard_target_open) begin
+                            if (limit_active) begin
+                                axis_state <= AXIS_CLOSED;
+                            end else begin
+                                start_standard_motion(close_dir, AXIS_CLOSING);
+                            end
+                        end
+                    end
+                    AXIS_INTERMEDIATE: begin
+                        if (limit_active) begin
+                            axis_state <= AXIS_CLOSED;
+                        end else begin
+                            start_standard_motion(close_dir, AXIS_CLOSING);
+                        end
+                    end
+                    default: begin
+                    end
+                endcase
+            end
+        end else begin
+            if (reverse_request) begin
+                reverse_pending <= 1'b1;
+            end
+
+            if (tick_1us) begin
+                case (motion_phase)
+                    PHASE_DIR_SETUP: begin
+                        if (reverse_pending || reverse_request) begin
+                            switch_opening_to_close();
+                        end else if (setup_remaining_us <= 16'd1) begin
+                            setup_remaining_us <= 16'd0;
+                            step_out <= 1'b1;
+                            motion_phase <= PHASE_STEP_HIGH;
+                            half_remaining_us <= active_half_period_us;
+                        end else begin
+                            setup_remaining_us <= setup_remaining_us - 16'd1;
+                        end
+                    end
+
+                    PHASE_STEP_HIGH: begin
+                        if (half_remaining_us <= 16'd1) begin
+                            step_out <= 1'b0;
+                            if (remaining_steps <= 13'd1) begin
+                                remaining_steps <= 13'd0;
+                            end else begin
+                                remaining_steps <= remaining_steps - 13'd1;
+                            end
+                            motion_phase <= PHASE_STEP_LOW;
+                            half_remaining_us <= active_half_period_us;
+                        end else begin
+                            half_remaining_us <= half_remaining_us - 16'd1;
+                        end
+                    end
+
+                    PHASE_STEP_LOW: begin
+                        if (half_remaining_us <= 16'd1) begin
+                            if (reverse_pending || reverse_request) begin
+                                switch_opening_to_close();
+                            end else if (remaining_steps == 13'd0) begin
+                                finish_normal_motion();
+                            end else begin
+                                step_out <= 1'b1;
+                                motion_phase <= PHASE_STEP_HIGH;
+                                half_remaining_us <= active_half_period_us;
+                            end
+                        end else begin
+                            half_remaining_us <= half_remaining_us - 16'd1;
+                        end
+                    end
+
+                    PHASE_LIMIT_LOW: begin
+                        step_out <= 1'b0;
+                        if (half_remaining_us <= 16'd1) begin
+                            apply_limit_stop();
+                        end else begin
+                            half_remaining_us <= half_remaining_us - 16'd1;
+                        end
+                    end
+
+                    default: begin
+                        step_out <= 1'b0;
+                        motion_phase <= PHASE_DIR_SETUP;
+                    end
+                endcase
+            end
+        end
+    end
+endmodule
+
+module prod2u_p4_axis_executor_legacy #(
+    parameter integer HAS_LIMIT = 1,
+    parameter integer STANDARD_STEPS = 3200,
+    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
 ) (
     input  wire        clk,
     input  wire        rst_n,
@@ -334,3 +896,4 @@ module prod2u_p4_axis_executor #(
         end
     end
 endmodule
+/* verilator lint_on DECLFILENAME */

+ 15 - 8
src/rtl/prod2u_p4_limit_filter.v

@@ -6,7 +6,7 @@ module prod2u_p4_limit_filter #(
 ) (
     input  wire clk,
     input  wire rst_n,
-    input  wire limit_n_raw,
+    input  wire limit_raw,
     output reg  limit_active,
     output reg  limit_ready
 );
@@ -15,32 +15,39 @@ module prod2u_p4_limit_filter #(
 
     reg sync1;
     reg sync2;
+    reg [1:0] sync_valid;
     reg candidate_level;
     reg [31:0] stable_count;
 
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
-            sync1 <= 1'b1;
-            sync2 <= 1'b1;
-            candidate_level <= 1'b1;
+            sync1 <= 1'b0;
+            sync2 <= 1'b0;
+            sync_valid <= 2'b00;
+            candidate_level <= 1'b0;
             stable_count <= 32'd0;
             limit_active <= 1'b0;
             limit_ready <= 1'b0;
         end else begin
-            sync1 <= limit_n_raw;
+            sync1 <= limit_raw;
             sync2 <= sync1;
+            sync_valid <= {sync_valid[0], 1'b1};
 
-            if (sync2 != candidate_level) begin
+            if (!sync_valid[1]) begin
+                stable_count <= 32'd0;
+                limit_active <= 1'b0;
+                limit_ready <= 1'b0;
+            end else if (sync2 != candidate_level) begin
                 candidate_level <= sync2;
                 stable_count <= 32'd1;
             end else if (stable_count < STABLE_CYCLES) begin
                 stable_count <= stable_count + 32'd1;
                 if (stable_count >= STABLE_CYCLES - 1) begin
-                    limit_active <= !candidate_level;
+                    limit_active <= candidate_level;
                     limit_ready <= 1'b1;
                 end
             end else begin
-                limit_active <= !candidate_level;
+                limit_active <= candidate_level;
                 limit_ready <= 1'b1;
             end
         end

+ 34 - 13
src/rtl/prod2u_p4_motor_hub.v

@@ -50,6 +50,7 @@ module prod2u_p4_motor_hub #(
     wire [7:0] y_target;
     wire [7:0] z_target;
     wire [2:0] snapshot_can_accept;
+    wire [2:0] snapshot_busy_reject;
     wire [2:0] snapshot_is_invalid;
     wire [2:0] axis_limit_ready;
     wire jog_parameters_valid;
@@ -69,19 +70,30 @@ module prod2u_p4_motor_hub #(
     wire x_close_dir;
     wire y_close_dir;
     wire z_close_dir;
+    wire [2:0] x_axis_state;
+    wire [2:0] y_axis_state;
+    wire x_jog_can_accept;
+    wire y_jog_can_accept;
+    wire x_standard_can_accept;
+    wire y_standard_can_accept;
+    wire [2:0] unused_z_axis_state;
+    wire z_jog_can_accept;
+    wire z_standard_can_accept;
 
     assign axis_limit_ready = {1'b1, y_limit_ready, x_limit_ready};
-    assign snapshot_can_accept = (~axis_busy) & axis_position_valid &
-        axis_limit_ready & {3{!force_stop}};
-    assign snapshot_is_invalid = (~axis_busy) &
-        ((~axis_position_valid) | (~axis_limit_ready));
+    assign snapshot_can_accept[0] = x_limit_ready && !force_stop && x_standard_can_accept;
+    assign snapshot_can_accept[1] = y_limit_ready && !force_stop && y_standard_can_accept;
+    assign snapshot_can_accept[2] = z_standard_can_accept && !force_stop;
+    assign snapshot_busy_reject = axis_busy & (~snapshot_can_accept);
+    assign snapshot_is_invalid = (~axis_busy) & (~snapshot_can_accept);
     assign jog_parameters_valid = (jog_axis < 2'd3) &&
         (jog_steps >= 13'd1) && (jog_steps <= 13'd160);
     assign x_jog_start = jog_valid && jog_parameters_valid && (jog_axis == 2'd0) &&
-        !axis_busy[0] && x_limit_ready && !force_stop;
+        x_jog_can_accept && x_limit_ready && !force_stop;
     assign y_jog_start = jog_valid && jog_parameters_valid && (jog_axis == 2'd1) &&
-        !axis_busy[1] && y_limit_ready && !force_stop;
-    assign z_jog_start = jog_valid && jog_parameters_valid && (jog_axis == 2'd2) && !axis_busy[2] && !force_stop;
+        y_jog_can_accept && y_limit_ready && !force_stop;
+    assign z_jog_start = jog_valid && jog_parameters_valid && (jog_axis == 2'd2) &&
+        z_jog_can_accept && !force_stop;
     assign x_standard_start = snapshot_valid && snapshot_can_accept[0];
     assign y_standard_start = snapshot_valid && snapshot_can_accept[1];
     assign z_standard_start = snapshot_valid && snapshot_can_accept[2];
@@ -119,7 +131,10 @@ module prod2u_p4_motor_hub #(
         .close_dir(x_close_dir),
         .fault(axis_fault[0]),
         .move_kind(x_move_kind),
-        .remaining_steps(x_remaining)
+        .remaining_steps(x_remaining),
+        .axis_state(x_axis_state),
+        .jog_can_accept(x_jog_can_accept),
+        .standard_can_accept(x_standard_can_accept)
     );
 
     prod2u_p4_axis_executor #(
@@ -153,7 +168,10 @@ module prod2u_p4_motor_hub #(
         .close_dir(y_close_dir),
         .fault(axis_fault[1]),
         .move_kind(y_move_kind),
-        .remaining_steps(y_remaining)
+        .remaining_steps(y_remaining),
+        .axis_state(y_axis_state),
+        .jog_can_accept(y_jog_can_accept),
+        .standard_can_accept(y_standard_can_accept)
     );
 
     prod2u_p4_axis_executor #(
@@ -187,7 +205,10 @@ module prod2u_p4_motor_hub #(
         .close_dir(z_close_dir),
         .fault(axis_fault[2]),
         .move_kind(z_move_kind),
-        .remaining_steps(z_remaining)
+        .remaining_steps(z_remaining),
+        .axis_state(unused_z_axis_state),
+        .jog_can_accept(z_jog_can_accept),
+        .standard_can_accept(z_standard_can_accept)
     );
 
     always @(*) begin
@@ -227,7 +248,7 @@ module prod2u_p4_motor_hub #(
 
             if (snapshot_valid) begin
                 snapshot_result_valid <= 1'b1;
-                snapshot_busy_mask <= axis_busy;
+                snapshot_busy_mask <= snapshot_busy_reject;
                 snapshot_invalid_mask <= snapshot_is_invalid;
                 snapshot_accepted_mask <= snapshot_can_accept;
             end
@@ -235,9 +256,9 @@ module prod2u_p4_motor_hub #(
             if (jog_valid) begin
                 jog_result_valid <= 1'b1;
                 case (jog_axis)
-                    2'd0: jog_accepted <= jog_parameters_valid && !axis_busy[0] &&
+                    2'd0: jog_accepted <= jog_parameters_valid && x_jog_can_accept &&
                         x_limit_ready && !force_stop;
-                    2'd1: jog_accepted <= jog_parameters_valid && !axis_busy[1] &&
+                    2'd1: jog_accepted <= jog_parameters_valid && y_jog_can_accept &&
                         y_limit_ready && !force_stop;
                     2'd2: jog_accepted <= jog_parameters_valid && !axis_busy[2] && !force_stop;
                     default: jog_accepted <= 1'b0;

+ 4 - 4
src/top/prod2u_p4_normal_v3_top.v

@@ -25,8 +25,8 @@ module prod2u_p4_normal_v3_top #(
     output wire        y_dir,
     output wire        z_step,
     output wire        z_dir,
-    input  wire        x_limit_n,
-    input  wire        y_limit_n,
+    input  wire        x_limit_raw,
+    input  wire        y_limit_raw,
     inout  wire        temp_scl,
     inout  wire        temp_sda
 );
@@ -179,7 +179,7 @@ module prod2u_p4_normal_v3_top #(
     ) u_x_limit (
         .clk(sys_clk),
         .rst_n(sys_rst_n),
-        .limit_n_raw(x_limit_n),
+        .limit_raw(x_limit_raw),
         .limit_active(x_limit_active),
         .limit_ready(x_limit_ready)
     );
@@ -190,7 +190,7 @@ module prod2u_p4_normal_v3_top #(
     ) u_y_limit (
         .clk(sys_clk),
         .rst_n(sys_rst_n),
-        .limit_n_raw(y_limit_n),
+        .limit_raw(y_limit_raw),
         .limit_active(y_limit_active),
         .limit_ready(y_limit_ready)
     );

+ 4 - 4
td/syn/prod2u_p4_normal_v3.tcl

@@ -46,8 +46,8 @@ wrapper = f"""module prod2u_p4_normal_v3_frozen_top (
     output wire        y_dir,
     output wire        z_step,
     output wire        z_dir,
-    input  wire        x_limit_n,
-    input  wire        y_limit_n,
+    input  wire        x_limit_raw,
+    input  wire        y_limit_raw,
     inout  wire        temp_scl,
     inout  wire        temp_sda
 );
@@ -68,8 +68,8 @@ wrapper = f"""module prod2u_p4_normal_v3_frozen_top (
         .y_dir(y_dir),
         .z_step(z_step),
         .z_dir(z_dir),
-        .x_limit_n(x_limit_n),
-        .y_limit_n(y_limit_n),
+        .x_limit_raw(x_limit_raw),
+        .y_limit_raw(y_limit_raw),
         .temp_scl(temp_scl),
         .temp_sda(temp_sda)
     );

+ 14 - 0
tests/formal/prod2u_p4_axis_motion_state.sby

@@ -0,0 +1,14 @@
+[options]
+mode prove
+depth 64
+
+[engines]
+abc pdr
+
+[script]
+read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_motion_state_formal.v
+prep -top prod2u_p4_axis_motion_state_formal
+
+[files]
+../../src/rtl/prod2u_p4_axis_executor.v
+prod2u_p4_axis_motion_state_formal.v

+ 235 - 0
tests/formal/prod2u_p4_axis_motion_state_formal.v

@@ -0,0 +1,235 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_axis_motion_state_formal;
+    (* gclk *) reg clk;
+    reg rst_n = 1'b0;
+    reg past_valid = 1'b0;
+
+    reg [2:0] reverse_driver = 3'd0;
+    reg reverse_request_seen = 1'b0;
+    reg reverse_fall_seen = 1'b0;
+    reg reverse_transition_seen = 1'b0;
+    reg [3:0] reverse_low_ticks = 4'd0;
+    reg [4:0] reverse_age = 5'd0;
+
+    wire reverse_limit_active = reverse_driver == 3'd0;
+    wire reverse_jog_start = rst_n && (reverse_driver == 3'd0);
+    wire reverse_standard_start = rst_n &&
+        ((reverse_driver == 3'd1) || ((reverse_driver == 3'd2) && reverse_step));
+    wire reverse_standard_target_open = reverse_driver == 3'd1;
+    wire reverse_step;
+    wire reverse_dir;
+    wire reverse_busy;
+    wire reverse_position_valid;
+    wire [7:0] reverse_current;
+    wire [7:0] reverse_target;
+    wire reverse_close_dir;
+    wire reverse_fault;
+    wire [1:0] reverse_move_kind;
+    wire [12:0] reverse_remaining;
+    wire [2:0] reverse_axis_state;
+    wire reverse_jog_can_accept;
+    wire reverse_standard_can_accept;
+
+    reg [3:0] lock_driver = 4'd0;
+    reg lock_seen = 1'b0;
+    reg [5:0] lock_age = 6'd0;
+    wire lock_limit_active = lock_driver == 4'd0;
+    wire lock_jog_start = rst_n &&
+        ((lock_driver == 4'd0) || (lock_driver == 4'd5) || (lock_driver == 4'd7));
+    wire lock_standard_start = rst_n &&
+        ((lock_driver == 4'd1) || (lock_driver == 4'd3) || (lock_driver == 4'd7));
+    wire lock_standard_target_open = (lock_driver == 4'd1) || (lock_driver == 4'd7);
+    wire lock_step;
+    wire lock_dir;
+    wire lock_busy;
+    wire lock_position_valid;
+    wire [7:0] lock_current;
+    wire [7:0] lock_target;
+    wire lock_close_dir;
+    wire lock_fault;
+    wire [1:0] lock_move_kind;
+    wire [12:0] lock_remaining;
+    wire [2:0] lock_axis_state;
+    wire lock_jog_can_accept;
+    wire lock_standard_can_accept;
+
+    prod2u_p4_axis_executor #(
+        .HAS_LIMIT(1),
+        .STANDARD_STEPS(3),
+        .DIR_SETUP_US(2),
+        .SPEED0_HALF_US(2),
+        .SPEED1_HALF_US(2),
+        .SPEED2_HALF_US(2),
+        .SPEED3_HALF_US(2)
+    ) reverse_dut (
+        .clk(clk),
+        .rst_n(rst_n),
+        .tick_1us(1'b1),
+        .force_stop(1'b0),
+        .limit_active(reverse_limit_active),
+        .jog_start(reverse_jog_start),
+        .jog_dir(1'b0),
+        .jog_speed_code(2'd3),
+        .jog_steps(13'd1),
+        .standard_start(reverse_standard_start),
+        .standard_target_open(reverse_standard_target_open),
+        .mark_closed(1'b0),
+        .mark_close_dir(1'b0),
+        .step_out(reverse_step),
+        .dir_out(reverse_dir),
+        .busy(reverse_busy),
+        .position_valid(reverse_position_valid),
+        .current_aperture(reverse_current),
+        .target_aperture(reverse_target),
+        .close_dir(reverse_close_dir),
+        .fault(reverse_fault),
+        .move_kind(reverse_move_kind),
+        .remaining_steps(reverse_remaining),
+        .axis_state(reverse_axis_state),
+        .jog_can_accept(reverse_jog_can_accept),
+        .standard_can_accept(reverse_standard_can_accept)
+    );
+
+    prod2u_p4_axis_executor #(
+        .HAS_LIMIT(1),
+        .STANDARD_STEPS(3),
+        .DIR_SETUP_US(2),
+        .SPEED0_HALF_US(1),
+        .SPEED1_HALF_US(1),
+        .SPEED2_HALF_US(1),
+        .SPEED3_HALF_US(1)
+    ) lock_dut (
+        .clk(clk),
+        .rst_n(rst_n),
+        .tick_1us(1'b1),
+        .force_stop(1'b0),
+        .limit_active(lock_limit_active),
+        .jog_start(lock_jog_start),
+        .jog_dir(1'b0),
+        .jog_speed_code(2'd3),
+        .jog_steps(13'd2),
+        .standard_start(lock_standard_start),
+        .standard_target_open(lock_standard_target_open),
+        .mark_closed(1'b0),
+        .mark_close_dir(1'b0),
+        .step_out(lock_step),
+        .dir_out(lock_dir),
+        .busy(lock_busy),
+        .position_valid(lock_position_valid),
+        .current_aperture(lock_current),
+        .target_aperture(lock_target),
+        .close_dir(lock_close_dir),
+        .fault(lock_fault),
+        .move_kind(lock_move_kind),
+        .remaining_steps(lock_remaining),
+        .axis_state(lock_axis_state),
+        .jog_can_accept(lock_jog_can_accept),
+        .standard_can_accept(lock_standard_can_accept)
+    );
+
+    always @(posedge clk) begin
+        past_valid <= 1'b1;
+        rst_n <= 1'b1;
+
+        if (!rst_n) begin
+            reverse_driver <= 3'd0;
+            reverse_request_seen <= 1'b0;
+            reverse_fall_seen <= 1'b0;
+            reverse_transition_seen <= 1'b0;
+            reverse_low_ticks <= 4'd0;
+            reverse_age <= 5'd0;
+            lock_driver <= 4'd0;
+            lock_seen <= 1'b0;
+            lock_age <= 6'd0;
+        end else begin
+            case (reverse_driver)
+                3'd0: if (reverse_axis_state == 3'd1) reverse_driver <= 3'd1;
+                3'd1: reverse_driver <= 3'd2;
+                3'd2: if (reverse_step) reverse_driver <= 3'd3;
+                3'd3: if (reverse_axis_state == 3'd4) reverse_driver <= 3'd4;
+                default: reverse_driver <= reverse_driver;
+            endcase
+
+            if ((reverse_driver == 3'd2) && reverse_step) begin
+                reverse_request_seen <= 1'b1;
+                reverse_age <= 5'd0;
+            end else if (reverse_request_seen && !reverse_transition_seen && reverse_age != 5'h1f) begin
+                reverse_age <= reverse_age + 5'd1;
+            end
+            if (past_valid && reverse_request_seen && $past(reverse_step) && !reverse_step) begin
+                reverse_fall_seen <= 1'b1;
+                // The falling-edge cycle is the first observed low cycle.
+                reverse_low_ticks <= 4'd1;
+            end else if (reverse_fall_seen && !reverse_transition_seen && !reverse_step &&
+                         reverse_low_ticks != 4'hf) begin
+                reverse_low_ticks <= reverse_low_ticks + 4'd1;
+            end
+            if (past_valid && (reverse_axis_state == 3'd4) && $past(reverse_axis_state == 3'd2)) begin
+                reverse_transition_seen <= 1'b1;
+            end
+
+            case (lock_driver)
+                4'd0: if (lock_axis_state == 3'd1) lock_driver <= 4'd1;
+                4'd1: lock_driver <= 4'd2;
+                4'd2: if (lock_axis_state == 3'd3) lock_driver <= 4'd3;
+                4'd3: lock_driver <= 4'd4;
+                4'd4: if (lock_axis_state == 3'd6) lock_driver <= 4'd5;
+                4'd5: lock_driver <= 4'd6;
+                4'd6: if (lock_axis_state == 3'd7) lock_driver <= 4'd7;
+                default: lock_driver <= 4'd7;
+            endcase
+            if (lock_driver == 4'd5) begin
+                lock_age <= 6'd0;
+            end else if ((lock_driver >= 4'd6) && !lock_seen && lock_age != 6'h3f) begin
+                lock_age <= lock_age + 6'd1;
+            end
+            if (lock_axis_state == 3'd7) begin
+                lock_seen <= 1'b1;
+            end
+        end
+
+        if (past_valid && $past(rst_n)) begin
+            if (reverse_request_seen && !reverse_transition_seen &&
+                (reverse_axis_state == 3'd2)) begin
+                assert(reverse_dir == 1'b1);
+                assert(reverse_busy);
+            end
+            if ((reverse_axis_state == 3'd4) && $past(reverse_axis_state == 3'd2)) begin
+                assert(reverse_request_seen);
+                assert(reverse_fall_seen);
+                assert(reverse_low_ticks >= 4'd2);
+                assert(!reverse_step);
+                assert(!$past(reverse_step));
+                assert(reverse_dir == reverse_close_dir);
+                assert(reverse_remaining == 13'd3);
+            end
+            if (reverse_age >= 5'd12) begin
+                assert(reverse_transition_seen);
+            end
+
+            if (lock_age >= 6'd24) begin
+                assert(lock_seen);
+            end
+            if (lock_seen) begin
+                assert(lock_axis_state == 3'd7);
+                assert(!lock_busy);
+                assert(!lock_step);
+                assert(!lock_position_valid);
+                assert(lock_current == 8'hff);
+                assert(lock_target == 8'hff);
+                assert(lock_fault);
+                assert(!lock_jog_can_accept);
+                assert(!lock_standard_can_accept);
+            end
+            if ($past(lock_axis_state == 3'd7)) begin
+                assert(lock_axis_state == 3'd7);
+                assert(!lock_step);
+            end
+        end
+    end
+
+    wire unused = ^reverse_current ^ ^reverse_target ^ reverse_fault ^ ^reverse_move_kind ^
+        reverse_jog_can_accept ^ reverse_standard_can_accept ^ lock_dir ^ lock_close_dir ^
+        ^lock_move_kind ^ ^lock_remaining;
+endmodule

+ 90 - 3
tests/formal/prod2u_p4_axis_safety_formal.v

@@ -23,6 +23,9 @@ module prod2u_p4_axis_safety_formal;
     wire fault;
     wire [1:0] move_kind;
     wire [12:0] remaining_steps;
+    wire [2:0] axis_state;
+    wire jog_can_accept;
+    wire standard_can_accept;
     reg past_valid = 1'b0;
     reg [3:0] dir_stable_ticks = 4'd0;
     wire modeled_en_n = ~busy;
@@ -113,7 +116,10 @@ module prod2u_p4_axis_safety_formal;
         .close_dir(close_dir),
         .fault(fault),
         .move_kind(move_kind),
-        .remaining_steps(remaining_steps)
+        .remaining_steps(remaining_steps),
+        .axis_state(axis_state),
+        .jog_can_accept(jog_can_accept),
+        .standard_can_accept(standard_can_accept)
     );
 
     prod2u_p4_axis_executor #(
@@ -269,10 +275,88 @@ module prod2u_p4_axis_safety_formal;
         if (past_valid && $past(rst_n)) begin
             if (!busy) assert(!step_out);
             if (modeled_en_n) assert(!step_out);
+            case (axis_state)
+                3'd0: begin
+                    assert(!position_valid);
+                    assert(current_aperture == 8'hff);
+                    assert(target_aperture == 8'hff);
+                    assert(!fault);
+                end
+                3'd1: begin
+                    assert(position_valid);
+                    assert(current_aperture == 8'd0);
+                    assert(target_aperture == 8'd0);
+                    assert(!fault);
+                end
+                3'd2: begin
+                    assert(position_valid);
+                    assert(current_aperture == 8'hfe);
+                    assert((target_aperture == 8'd100) || (target_aperture == 8'd0));
+                    assert(!fault);
+                end
+                3'd3: begin
+                    assert(position_valid);
+                    assert(current_aperture == 8'd100);
+                    assert(target_aperture == 8'd100);
+                    assert(!fault);
+                end
+                3'd4: begin
+                    assert(position_valid);
+                    assert(current_aperture == 8'hfe);
+                    assert(target_aperture == 8'd0);
+                    assert(!fault);
+                end
+                3'd5: begin
+                    assert(position_valid);
+                    assert(current_aperture == 8'hfe);
+                    assert(target_aperture == 8'hfe);
+                    assert(!fault);
+                end
+                3'd6: begin
+                    assert(position_valid);
+                    assert(current_aperture == 8'hfe);
+                    assert(target_aperture == 8'd0);
+                    assert(!fault);
+                end
+                default: begin
+                    assert(!position_valid);
+                    assert(current_aperture == 8'hff);
+                    assert(target_aperture == 8'hff);
+                    assert(fault);
+                    assert(!busy);
+                    assert(!step_out);
+                    assert(!jog_can_accept);
+                    assert(!standard_can_accept);
+                end
+            endcase
+            if ($past(axis_state == 3'd7)) begin
+                assert(axis_state == 3'd7);
+            end
+            if (past_valid && dir_out != $past(dir_out)) begin
+                assert(!step_out);
+                assert(!$past(step_out));
+            end
+            if (axis_state == 3'd4 && busy) begin
+                assert(dir_out == close_dir);
+            end
+            if (axis_state == 3'd2 && busy) begin
+                assert(dir_out != close_dir);
+            end
             if ($past(force_stop && busy)) begin
                 assert(!busy);
                 assert(!step_out);
-                assert(!position_valid);
+                if ($past(axis_state == 3'd6)) begin
+                    assert(axis_state == 3'd7);
+                    assert(!position_valid);
+                    assert(fault);
+                end else if ($past(axis_state == 3'd0)) begin
+                    assert(axis_state == 3'd0);
+                    assert(!position_valid);
+                end else begin
+                    assert(axis_state == 3'd5);
+                    assert(position_valid);
+                    assert(current_aperture == 8'hfe);
+                end
             end
             if (step_out && !$past(step_out)) begin
                 assert(busy);
@@ -281,7 +365,9 @@ module prod2u_p4_axis_safety_formal;
             if ($past(busy && !force_stop &&
                       !(limit_active && ((move_kind == 2'd2) ||
                         ((move_kind == 2'd1) && target_aperture == 8'd0))))) begin
-                assert(dir_out == $past(dir_out));
+                if (!(axis_state == 3'd4 && $past(axis_state) == 3'd2)) begin
+                    assert(dir_out == $past(dir_out));
+                end
             end
             if (!position_valid) assert(current_aperture == 8'hff);
             if (!exact_busy) assert(!exact_step_out);
@@ -305,6 +391,7 @@ module prod2u_p4_axis_safety_formal;
     end
 
     wire unused_state = ^target_aperture ^ close_dir ^ fault ^ ^move_kind ^ ^remaining_steps ^
+        ^axis_state ^ jog_can_accept ^ standard_can_accept ^
         exact_position_valid ^ ^exact_current_aperture ^ ^exact_target_aperture ^ exact_close_dir ^
         exact_fault ^ ^exact_move_kind ^ ^exact_remaining_steps;
     wire unused_hub_state = hub_snapshot_result_valid ^ ^hub_snapshot_busy_mask ^

+ 7 - 6
tests/sim/prod2u_p4_axis_executor_xy_tb.v

@@ -379,8 +379,8 @@ module prod2u_p4_axis_executor_xy_tb;
         end
         limit_active = 1'b0;
         count_until_idle(rises);
-        if (close_dir !== 1'b0 || position_valid) begin
-            $display("reverse JOG changed close_dir or kept a synthetic position");
+        if (close_dir !== 1'b0 || !position_valid || current_aperture !== 8'hfe) begin
+            $display("reverse JOG changed close_dir or lost calibrated intermediate state");
             $fatal;
         end
         limit_active = 1'b1;
@@ -430,8 +430,9 @@ module prod2u_p4_axis_executor_xy_tb;
         count_until_idle(rises);
         pulse_standard(1'b0);
         count_until_idle(rises);
-        if (rises !== 8 || position_valid || !fault || step_out) begin
-            $display("missing close limit did not invalidate position rises=%0d", rises);
+        if (rises !== 8 || !position_valid || fault || step_out ||
+            current_aperture !== 8'hfe || target_aperture !== 8'd0) begin
+            $display("missing close limit did not enter recovery rises=%0d", rises);
             $fatal;
         end
 
@@ -467,8 +468,8 @@ module prod2u_p4_axis_executor_xy_tb;
         @(posedge clk);
         #1;
         force_stop = 1'b0;
-        if (busy || step_out || position_valid) begin
-            $display("force_stop did not stop low and invalidate a moving axis");
+        if (busy || step_out || !position_valid || current_aperture !== 8'hfe || fault) begin
+            $display("force_stop did not stop low in calibrated intermediate state");
             $fatal;
         end
 

+ 512 - 0
tests/sim/prod2u_p4_axis_motion_state_tb.v

@@ -0,0 +1,512 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_axis_motion_state_tb;
+    localparam [2:0] AXIS_UNCALIBRATED = 3'd0;
+    localparam [2:0] AXIS_CLOSED = 3'd1;
+    localparam [2:0] AXIS_OPENING = 3'd2;
+    localparam [2:0] AXIS_OPEN = 3'd3;
+    localparam [2:0] AXIS_CLOSING = 3'd4;
+    localparam [2:0] AXIS_INTERMEDIATE = 3'd5;
+    localparam [2:0] AXIS_RECOVERY = 3'd6;
+    localparam [2:0] AXIS_LOCKED_FAULT = 3'd7;
+
+    reg clk;
+    reg rst_n;
+    reg tick_1us;
+    reg force_stop;
+    reg limit_active;
+    reg jog_start;
+    reg jog_dir;
+    reg [1:0] jog_speed_code;
+    reg [12:0] jog_steps;
+    reg standard_start;
+    reg standard_target_open;
+    wire step_out;
+    wire dir_out;
+    wire busy;
+    wire position_valid;
+    wire [7:0] current_aperture;
+    wire [7:0] target_aperture;
+    wire close_dir;
+    wire fault;
+    wire [1:0] move_kind;
+    wire [12:0] remaining_steps;
+    wire [2:0] axis_state;
+    wire jog_can_accept;
+    wire standard_can_accept;
+
+    integer guard;
+    integer rises;
+    integer low_ticks;
+    integer setup_ticks;
+    reg previous_step;
+    reg saved_dir;
+    reg [12:0] saved_remaining;
+
+    prod2u_p4_axis_executor #(
+        .HAS_LIMIT(1),
+        .STANDARD_STEPS(4),
+        .DIR_SETUP_US(3),
+        .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(tick_1us),
+        .force_stop(force_stop),
+        .limit_active(limit_active),
+        .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),
+        .mark_closed(1'b0),
+        .mark_close_dir(1'b0),
+        .step_out(step_out),
+        .dir_out(dir_out),
+        .busy(busy),
+        .position_valid(position_valid),
+        .current_aperture(current_aperture),
+        .target_aperture(target_aperture),
+        .close_dir(close_dir),
+        .fault(fault),
+        .move_kind(move_kind),
+        .remaining_steps(remaining_steps),
+        .axis_state(axis_state),
+        .jog_can_accept(jog_can_accept),
+        .standard_can_accept(standard_can_accept)
+    );
+
+    initial begin
+        clk = 1'b0;
+        forever #5 clk = ~clk;
+    end
+
+    task reset_axis;
+        begin
+            rst_n = 1'b0;
+            tick_1us = 1'b1;
+            force_stop = 1'b0;
+            limit_active = 1'b0;
+            jog_start = 1'b0;
+            jog_dir = 1'b0;
+            jog_speed_code = 2'd3;
+            jog_steps = 13'd1;
+            standard_start = 1'b0;
+            standard_target_open = 1'b0;
+            repeat (4) @(negedge clk);
+            rst_n = 1'b1;
+            @(negedge clk);
+        end
+    endtask
+
+    task pulse_jog;
+        input direction;
+        input [12:0] steps;
+        begin
+            @(negedge clk);
+            jog_dir = direction;
+            jog_steps = steps;
+            jog_start = 1'b1;
+            @(posedge clk);
+            #1;
+            @(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;
+            @(posedge clk);
+            #1;
+            @(negedge clk);
+            standard_start = 1'b0;
+        end
+    endtask
+
+    task count_until_idle;
+        output integer rise_count;
+        begin
+            rise_count = 0;
+            guard = 0;
+            previous_step = step_out;
+            while (busy && guard < 300) begin
+                @(posedge clk);
+                #1;
+                if (!previous_step && step_out) begin
+                    rise_count = rise_count + 1;
+                end
+                previous_step = step_out;
+                guard = guard + 1;
+            end
+            if (busy) begin
+                $display("axis did not become idle");
+                $fatal;
+            end
+        end
+    endtask
+
+    task calibrate_closed;
+        input direction;
+        begin
+            limit_active = 1'b1;
+            jog_dir = direction;
+            #1;
+            if (!jog_can_accept) begin
+                $display("uncalibrated active limit did not allow zero-step calibration");
+                $fatal;
+            end
+            pulse_jog(direction, 13'd1);
+            if (busy || step_out || axis_state !== AXIS_CLOSED || close_dir !== direction ||
+                !position_valid || current_aperture !== 8'd0 || target_aperture !== 8'd0 || fault) begin
+                $display("zero-step closed calibration mismatch state=%0d", axis_state);
+                $fatal;
+            end
+        end
+    endtask
+
+    task open_to_endpoint;
+        begin
+            limit_active = 1'b0;
+            standard_target_open = 1'b1;
+            #1;
+            if (!standard_can_accept) begin
+                $display("closed axis did not accept OPEN");
+                $fatal;
+            end
+            pulse_standard(1'b1);
+            count_until_idle(rises);
+            if (rises !== 4 || axis_state !== AXIS_OPEN || !position_valid ||
+                current_aperture !== 8'd100 || target_aperture !== 8'd100 || fault) begin
+                $display("standard OPEN mismatch rises=%0d state=%0d", rises, axis_state);
+                $fatal;
+            end
+        end
+    endtask
+
+    initial begin
+        reset_axis();
+
+        if (axis_state !== AXIS_UNCALIBRATED || busy || step_out || position_valid || fault ||
+            current_aperture !== 8'hff || target_aperture !== 8'hff) begin
+            $display("reset did not expose the uncalibrated 0xFF state");
+            $fatal;
+        end
+        jog_dir = 1'b0;
+        #1;
+        if (!jog_can_accept) begin
+            $display("uncalibrated low limit rejected JOG direction 0");
+            $fatal;
+        end
+        pulse_jog(1'b0, 13'd2);
+        count_until_idle(rises);
+        if (rises !== 2 || axis_state !== AXIS_UNCALIBRATED || current_aperture !== 8'hff) begin
+            $display("uncalibrated direction 0 JOG changed calibration state");
+            $fatal;
+        end
+        jog_dir = 1'b1;
+        #1;
+        if (!jog_can_accept) begin
+            $display("uncalibrated low limit rejected JOG direction 1");
+            $fatal;
+        end
+        pulse_jog(1'b1, 13'd2);
+        count_until_idle(rises);
+        if (rises !== 2 || axis_state !== AXIS_UNCALIBRATED || current_aperture !== 8'hff) begin
+            $display("uncalibrated direction 1 JOG changed calibration state");
+            $fatal;
+        end
+
+        calibrate_closed(1'b0);
+        standard_target_open = 1'b0;
+        #1;
+        if (!standard_can_accept) begin
+            $display("CLOSED+CLOSE was not accepted as idempotent");
+            $fatal;
+        end
+        pulse_standard(1'b0);
+        if (busy || axis_state !== AXIS_CLOSED || remaining_steps !== 13'd0) begin
+            $display("CLOSED+CLOSE restarted motion");
+            $fatal;
+        end
+
+        jog_dir = 1'b0;
+        #1;
+        if (jog_can_accept) begin
+            $display("closed axis allowed another close-direction JOG");
+            $fatal;
+        end
+        jog_dir = 1'b1;
+        #1;
+        if (!jog_can_accept) begin
+            $display("closed axis rejected away-direction JOG");
+            $fatal;
+        end
+        pulse_jog(1'b1, 13'd2);
+        if (!busy || axis_state !== AXIS_INTERMEDIATE || !position_valid ||
+            current_aperture !== 8'hfe || target_aperture !== 8'hfe || close_dir !== 1'b0) begin
+            $display("away JOG did not preserve close direction in INTERMEDIATE");
+            $fatal;
+        end
+        limit_active = 1'b0;
+        count_until_idle(rises);
+        if (rises !== 2 || axis_state !== AXIS_INTERMEDIATE || close_dir !== 1'b0) begin
+            $display("away JOG completion lost INTERMEDIATE knowledge");
+            $fatal;
+        end
+
+        standard_target_open = 1'b1;
+        #1;
+        if (standard_can_accept) begin
+            $display("INTERMEDIATE accepted OPEN");
+            $fatal;
+        end
+        pulse_standard(1'b1);
+        if (busy || axis_state !== AXIS_INTERMEDIATE) begin
+            $display("rejected INTERMEDIATE+OPEN changed state");
+            $fatal;
+        end
+        standard_target_open = 1'b0;
+        #1;
+        if (!standard_can_accept) begin
+            $display("INTERMEDIATE rejected CLOSE");
+            $fatal;
+        end
+        pulse_standard(1'b0);
+        if (!busy || axis_state !== AXIS_CLOSING || current_aperture !== 8'hfe ||
+            target_aperture !== 8'd0 || remaining_steps !== 13'd4) begin
+            $display("INTERMEDIATE+CLOSE did not start closing");
+            $fatal;
+        end
+        tick_1us = 1'b0;
+        saved_remaining = remaining_steps;
+        pulse_standard(1'b0);
+        if (!busy || axis_state !== AXIS_CLOSING || remaining_steps !== saved_remaining) begin
+            $display("CLOSING+CLOSE restarted remaining_steps");
+            $fatal;
+        end
+        standard_target_open = 1'b1;
+        #1;
+        if (standard_can_accept) begin
+            $display("CLOSING accepted OPEN");
+            $fatal;
+        end
+        pulse_standard(1'b1);
+        if (axis_state !== AXIS_CLOSING || remaining_steps !== saved_remaining || dir_out !== close_dir) begin
+            $display("rejected CLOSING+OPEN changed motion");
+            $fatal;
+        end
+        tick_1us = 1'b1;
+        limit_active = 1'b1;
+        count_until_idle(rises);
+        if (axis_state !== AXIS_CLOSED || step_out || fault) begin
+            $display("close limit did not restore CLOSED");
+            $fatal;
+        end
+
+        limit_active = 1'b0;
+        pulse_standard(1'b1);
+        if (!busy || axis_state !== AXIS_OPENING || current_aperture !== 8'hfe ||
+            target_aperture !== 8'd100) begin
+            $display("CLOSED+OPEN did not enter OPENING");
+            $fatal;
+        end
+        tick_1us = 1'b0;
+        saved_remaining = remaining_steps;
+        saved_dir = dir_out;
+        pulse_standard(1'b1);
+        if (!busy || axis_state !== AXIS_OPENING || remaining_steps !== saved_remaining ||
+            dir_out !== saved_dir) begin
+            $display("OPENING+OPEN restarted motion");
+            $fatal;
+        end
+        tick_1us = 1'b1;
+        guard = 0;
+        while (!step_out && guard < 40) begin
+            @(posedge clk);
+            #1;
+            guard = guard + 1;
+        end
+        if (!step_out) begin
+            $display("OPENING never produced STEP high");
+            $fatal;
+        end
+        tick_1us = 1'b0;
+        saved_dir = dir_out;
+        pulse_standard(1'b0);
+        if (!busy || !step_out || dir_out !== saved_dir || target_aperture !== 8'd0) begin
+            $display("OPENING+CLOSE truncated STEP or changed DIR immediately");
+            $fatal;
+        end
+        standard_target_open = 1'b1;
+        #1;
+        if (standard_can_accept) begin
+            $display("pending OPEN-to-CLOSE reversal accepted OPEN");
+            $fatal;
+        end
+        tick_1us = 1'b1;
+        guard = 0;
+        while (step_out && guard < 20) begin
+            @(posedge clk);
+            #1;
+            guard = guard + 1;
+        end
+        if (step_out || dir_out !== saved_dir || !busy) begin
+            $display("safe reversal did not finish the current STEP before DIR change");
+            $fatal;
+        end
+        low_ticks = 0;
+        while (dir_out == saved_dir && low_ticks < 20) begin
+            @(posedge clk);
+            #1;
+            if (step_out) begin
+                $display("safe reversal raised STEP during final low interval");
+                $fatal;
+            end
+            low_ticks = low_ticks + 1;
+        end
+        if (dir_out === saved_dir || low_ticks < 2 || axis_state !== AXIS_CLOSING ||
+            remaining_steps !== 13'd4) begin
+            $display("safe reversal low/DIR mismatch low_ticks=%0d state=%0d", low_ticks, axis_state);
+            $fatal;
+        end
+        setup_ticks = 0;
+        while (!step_out && setup_ticks < 20) begin
+            @(posedge clk);
+            #1;
+            setup_ticks = setup_ticks + 1;
+        end
+        if (!step_out || setup_ticks < 3 || dir_out !== close_dir) begin
+            $display("safe reversal did not honor DIR setup setup_ticks=%0d", setup_ticks);
+            $fatal;
+        end
+        limit_active = 1'b1;
+        count_until_idle(rises);
+        if (axis_state !== AXIS_CLOSED || step_out) begin
+            $display("reversed close did not finish CLOSED and low");
+            $fatal;
+        end
+
+        open_to_endpoint();
+        standard_target_open = 1'b1;
+        #1;
+        if (!standard_can_accept) begin
+            $display("OPEN+OPEN was not accepted as idempotent");
+            $fatal;
+        end
+        pulse_standard(1'b1);
+        if (busy || axis_state !== AXIS_OPEN) begin
+            $display("OPEN+OPEN restarted motion");
+            $fatal;
+        end
+        jog_dir = 1'b1;
+        #1;
+        if (jog_can_accept) begin
+            $display("OPEN allowed another open-direction JOG");
+            $fatal;
+        end
+        jog_dir = 1'b0;
+        #1;
+        if (!jog_can_accept) begin
+            $display("OPEN rejected close-direction JOG");
+            $fatal;
+        end
+        pulse_jog(1'b0, 13'd2);
+        count_until_idle(rises);
+        if (rises !== 2 || axis_state !== AXIS_INTERMEDIATE || close_dir !== 1'b0 ||
+            current_aperture !== 8'hfe) begin
+            $display("OPEN reverse JOG did not enter INTERMEDIATE");
+            $fatal;
+        end
+
+        pulse_standard(1'b0);
+        count_until_idle(rises);
+        if (rises !== 4 || axis_state !== AXIS_RECOVERY || busy || fault ||
+            !position_valid || current_aperture !== 8'hfe || target_aperture !== 8'd0) begin
+            $display("missing close limit did not enter RECOVERY rises=%0d state=%0d", rises, axis_state);
+            $fatal;
+        end
+        jog_dir = 1'b1;
+        #1;
+        if (jog_can_accept) begin
+            $display("RECOVERY allowed away-direction JOG");
+            $fatal;
+        end
+        standard_target_open = 1'b0;
+        #1;
+        if (standard_can_accept) begin
+            $display("RECOVERY accepted a standard command");
+            $fatal;
+        end
+        jog_dir = 1'b0;
+        #1;
+        if (!jog_can_accept) begin
+            $display("RECOVERY rejected its one close-direction JOG");
+            $fatal;
+        end
+        pulse_jog(1'b0, 13'd3);
+        count_until_idle(rises);
+        if (rises !== 3 || axis_state !== AXIS_LOCKED_FAULT || busy || step_out ||
+            position_valid || !fault || current_aperture !== 8'hff || target_aperture !== 8'hff) begin
+            $display("failed recovery did not enter LOCKED_FAULT");
+            $fatal;
+        end
+        jog_dir = 1'b0;
+        standard_target_open = 1'b0;
+        #1;
+        if (jog_can_accept || standard_can_accept) begin
+            $display("LOCKED_FAULT exposed a motion command");
+            $fatal;
+        end
+        pulse_jog(1'b0, 13'd1);
+        pulse_standard(1'b0);
+        if (axis_state !== AXIS_LOCKED_FAULT || busy || step_out || !fault) begin
+            $display("LOCKED_FAULT did not remain motionless");
+            $fatal;
+        end
+
+        reset_axis();
+        calibrate_closed(1'b1);
+        open_to_endpoint();
+        pulse_standard(1'b0);
+        count_until_idle(rises);
+        if (axis_state !== AXIS_RECOVERY) begin
+            $display("second sequence did not enter RECOVERY");
+            $fatal;
+        end
+        pulse_jog(1'b1, 13'd160);
+        guard = 0;
+        while (!step_out && guard < 40) begin
+            @(posedge clk);
+            #1;
+            guard = guard + 1;
+        end
+        if (!step_out || !busy || axis_state !== AXIS_RECOVERY) begin
+            $display("recovery JOG did not start");
+            $fatal;
+        end
+        limit_active = 1'b1;
+        @(posedge clk);
+        #1;
+        if (!busy || step_out) begin
+            $display("recovery limit did not preserve the final low interval");
+            $fatal;
+        end
+        count_until_idle(rises);
+        if (axis_state !== AXIS_CLOSED || busy || step_out || fault || close_dir !== 1'b1 ||
+            current_aperture !== 8'd0) begin
+            $display("recovery limit did not restore CLOSED");
+            $fatal;
+        end
+
+        $display("PASS: prod2u_p4_axis_motion_state_tb");
+        $finish;
+    end
+endmodule

+ 17 - 10
tests/sim/prod2u_p4_limit_filter_tb.v

@@ -3,7 +3,7 @@
 module prod2u_p4_limit_filter_tb;
     reg clk;
     reg rst_n;
-    reg limit_n_raw;
+    reg limit_raw;
     wire limit_active;
     wire limit_ready;
     integer i;
@@ -14,7 +14,7 @@ module prod2u_p4_limit_filter_tb;
     ) dut (
         .clk(clk),
         .rst_n(rst_n),
-        .limit_n_raw(limit_n_raw),
+        .limit_raw(limit_raw),
         .limit_active(limit_active),
         .limit_ready(limit_ready)
     );
@@ -26,7 +26,7 @@ module prod2u_p4_limit_filter_tb;
 
     initial begin
         rst_n = 1'b0;
-        limit_n_raw = 1'b0;
+        limit_raw = 1'b0;
         repeat (3) @(negedge clk);
         rst_n = 1'b1;
         for (i = 0; i < 5; i = i + 1) begin
@@ -38,20 +38,20 @@ module prod2u_p4_limit_filter_tb;
         end
         // The two-flop synchronizer precedes the five stable samples.
         repeat (3) @(negedge clk);
-        if (!limit_ready || !limit_active) begin
-            $display("stable initial low input did not settle as an active limit");
+        if (!limit_ready || limit_active) begin
+            $display("stable initial low input did not settle as an inactive open limit");
             $fatal;
         end
 
-        limit_n_raw = 1'b1;
+        limit_raw = 1'b1;
         repeat (4) @(negedge clk);
-        if (!limit_active) begin
-            $display("stable low input released before five synchronized high samples");
+        if (limit_active) begin
+            $display("stable low input asserted before five synchronized high samples");
             $fatal;
         end
         repeat (4) @(negedge clk);
-        if (limit_active) begin
-            $display("stable high input did not release the limit");
+        if (!limit_active) begin
+            $display("stable high input did not assert the closed limit");
             $fatal;
         end
         if (!limit_ready) begin
@@ -59,6 +59,13 @@ module prod2u_p4_limit_filter_tb;
             $fatal;
         end
 
+        limit_raw = 1'b0;
+        repeat (8) @(negedge clk);
+        if (limit_active) begin
+            $display("stable low input did not release the closed limit");
+            $fatal;
+        end
+
         $display("PASS: prod2u_p4_limit_filter_tb");
         $finish;
     end

+ 36 - 9
tests/sim/prod2u_p4_limit_ready_motor_tb.v

@@ -3,8 +3,8 @@
 module prod2u_p4_limit_ready_motor_tb;
     reg clk;
     reg rst_n;
-    reg x_limit_n_raw;
-    reg y_limit_n_raw;
+    reg x_limit_raw;
+    reg y_limit_raw;
     reg jog_valid;
     reg [1:0] jog_axis;
     reg jog_dir;
@@ -27,7 +27,7 @@ module prod2u_p4_limit_ready_motor_tb;
     ) u_x_limit (
         .clk(clk),
         .rst_n(rst_n),
-        .limit_n_raw(x_limit_n_raw),
+        .limit_raw(x_limit_raw),
         .limit_active(x_limit_active),
         .limit_ready(x_limit_ready)
     );
@@ -38,7 +38,7 @@ module prod2u_p4_limit_ready_motor_tb;
     ) u_y_limit (
         .clk(clk),
         .rst_n(rst_n),
-        .limit_n_raw(y_limit_n_raw),
+        .limit_raw(y_limit_raw),
         .limit_active(y_limit_active),
         .limit_ready(y_limit_ready)
     );
@@ -91,8 +91,8 @@ module prod2u_p4_limit_ready_motor_tb;
 
     initial begin
         rst_n = 1'b0;
-        x_limit_n_raw = 1'b0;
-        y_limit_n_raw = 1'b1;
+        x_limit_raw = 1'b0;
+        y_limit_raw = 1'b0;
         jog_valid = 1'b0;
         jog_axis = 2'd0;
         jog_dir = 1'b0;
@@ -120,8 +120,35 @@ module prod2u_p4_limit_ready_motor_tb;
 
         // Account for synchronizer propagation after the required five samples.
         repeat (3) @(negedge clk);
-        if (!x_limit_ready || !x_limit_active) begin
-            $display("low limit did not become ready and active after debounce");
+        if (!x_limit_ready || x_limit_active) begin
+            $display("low open limit did not become ready and inactive after debounce");
+            $fatal;
+        end
+        jog_valid = 1'b1;
+        @(posedge clk);
+        #1;
+        jog_valid = 1'b0;
+        if (!jog_result_valid || !jog_accepted || en_n || step_out !== 3'b000 ||
+            status_payload[1 * 8 +: 3] !== 3'b000 ||
+            status_payload[3 * 8 +: 8] !== 8'hff) begin
+            $display("stable low open limit did not allow an uncalibrated X JOG");
+            $fatal;
+        end
+
+        i = 0;
+        while (!en_n && i < 50) begin
+            @(negedge clk);
+            i = i + 1;
+        end
+        if (!en_n || step_out !== 3'b000) begin
+            $display("uncalibrated X JOG did not finish low");
+            $fatal;
+        end
+
+        x_limit_raw = 1'b1;
+        repeat (8) @(negedge clk);
+        if (!x_limit_active) begin
+            $display("stable high input did not assert the X closed limit");
             $fatal;
         end
         jog_valid = 1'b1;
@@ -131,7 +158,7 @@ module prod2u_p4_limit_ready_motor_tb;
         if (!jog_result_valid || !jog_accepted || !en_n || step_out !== 3'b000 ||
             status_payload[1 * 8 +: 3] !== 3'b001 ||
             status_payload[3 * 8 +: 8] !== 8'd0) begin
-            $display("stable closing limit did not establish X zero position without a pulse");
+            $display("stable high closed limit did not establish X zero without a pulse");
             $fatal;
         end
 

+ 288 - 0
tests/sim/prod2u_p4_motor_hub_policy_tb.v

@@ -0,0 +1,288 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_motor_hub_policy_tb;
+    localparam [2:0] AXIS_CLOSED = 3'd1;
+    localparam [2:0] AXIS_OPENING = 3'd2;
+    localparam [2:0] AXIS_OPEN = 3'd3;
+    localparam [2:0] AXIS_CLOSING = 3'd4;
+    localparam [2:0] AXIS_INTERMEDIATE = 3'd5;
+    localparam [2:0] AXIS_RECOVERY = 3'd6;
+    localparam [2:0] AXIS_LOCKED_FAULT = 3'd7;
+
+    reg clk;
+    reg rst_n;
+    reg tick_1us;
+    reg force_stop;
+    reg x_limit_active;
+    reg y_limit_active;
+    reg x_limit_ready;
+    reg y_limit_ready;
+    reg snapshot_valid;
+    reg [23:0] snapshot_targets;
+    wire snapshot_result_valid;
+    wire [2:0] snapshot_busy_mask;
+    wire [2:0] snapshot_invalid_mask;
+    wire [2:0] snapshot_accepted_mask;
+    reg jog_valid;
+    reg [1:0] jog_axis;
+    reg jog_dir;
+    reg [1:0] jog_speed_code;
+    reg [12:0] jog_steps;
+    wire jog_result_valid;
+    wire jog_accepted;
+    reg mark_closed_valid;
+    reg mark_close_dir;
+    wire mark_result_valid;
+    wire mark_accepted;
+    wire [2:0] step_out;
+    wire [2:0] dir_out;
+    wire en_n;
+    wire [79:0] status_payload;
+
+    integer guard;
+    reg [12:0] saved_x_remaining;
+    reg [12:0] saved_y_remaining;
+    reg [1:0] saved_open_dirs;
+
+    prod2u_p4_motor_hub #(
+        .STANDARD_STEPS(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(tick_1us),
+        .force_stop(force_stop),
+        .disabled(1'b0),
+        .watchdog_timeout(1'b0),
+        .x_limit_active(x_limit_active),
+        .y_limit_active(y_limit_active),
+        .x_limit_ready(x_limit_ready),
+        .y_limit_ready(y_limit_ready),
+        .snapshot_valid(snapshot_valid),
+        .snapshot_targets(snapshot_targets),
+        .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),
+        .mark_closed_valid(mark_closed_valid),
+        .mark_close_dir(mark_close_dir),
+        .mark_result_valid(mark_result_valid),
+        .mark_accepted(mark_accepted),
+        .step_out(step_out),
+        .dir_out(dir_out),
+        .en_n(en_n),
+        .status_payload(status_payload)
+    );
+
+    initial begin
+        clk = 1'b0;
+        forever #5 clk = ~clk;
+    end
+
+    task pulse_jog_expect;
+        input [1:0] axis;
+        input direction;
+        input [12:0] steps;
+        input expected_accept;
+        begin
+            @(negedge clk);
+            jog_axis = axis;
+            jog_dir = direction;
+            jog_steps = steps;
+            jog_valid = 1'b1;
+            @(posedge clk);
+            #1;
+            if (!jog_result_valid || jog_accepted !== expected_accept) begin
+                $display("JOG policy mismatch axis=%0d dir=%0d accepted=%0d/%0d",
+                    axis, direction, jog_accepted, expected_accept);
+                $fatal;
+            end
+            @(negedge clk);
+            jog_valid = 1'b0;
+        end
+    endtask
+
+    task pulse_snapshot_expect;
+        input [7:0] x_target;
+        input [7:0] y_target;
+        input [7:0] z_target;
+        input [2:0] expected_busy;
+        input [2:0] expected_invalid;
+        input [2:0] expected_accepted;
+        begin
+            @(negedge clk);
+            snapshot_targets = {z_target, y_target, x_target};
+            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 policy mismatch busy=%03b/%03b invalid=%03b/%03b accepted=%03b/%03b",
+                    snapshot_busy_mask, expected_busy, snapshot_invalid_mask, expected_invalid,
+                    snapshot_accepted_mask, expected_accepted);
+                $fatal;
+            end
+            @(negedge clk);
+            snapshot_valid = 1'b0;
+        end
+    endtask
+
+    task wait_all_idle;
+        begin
+            guard = 0;
+            while (!en_n && guard < 300) begin
+                @(negedge clk);
+                guard = guard + 1;
+            end
+            if (!en_n || step_out !== 3'b000) begin
+                $display("hub did not finish idle and low");
+                $fatal;
+            end
+        end
+    endtask
+
+    initial begin
+        rst_n = 1'b0;
+        tick_1us = 1'b1;
+        force_stop = 1'b0;
+        x_limit_active = 1'b0;
+        y_limit_active = 1'b0;
+        x_limit_ready = 1'b1;
+        y_limit_ready = 1'b1;
+        snapshot_valid = 1'b0;
+        snapshot_targets = 24'd0;
+        jog_valid = 1'b0;
+        jog_axis = 2'd0;
+        jog_dir = 1'b0;
+        jog_speed_code = 2'd3;
+        jog_steps = 13'd1;
+        mark_closed_valid = 1'b0;
+        mark_close_dir = 1'b0;
+        repeat (4) @(negedge clk);
+        rst_n = 1'b1;
+        @(negedge clk);
+
+        x_limit_active = 1'b1;
+        pulse_jog_expect(2'd0, 1'b0, 13'd1, 1'b1);
+        y_limit_active = 1'b1;
+        pulse_jog_expect(2'd1, 1'b1, 13'd1, 1'b1);
+        mark_closed_valid = 1'b1;
+        mark_close_dir = 1'b0;
+        @(posedge clk);
+        #1;
+        mark_closed_valid = 1'b0;
+        if (!mark_result_valid || !mark_accepted || status_payload[15:8] !== 8'h07 ||
+            status_payload[47:24] !== 24'd0) begin
+            $display("initial XYZ calibration mismatch");
+            $fatal;
+        end
+
+        pulse_jog_expect(2'd0, 1'b0, 13'd1, 1'b0);
+        if (!en_n || step_out !== 3'b000 || dut.x_axis_state !== AXIS_CLOSED) begin
+            $display("blocked close JOG changed CLOSED state");
+            $fatal;
+        end
+        pulse_snapshot_expect(8'd0, 8'd0, 8'd0, 3'b000, 3'b000, 3'b111);
+
+        x_limit_active = 1'b0;
+        y_limit_active = 1'b0;
+        pulse_snapshot_expect(8'd100, 8'd100, 8'd0, 3'b000, 3'b000, 3'b111);
+        if (dut.x_axis_state !== AXIS_OPENING || dut.y_axis_state !== AXIS_OPENING) begin
+            $display("snapshot OPEN did not start X/Y together");
+            $fatal;
+        end
+        tick_1us = 1'b0;
+        saved_x_remaining = dut.x_remaining;
+        saved_y_remaining = dut.y_remaining;
+        saved_open_dirs = dir_out[1:0];
+        pulse_snapshot_expect(8'd100, 8'd100, 8'd0, 3'b000, 3'b000, 3'b111);
+        if (dut.x_remaining !== saved_x_remaining || dut.y_remaining !== saved_y_remaining ||
+            dir_out[1:0] !== saved_open_dirs) begin
+            $display("OPENING+OPEN restarted counters or changed DIR");
+            $fatal;
+        end
+
+        pulse_snapshot_expect(8'd0, 8'd0, 8'd0, 3'b000, 3'b000, 3'b111);
+        if (step_out[1:0] !== 2'b00 || dir_out[1:0] !== saved_open_dirs ||
+            status_payload[55:48] !== 8'd0 || status_payload[63:56] !== 8'd0) begin
+            $display("OPENING+CLOSE did not queue a safe reversal");
+            $fatal;
+        end
+        pulse_snapshot_expect(8'd100, 8'd100, 8'd0, 3'b011, 3'b000, 3'b100);
+        tick_1us = 1'b1;
+        guard = 0;
+        while ((dut.x_axis_state != AXIS_CLOSING || dut.y_axis_state != AXIS_CLOSING) && guard < 40) begin
+            @(negedge clk);
+            guard = guard + 1;
+        end
+        if (guard >= 40 || dir_out[0] !== 1'b0 || dir_out[1] !== 1'b1) begin
+            $display("queued X/Y reversal did not switch safely to closing");
+            $fatal;
+        end
+        x_limit_active = 1'b1;
+        y_limit_active = 1'b1;
+        wait_all_idle();
+        if (dut.x_axis_state !== AXIS_CLOSED || dut.y_axis_state !== AXIS_CLOSED) begin
+            $display("reversed X/Y close did not reach CLOSED");
+            $fatal;
+        end
+
+        x_limit_active = 1'b0;
+        y_limit_active = 1'b0;
+        pulse_snapshot_expect(8'd100, 8'd100, 8'd0, 3'b000, 3'b000, 3'b111);
+        wait_all_idle();
+        if (dut.x_axis_state !== AXIS_OPEN || dut.y_axis_state !== AXIS_OPEN ||
+            status_payload[39:24] !== {8'd100, 8'd100}) begin
+            $display("X/Y OPEN completion mismatch");
+            $fatal;
+        end
+
+        pulse_jog_expect(2'd0, 1'b1, 13'd1, 1'b0);
+        pulse_jog_expect(2'd0, 1'b0, 13'd2, 1'b1);
+        wait_all_idle();
+        if (dut.x_axis_state !== AXIS_INTERMEDIATE || status_payload[31:24] !== 8'hfe ||
+            status_payload[15:8] !== 8'h07) begin
+            $display("X close-direction JOG did not preserve calibrated INTERMEDIATE");
+            $fatal;
+        end
+
+        pulse_snapshot_expect(8'd100, 8'd100, 8'd0, 3'b000, 3'b001, 3'b110);
+        pulse_snapshot_expect(8'd0, 8'd100, 8'd0, 3'b000, 3'b000, 3'b111);
+        wait_all_idle();
+        if (dut.x_axis_state !== AXIS_RECOVERY || status_payload[31:24] !== 8'hfe ||
+            status_payload[55:48] !== 8'd0 || status_payload[73] !== 1'b0) begin
+            $display("missing X close limit did not expose RECOVERY 0xFE");
+            $fatal;
+        end
+        pulse_snapshot_expect(8'd0, 8'd100, 8'd0, 3'b000, 3'b001, 3'b110);
+        pulse_jog_expect(2'd0, 1'b1, 13'd1, 1'b0);
+        pulse_jog_expect(2'd0, 1'b0, 13'd2, 1'b1);
+        wait_all_idle();
+        if (dut.x_axis_state !== AXIS_LOCKED_FAULT || status_payload[8] !== 1'b0 ||
+            status_payload[31:24] !== 8'hff || status_payload[55:48] !== 8'hff ||
+            status_payload[72] !== 1'b1) begin
+            $display("failed X recovery did not expose LOCKED 0xFF+fault");
+            $fatal;
+        end
+        pulse_jog_expect(2'd0, 1'b0, 13'd1, 1'b0);
+        if (!en_n || step_out !== 3'b000 || dut.x_axis_state !== AXIS_LOCKED_FAULT) begin
+            $display("LOCKED X axis moved");
+            $fatal;
+        end
+
+        $display("PASS: prod2u_p4_motor_hub_policy_tb");
+        $finish;
+    end
+endmodule

+ 5 - 5
tests/sim/prod2u_p4_motor_hub_tb.v

@@ -294,7 +294,6 @@ module prod2u_p4_motor_hub_tb;
 
         x_limit_active = 1'b1;
         x_limit_ready = 1'b1;
-        pulse_jog(2'd0, 1'b0);
         y_limit_active = 1'b1;
         y_limit_ready = 1'b1;
         pulse_jog(2'd1, 1'b1);
@@ -339,9 +338,9 @@ module prod2u_p4_motor_hub_tb;
             $fatal;
         end
         opening_dirs = dir_out;
-        pulse_snapshot(8'd0, 8'd0, 8'd0, 3'b111, 3'b000, 3'b000);
+        pulse_snapshot(8'd100, 8'd100, 8'd100, 3'b100, 3'b000, 3'b011);
         if (dir_out !== opening_dirs || en_n) begin
-            $display("busy reverse target changed direction or stopped EN");
+            $display("idempotent OPEN changed direction or stopped EN");
             $fatal;
         end
         wait_all_idle();
@@ -373,8 +372,9 @@ module prod2u_p4_motor_hub_tb;
         @(posedge clk);
         #1;
         force_stop = 1'b0;
-        if (!en_n || step_out !== 3'b000 || status_payload[1 * 8 +: 3] !== 3'b110) begin
-            $display("force_stop did not invalidate only the moving X axis");
+        if (!en_n || step_out !== 3'b000 || status_payload[1 * 8 +: 3] !== 3'b111 ||
+            status_payload[3 * 8 +: 8] !== 8'hfe) begin
+            $display("force_stop did not preserve calibrated X intermediate state");
             $fatal;
         end
 

+ 15 - 15
tests/sim/prod2u_p4_normal_v3_core_tb.v

@@ -417,9 +417,9 @@ module prod2u_p4_normal_v3_core_tb;
 
         build_snapshot(8'd0);
         send_request(8'h07, 6'd34, request_payload);
-        expect_ack(1'b1, 8'h2a, 8'h16, 8'h07, 8'h00, 8'h01);
-        if (dir_out !== opening_dirs || en_n) begin
-            $display("busy reverse snapshot stopped or reversed a motor");
+        expect_ack(1'b1, 8'h2a, 8'h16, 8'h04, 8'h00, 8'h07);
+        if (dir_out[2] !== opening_dirs[2] || en_n) begin
+            $display("OPENING-to-CLOSE snapshot disturbed the busy Z axis");
             $fatal;
         end
 
@@ -437,9 +437,9 @@ module prod2u_p4_normal_v3_core_tb;
         request_payload[7:0] = 8'h37;
         send_request(8'h11, 6'd8, request_payload);
         expect_ack(1'b1, 8'h37, 8'h00, 8'h00, 8'h12, 8'h08);
-        if (!motion_status_valid || motion_status_payload[15:8] !== 8'h00 ||
-            motion_status_payload[47:24] !== 24'hffffff) begin
-            $display("GET_MOTOR_STATUS did not return the invalidated XYZ status");
+        if (!motion_status_valid || motion_status_payload[15:8] !== 8'h03 ||
+            motion_status_payload[47:24] !== {8'hff, 8'hfe, 8'hfe}) begin
+            $display("GET_MOTOR_STATUS did not preserve calibrated XY intermediate status");
             $fatal;
         end
         motion_status_ready = 1'b1;
@@ -517,21 +517,17 @@ module prod2u_p4_normal_v3_core_tb;
         end
 
         // A normal snapshot from DISABLE must still recover and arm the watchdog.
+        x_limit_active = 1'b1;
+        y_limit_active = 1'b1;
         build_snapshot(8'd0);
         send_request(8'h07, 6'd34, request_payload);
-        expect_ack(1'b1, 8'h2a, 8'h16, 8'h38, 8'h00, 8'h01);
+        expect_ack(1'b1, 8'h2a, 8'h16, 8'h20, 8'h00, 8'h07);
         if (disabled || watchdog_timeout) begin
             $display("snapshot did not recover from DISABLE");
             $fatal;
         end
 
-        // Calibrate all axes so the snapshot motor result is accepted before timeout.
-        x_limit_active = 1'b1;
-        send_jog(2'd0, 1'b0);
-        expect_ack(1'b1, 8'h35, 8'h00, 8'h00, 8'h00, 8'h00);
-        y_limit_active = 1'b1;
-        send_jog(2'd1, 1'b1);
-        expect_ack(1'b1, 8'h35, 8'h00, 8'h00, 8'h00, 8'h00);
+        // X/Y were zero-step closed by the active limits; calibrate protocol-reserved Z.
         send_mark_z(1'b0);
         expect_ack(1'b1, 8'h36, 8'h00, 8'h00, 8'h00, 8'h00);
         x_limit_active = 1'b0;
@@ -560,14 +556,18 @@ module prod2u_p4_normal_v3_core_tb;
         expect_watchdog_abort_ack(8'h2a);
 
         // A new snapshot that starts with watchdog_timeout already set is recovery, not a new race.
+        x_limit_active = 1'b1;
+        y_limit_active = 1'b1;
         build_snapshot(8'd0);
         send_request(8'h07, 6'd34, request_payload);
-        expect_ack(1'b1, 8'h2a, 8'h16, 8'h38, 8'h00, 8'h01);
+        expect_ack(1'b1, 8'h2a, 8'h16, 8'h20, 8'h00, 8'h07);
         if (disabled || watchdog_timeout) begin
             $display("snapshot did not recover from watchdog timeout");
             $fatal;
         end
 
+        x_limit_active = 1'b0;
+        y_limit_active = 1'b0;
         send_jog(2'd0, 1'b1);
         guard = 0;
         while (!dut.motor_jog_result_valid && guard < 20) begin

+ 6 - 6
tests/sim/prod2u_p4_normal_v3_top_e2e_tb.v

@@ -6,8 +6,8 @@ module prod2u_p4_normal_v3_top_e2e_tb;
     reg sys_clk;
     reg host_uart_rx;
     wire host_uart_tx;
-    reg x_limit_n;
-    reg y_limit_n;
+    reg x_limit_raw;
+    reg y_limit_raw;
     reg force_sda_stuck_low;
     reg i2c_scan_start;
     wire slave_sda_drive_low;
@@ -29,8 +29,8 @@ module prod2u_p4_normal_v3_top_e2e_tb;
     initial begin
         sys_clk = 1'b0;
         host_uart_rx = 1'b1;
-        x_limit_n = 1'b1;
-        y_limit_n = 1'b1;
+        x_limit_raw = 1'b0;
+        y_limit_raw = 1'b0;
         force_sda_stuck_low = 1'b0;
         i2c_scan_start = 1'b0;
     end
@@ -60,8 +60,8 @@ module prod2u_p4_normal_v3_top_e2e_tb;
         .y_dir(y_dir),
         .z_step(z_step),
         .z_dir(z_dir),
-        .x_limit_n(x_limit_n),
-        .y_limit_n(y_limit_n),
+        .x_limit_raw(x_limit_raw),
+        .y_limit_raw(y_limit_raw),
         .temp_scl(temp_scl),
         .temp_sda(temp_sda)
     );

+ 6 - 6
tests/sim/prod2u_p4_normal_v3_top_tb.v

@@ -10,8 +10,8 @@ module prod2u_p4_normal_v3_top_tb;
     wire dut_to_host;
     wire host_rx_valid;
     wire [7:0] host_rx_data;
-    reg x_limit_n;
-    reg y_limit_n;
+    reg x_limit_raw;
+    reg y_limit_raw;
     wire [23:0] ptc_pwm_out;
     wire [3:0] fan_pwm_out;
     wire solenoid_out;
@@ -101,8 +101,8 @@ module prod2u_p4_normal_v3_top_tb;
         .y_dir(y_dir),
         .z_step(z_step),
         .z_dir(z_dir),
-        .x_limit_n(x_limit_n),
-        .y_limit_n(y_limit_n),
+        .x_limit_raw(x_limit_raw),
+        .y_limit_raw(y_limit_raw),
         .temp_scl(temp_scl),
         .temp_sda(temp_sda)
     );
@@ -247,8 +247,8 @@ module prod2u_p4_normal_v3_top_tb;
         host_tx_valid = 1'b0;
         host_tx_data = 8'd0;
         host_rst_n = 1'b0;
-        x_limit_n = 1'b1;
-        y_limit_n = 1'b1;
+        x_limit_raw = 1'b0;
+        y_limit_raw = 1'b0;
         captured_count = 0;
 
         repeat (3) @(negedge clk);

+ 6 - 6
tests/sim/prod2u_p4_temperature_e2e_tb.v

@@ -14,8 +14,8 @@ module prod2u_p4_temperature_e2e_tb;
     wire dut_to_host;
     wire host_rx_valid;
     wire [7:0] host_rx_data;
-    reg x_limit_n;
-    reg y_limit_n;
+    reg x_limit_raw;
+    reg y_limit_raw;
     wire [23:0] ptc_pwm_out;
     wire [3:0] fan_pwm_out;
     wire solenoid_out;
@@ -100,8 +100,8 @@ module prod2u_p4_temperature_e2e_tb;
         .y_dir(y_dir),
         .z_step(z_step),
         .z_dir(z_dir),
-        .x_limit_n(x_limit_n),
-        .y_limit_n(y_limit_n),
+        .x_limit_raw(x_limit_raw),
+        .y_limit_raw(y_limit_raw),
         .temp_scl(temp_scl),
         .temp_sda(temp_sda)
     );
@@ -360,8 +360,8 @@ module prod2u_p4_temperature_e2e_tb;
         host_tx_valid = 1'b0;
         host_tx_data = 8'd0;
         host_rst_n = 1'b0;
-        x_limit_n = 1'b1;
-        y_limit_n = 1'b1;
+        x_limit_raw = 1'b0;
+        y_limit_raw = 1'b0;
         slave_sda_drive_low = 1'b0;
         captured_count = 0;
         request_length = 0;

+ 17 - 0
tests/unit/test_pid_harness.py

@@ -22,6 +22,7 @@ sys.path.insert(0, str(ROOT / "tools"))
 from pid_harness import (  # noqa: E402
     PROD2U_P4_NORMAL_V3_FORMAL_TARGETS,
     PROD2U_P4_NORMAL_V3_HDL_TARGETS,
+    PROD2U_P4_NORMAL_V3_UNIT_TESTS,
     TD_TOP_PROFILES,
     _patch_prod2u_staged_top,
     build_td_elaboration_plan,
@@ -67,6 +68,19 @@ from pid_harness import (  # noqa: E402
 
 
 class PidHarnessTests(unittest.TestCase):
+    def test_v3_unit_test_registry_only_references_existing_tests(self) -> None:
+        missing = [
+            name
+            for name in PROD2U_P4_NORMAL_V3_UNIT_TESTS
+            if not (ROOT / "tests" / "unit" / name).is_file()
+        ]
+
+        self.assertEqual(missing, [])
+        self.assertIn(
+            "test_prod2u_p4_normal_v3_resources.py",
+            PROD2U_P4_NORMAL_V3_UNIT_TESTS,
+        )
+
     def test_v3_unit_subprocess_exposes_both_repository_and_tools_import_roots(self) -> None:
         completed = __import__("subprocess").CompletedProcess(
             args=[], returncode=0, stdout="", stderr=""
@@ -831,6 +845,8 @@ endmodule
         self.assertNotIn("sha256", payload["td_tool"])
         self.assertNotIn("source_manifest_sha256", payload)
         self.assertEqual(payload["resource_gate"]["status"], "pass")
+        self.assertTrue(payload["resource_delta"]["advisory_only"])
+        self.assertFalse(payload["resource_delta"]["affects_build_status"])
         self.assertEqual(payload["timing_gate"]["status"], "pass")
         self.assertEqual(payload["syn"]["critical_warning_count"], 0)
         self.assertEqual(payload["phy"]["critical_warning_count"], 0)
@@ -1130,6 +1146,7 @@ endmodule
             "prod2u_p4_watchdog": "tests/formal/prod2u_p4_watchdog.sby",
             "prod2u_p4_core_watchdog_race": "tests/formal/prod2u_p4_core_watchdog_race.sby",
             "prod2u_p4_axis_safety": "tests/formal/prod2u_p4_axis_safety.sby",
+            "prod2u_p4_axis_motion_state": "tests/formal/prod2u_p4_axis_motion_state.sby",
             "prod2u_p4_i2c_release": "tests/formal/prod2u_p4_i2c_release.sby",
         }
         for name, sby in expected_formal.items():

+ 4 - 4
tests/unit/test_pin_inventory.py

@@ -330,8 +330,8 @@ class PinInventoryTests(unittest.TestCase):
         self.assertEqual(len(set(payload["assignments"].values())), 43)
         self.assertEqual(payload["conflict_check"]["status"], "pass")
         self.assertEqual(payload["conflict_check"]["errors"], [])
-        self.assertEqual(payload["pin_constraints"]["x_limit_n"]["pulltype"], "PULLUP")
-        self.assertEqual(payload["pin_constraints"]["y_limit_n"]["pulltype"], "PULLUP")
+        self.assertEqual(payload["pin_constraints"]["x_limit_raw"]["pulltype"], "PULLUP")
+        self.assertEqual(payload["pin_constraints"]["y_limit_raw"]["pulltype"], "PULLUP")
         self.assertEqual(payload["pin_constraints"]["temp_scl"]["pulltype"], "NONE")
         self.assertEqual(payload["pin_constraints"]["temp_sda"]["pulltype"], "NONE")
         self.assertEqual(
@@ -350,8 +350,8 @@ class PinInventoryTests(unittest.TestCase):
         self.assertEqual(payload["assignments"]["ptc_pwm_out[21]"], "R10")
         self.assertEqual(payload["assignments"]["fan_pwm_out[2]"], "B1")
         self.assertEqual(payload["assignments"]["solenoid_out"], "P5")
-        self.assertEqual(payload["assignments"]["x_limit_n"], "A11")
-        self.assertEqual(payload["assignments"]["y_limit_n"], "A5")
+        self.assertEqual(payload["assignments"]["x_limit_raw"], "A11")
+        self.assertEqual(payload["assignments"]["y_limit_raw"], "A5")
         self.assertEqual(payload["assignments"]["temp_scl"], "M8")
         self.assertEqual(payload["assignments"]["temp_sda"], "N9")
         self.assertEqual(payload["uart_assignments"]["host_uart_tx"]["fpga_ball"], "M10")

+ 108 - 6
tests/unit/test_prod2u_p4_normal_v3_gate.py

@@ -10,6 +10,7 @@ import tempfile
 import unittest
 from pathlib import Path
 from types import SimpleNamespace
+from unittest import mock
 
 
 ROOT = Path(__file__).resolve().parents[2]
@@ -54,8 +55,8 @@ def gate_args(root: Path, **overrides: object) -> SimpleNamespace:
         "confirm_ptc_load_disabled": True,
         "confirm_mechanical_travel_safe": True,
         "confirm_p5_active_high_closes_intake": True,
-        "confirm_ls1_x_closed_low": True,
-        "confirm_ls2_y_closed_low": True,
+        "confirm_ls1_x_closed_high": True,
+        "confirm_ls2_y_closed_high": True,
         "x_close_dir": 0,
         "y_close_dir": 1,
         "enable_temperature_test": False,
@@ -118,6 +119,107 @@ class DisableEndpoint:
 
 
 class Prod2UP4NormalV3GateTests(unittest.TestCase):
+    def test_xy_sequence_calibrates_before_any_away_jog(self) -> None:
+        cli = load_cli()
+        calls: list[tuple[object, ...]] = []
+        calibrated = SimpleNamespace(
+            status=SimpleNamespace(
+                position_valid_mask=0x03,
+                busy_mask=0,
+                current_xyz=(0, 0, 0xFF),
+            )
+        )
+
+        def fake_calibrate(_session, _events, *, axis, raw_dir, sleep):
+            calls.append(("calibrate", axis, raw_dir))
+            return calibrated
+
+        def fake_status(_session, _events, *, phase):
+            calls.append(("status", phase))
+            return calibrated
+
+        def fake_jog(_session, _events, *, phase, axis, raw_dir, speed_code, steps):
+            calls.append(("jog", axis, raw_dir, speed_code, steps))
+
+        def fake_wait(_session, _events, *, phase, sleep):
+            calls.append(("wait", phase))
+            return calibrated
+
+        with mock.patch.object(cli, "_calibrate_axis_until_limit", side_effect=fake_calibrate), \
+             mock.patch.object(cli, "_gate_motor_status", side_effect=fake_status), \
+             mock.patch.object(cli, "_gate_jog", side_effect=fake_jog), \
+             mock.patch.object(cli, "_wait_for_idle", side_effect=fake_wait), \
+             mock.patch.object(cli, "_confirm_operator_observation"):
+            stages: list[dict[str, object]] = []
+            cli._run_xy_calibration_then_jog(
+                object(),
+                [],
+                stages,
+                [],
+                x_close_dir=0,
+                y_close_dir=1,
+                sleep=lambda _seconds: None,
+                operator_observer=lambda *_args: {"status": "pass"},
+            )
+
+        self.assertEqual(calls[:3], [
+            ("calibrate", 0, 0),
+            ("calibrate", 1, 1),
+            ("status", "calibration-status"),
+        ])
+        self.assertEqual(
+            [call for call in calls if call[0] == "jog"],
+            [("jog", 0, 1, 2, 20), ("jog", 1, 0, 2, 20)],
+        )
+        self.assertEqual([stage["name"] for stage in stages], ["motor_calibration", "motor_jog"])
+        planned = cli.hardware_stage_plan(
+            enable_temperature_test=False,
+            ct7428_bus_confirmed=False,
+        )["stages"]
+        self.assertLess(planned.index("motor_calibration"), planned.index("motor_jog"))
+
+    def test_xy_sequence_returns_both_axes_closed_before_standard_open(self) -> None:
+        cli = load_cli()
+        axis_states = {0: "uncalibrated", 1: "uncalibrated"}
+
+        def status_result():
+            current_xy = tuple(
+                0 if axis_states[axis] == "closed" else 0xFE
+                for axis in (0, 1)
+            )
+            return SimpleNamespace(
+                status=SimpleNamespace(
+                    position_valid_mask=0x03,
+                    busy_mask=0,
+                    current_xyz=(*current_xy, 0xFF),
+                )
+            )
+
+        def fake_calibrate(_session, _events, *, axis, raw_dir, sleep):
+            axis_states[axis] = "closed"
+            return status_result()
+
+        def fake_jog(_session, _events, *, phase, axis, raw_dir, speed_code, steps):
+            axis_states[axis] = "intermediate"
+
+        with mock.patch.object(cli, "_calibrate_axis_until_limit", side_effect=fake_calibrate), \
+             mock.patch.object(cli, "_gate_motor_status", side_effect=lambda *_args, **_kwargs: status_result()), \
+             mock.patch.object(cli, "_gate_jog", side_effect=fake_jog), \
+             mock.patch.object(cli, "_wait_for_idle", side_effect=lambda *_args, **_kwargs: status_result()), \
+             mock.patch.object(cli, "_confirm_operator_observation"):
+            cli._run_xy_calibration_then_jog(
+                object(),
+                [],
+                [],
+                [],
+                x_close_dir=0,
+                y_close_dir=1,
+                sleep=lambda _seconds: None,
+                operator_observer=lambda *_args: {"status": "pass"},
+            )
+
+        self.assertEqual(axis_states, {0: "closed", 1: "closed"})
+
     def test_parser_requires_explicit_motor_directions_and_physical_facts(self) -> None:
         cli = load_cli()
 
@@ -135,8 +237,8 @@ class Prod2UP4NormalV3GateTests(unittest.TestCase):
                 "--confirm-ptc-load-disabled",
                 "--confirm-mechanical-travel-safe",
                 "--confirm-p5-active-high-closes-intake",
-                "--confirm-ls1-x-closed-low",
-                "--confirm-ls2-y-closed-low",
+                "--confirm-ls1-x-closed-high",
+                "--confirm-ls2-y-closed-high",
                 "--x-close-dir",
                 "0",
                 "--y-close-dir",
@@ -146,8 +248,8 @@ class Prod2UP4NormalV3GateTests(unittest.TestCase):
 
         self.assertEqual((args.x_close_dir, args.y_close_dir), (0, 1))
         self.assertTrue(args.confirm_p5_active_high_closes_intake)
-        self.assertTrue(args.confirm_ls1_x_closed_low)
-        self.assertTrue(args.confirm_ls2_y_closed_low)
+        self.assertTrue(args.confirm_ls1_x_closed_high)
+        self.assertTrue(args.confirm_ls2_y_closed_high)
 
     def test_missing_core_confirmation_fails_before_enumeration_serial_or_programming(self) -> None:
         cli = load_cli()

+ 93 - 6
tests/unit/test_prod2u_p4_normal_v3_model.py

@@ -211,7 +211,7 @@ class Prod2UP4NormalV3ModelTests(unittest.TestCase):
         self.assertEqual(subject.feed_stream(b"noise\x00\xff\xa5" + bytes(bad_crc)), [])
         self.assertEqual(subject.state_fingerprint(), before)
 
-    def test_disable_and_watchdog_restore_safe_outputs_and_invalidate_only_moving_axes(self) -> None:
+    def test_disable_and_watchdog_restore_safe_outputs_and_preserve_calibrated_intermediate_axes(self) -> None:
         subject = self.enabled_model()
         self.calibrate_all(subject)
         self.assertTrue(subject.apply_frame(OPEN_GOLDEN).accepted)
@@ -226,7 +226,9 @@ class Prod2UP4NormalV3ModelTests(unittest.TestCase):
         self.assertFalse(subject.disabled)
         self.assertTrue(subject.watchdog_timeout)
         self.assertTrue(subject.axes[0].position_valid)
-        self.assertFalse(subject.axes[1].position_valid)
+        self.assertTrue(subject.axes[1].position_valid)
+        self.assertEqual(subject.axes[1].state, model_v3.AXIS_INTERMEDIATE)
+        self.assertEqual(subject.axes[1].current, 0xFE)
         self.assertFalse(subject.axes[2].position_valid)
         self.assertEqual(subject.busy_mask, 0)
 
@@ -259,6 +261,82 @@ class Prod2UP4NormalV3ModelTests(unittest.TestCase):
         subject.complete_axis(2)
         self.assertFalse(subject.axes[2].position_valid)
 
+    def test_xy_jog_preserves_close_direction_and_locks_after_one_failed_recovery(self) -> None:
+        subject = self.enabled_model()
+        self.calibrate_all(subject)
+        axis = subject.axes[0]
+        self.assertEqual(axis.state, model_v3.AXIS_CLOSED)
+        self.assertEqual(axis.close_dir, 1)
+
+        close_again = subject.apply_frame(model_v3.GOLDEN_VECTORS["jog_x"], limit_active_mask=0b001)
+        self.assertFalse(close_again.accepted)
+        self.assertEqual(axis.state, model_v3.AXIS_CLOSED)
+
+        away = model_v3.encode_motion_frame(bytes((0x35, 0, 0, 3, 2, 0, 0, 0)))
+        self.assertTrue(subject.apply_frame(away, limit_active_mask=0b001).accepted)
+        self.assertEqual(axis.state, model_v3.AXIS_INTERMEDIATE)
+        self.assertTrue(axis.position_valid)
+        self.assertEqual((axis.current, axis.target), (0xFE, 0xFE))
+        self.assertEqual(axis.close_dir, 1)
+        subject.complete_axis(0)
+        self.assertEqual(axis.state, model_v3.AXIS_INTERMEDIATE)
+
+        self.assertTrue(subject.apply_frame(ENABLE_GOLDEN).accepted)
+        self.assertEqual(axis.state, model_v3.AXIS_CLOSING)
+        subject.complete_axis(0, limit_hit=False)
+        self.assertEqual(axis.state, model_v3.AXIS_RECOVERY)
+        self.assertEqual((axis.current, axis.target), (0xFE, 0))
+        self.assertFalse(axis.fault)
+
+        wrong_way = subject.apply_frame(away)
+        self.assertFalse(wrong_way.accepted)
+        recovery = model_v3.encode_motion_frame(bytes((0x35, 0, 1, 3, 160, 0, 0, 0)))
+        self.assertTrue(subject.apply_frame(recovery).accepted)
+        subject.complete_axis(0, limit_hit=False)
+        self.assertEqual(axis.state, model_v3.AXIS_LOCKED_FAULT)
+        self.assertFalse(axis.position_valid)
+        self.assertEqual((axis.current, axis.target), (0xFF, 0xFF))
+        self.assertTrue(axis.fault)
+        self.assertFalse(subject.apply_frame(recovery).accepted)
+
+    def test_xy_standard_idempotence_and_safe_reverse_policy(self) -> None:
+        subject = self.enabled_model()
+        self.calibrate_all(subject)
+        open_xy = model_v3.encode_snapshot_frame(
+            ptc_percent=(0,) * 24,
+            fan_percent=(30,) * 4,
+            solenoid=0,
+            xyz=(100, 100, 0),
+        )
+        close_all = ENABLE_GOLDEN
+
+        self.assertEqual(subject.apply_frame(close_all).status, model_v3.STATUS_OK)
+        self.assertEqual(subject.apply_frame(open_xy).status, model_v3.STATUS_OK)
+        self.assertEqual(subject.axes[0].state, model_v3.AXIS_OPENING)
+        self.assertEqual(subject.axes[1].state, model_v3.AXIS_OPENING)
+        subject.axes[0].remaining_steps = 123
+        subject.axes[1].remaining_steps = 456
+
+        idempotent_open = subject.apply_frame(open_xy)
+        self.assertEqual(idempotent_open.status, model_v3.STATUS_OK)
+        self.assertEqual(subject.axes[0].remaining_steps, 123)
+        self.assertEqual(subject.axes[1].remaining_steps, 456)
+
+        reverse_close = subject.apply_frame(close_all)
+        self.assertEqual(reverse_close.status, model_v3.STATUS_OK)
+        self.assertEqual(subject.axes[0].state, model_v3.AXIS_CLOSING)
+        self.assertEqual(subject.axes[1].state, model_v3.AXIS_CLOSING)
+        self.assertEqual(subject.axes[0].remaining_steps, model_v3.STANDARD_STEPS)
+        self.assertEqual(subject.axes[1].remaining_steps, model_v3.STANDARD_STEPS)
+
+        idempotent_close = subject.apply_frame(close_all)
+        self.assertEqual(idempotent_close.status, model_v3.STATUS_OK)
+        self.assertEqual(subject.axes[0].remaining_steps, model_v3.STANDARD_STEPS)
+        rejected_open = subject.apply_frame(open_xy)
+        self.assertEqual(rejected_open.status, model_v3.STATUS_PARTIAL)
+        self.assertEqual(rejected_open.detail & 0b011, 0b011)
+        self.assertEqual(subject.axes[0].state, model_v3.AXIS_CLOSING)
+
     def test_motor_status_ack_requires_followup_result_flag(self) -> None:
         subject = model_v3.NormalV3Model()
         request = model_v3.encode_motion_frame(bytes((0x37, 0, 0, 0, 0, 0, 0, 0)))
@@ -579,11 +657,20 @@ class Prod2UP4NormalV3ModelPropertyTests(unittest.TestCase):
 
         for axis in range(3):
             bit = 1 << axis
-            if busy_mask & bit or invalid_mask & bit:
-                jog = model_v3.encode_motion_frame(bytes((0x35, axis, 1, 0, 1, 0, 0, 0)))
+            if busy_mask & bit:
+                raw_dir = 1
+                if axis < 2:
+                    raw_dir = 1 - int(subject.axes[axis].close_dir or 0)
+                jog = model_v3.encode_motion_frame(bytes((0x35, axis, raw_dir, 0, 1, 0, 0, 0)))
                 self.assertTrue(subject.apply_frame(jog).accepted)
-                if invalid_mask & bit:
-                    subject.complete_axis(axis)
+            elif invalid_mask & bit:
+                if axis < 2:
+                    subject._set_xy_state(subject.axes[axis], model_v3.AXIS_LOCKED_FAULT)
+                else:
+                    subject.axes[axis].state = model_v3.AXIS_UNCALIBRATED
+                    subject.axes[axis].position_valid = False
+                    subject.axes[axis].current = model_v3.UNKNOWN_POSITION
+                    subject.axes[axis].target = model_v3.UNKNOWN_POSITION
 
         frame = model_v3.encode_snapshot_frame(
             ptc_percent=(ptc_value,) * 24,

+ 3 - 3
tests/unit/test_prod2u_p4_normal_v3_receipts.py

@@ -30,15 +30,15 @@ def valid_receipt(*, temperature_status: str = "not_run_bus_unconfirmed") -> dic
                 "com5_present": True,
                 "al_link_present": True,
                 "p5_active_high_closes_intake": True,
-                "ls1_x_closed_low": True,
-                "ls2_y_closed_low": True,
+                "ls1_x_closed_high": True,
+                "ls2_y_closed_high": True,
             },
         },
         {"name": "program_sram", "status": "pass"},
         {"name": "initial_disable", "status": "pass"},
         {"name": "boot_identity", "status": "pass"},
-        {"name": "motor_jog", "status": "pass"},
         {"name": "motor_calibration", "status": "pass"},
+        {"name": "motor_jog", "status": "pass"},
         {"name": "xy_open_close", "status": "pass"},
         {"name": "busy_partial", "status": "pass"},
         {"name": "watchdog", "status": "pass"},

+ 103 - 0
tests/unit/test_prod2u_p4_normal_v3_resources.py

@@ -0,0 +1,103 @@
+#!/usr/bin/env python3
+"""Tests for advisory-only Normal v3 TD resource deltas."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import re
+import sys
+import unittest
+from pathlib import Path
+
+
+sys.dont_write_bytecode = True
+ROOT = Path(__file__).resolve().parents[2]
+TOOLS = ROOT / "tools"
+BUILD_MODULE = TOOLS / "prod2u_p4_normal_v3_build.py"
+BASELINE = ROOT / "config" / "prod2u_p4_normal_v3_resource_baseline.json"
+
+
+def load_module(path: Path, name: str):
+    spec = importlib.util.spec_from_file_location(name, path)
+    if spec is None or spec.loader is None:
+        raise RuntimeError(f"cannot load module: {path}")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class NormalV3ResourceBaselineTests(unittest.TestCase):
+    def test_tracked_baseline_records_both_clean_builds(self) -> None:
+        self.assertTrue(BASELINE.is_file(), BASELINE)
+        payload = json.loads(BASELINE.read_text(encoding="utf-8"))
+
+        self.assertEqual(
+            payload["schema"],
+            "prod2u-p4-normal-v3-resource-baseline-v1",
+        )
+        self.assertEqual(payload["profile"], "prod2u_p4_normal_v3")
+        self.assertEqual(payload["device"], "EF2L45BG256B")
+        self.assertRegex(payload["snapshot_commit"], r"^[0-9a-f]{40}$")
+        self.assertTrue(payload["snapshot_commit"].startswith("c9cf6a5"))
+        self.assertEqual(
+            {sample["build_id"] for sample in payload["samples"]},
+            {"6A5AE72C", "6A5B30C9"},
+        )
+        self.assertEqual(payload["envelope"]["overall"]["lut"], {"min": 3047, "max": 3060})
+        self.assertEqual(payload["envelope"]["overall"]["reg"], {"min": 2475, "max": 2476})
+        self.assertEqual(payload["envelope"]["overall"]["packed_slices"], {"min": 1743, "max": 1748})
+        self.assertEqual(payload["envelope"]["overall"]["mslice"], {"min": 871, "max": 874})
+        self.assertEqual(payload["envelope"]["overall"]["bram"], {"min": 0, "max": 0})
+        self.assertEqual(payload["envelope"]["overall"]["dsp"], {"min": 0, "max": 0})
+        self.assertEqual(payload["envelope"]["overall"]["io"], {"min": 43, "max": 43})
+
+    def test_delta_report_is_advisory_and_uses_envelope_edges(self) -> None:
+        build = load_module(BUILD_MODULE, "prod2u_p4_normal_v3_build_resources")
+        self.assertTrue(hasattr(build, "create_resource_delta_report"))
+        baseline = json.loads(BASELINE.read_text(encoding="utf-8"))
+        resources = {
+            "utilization": {
+                "lut": {"used": 3100, "total": 4480, "percent": 69.2},
+                "reg": {"used": 2500, "total": 4480, "percent": 55.8},
+                "bram": {"used": 0, "total": 12, "percent": 0.0},
+                "dsp": {"used": 0, "total": 15, "percent": 0.0},
+                "pad": {"used": 43, "total": 202, "percent": 21.29},
+            },
+            "packing": {"mslice": 880, "lslice": 880, "total_slices": 1760},
+            "hierarchy": [
+                {"instance": "u_motors", "module": "prod2u_p4_motor_hub", "lut": 470, "seq": 240},
+                {"instance": "u_z_axis", "module": "prod2u_p4_axis_executor", "lut": 90, "seq": 64},
+            ],
+        }
+        timing = {
+            "fmax_mhz": 56.0,
+            "worst_setup_slack_ns": 22.0,
+            "worst_hold_slack_ns": 0.029,
+        }
+
+        report = build.create_resource_delta_report(
+            resources=resources,
+            timing=timing,
+            baseline=baseline,
+        )
+
+        self.assertEqual(report["schema"], "prod2u-p4-normal-v3-resource-delta-v1")
+        self.assertTrue(report["advisory_only"])
+        self.assertFalse(report["affects_build_status"])
+        self.assertEqual(report["overall"]["lut"]["delta_from_baseline_max"], 40)
+        self.assertEqual(report["overall"]["reg"]["delta_from_baseline_max"], 24)
+        self.assertEqual(report["overall"]["packed_slices"]["delta_from_baseline_max"], 12)
+        self.assertEqual(report["overall"]["mslice"]["delta_from_baseline_max"], 6)
+        self.assertEqual(report["hierarchy"]["u_motors"]["lut"]["delta_from_baseline_max"], 17)
+        self.assertEqual(report["hierarchy"]["u_z_axis"]["seq"]["delta_from_baseline_max"], 0)
+        self.assertAlmostEqual(report["timing"]["fmax_mhz"]["delta_from_baseline_min"], -1.637)
+        self.assertAlmostEqual(
+            report["timing"]["worst_hold_slack_ns"]["delta_from_baseline_min"],
+            -0.002,
+        )
+        self.assertFalse(any(re.search(r"limit|threshold", key, re.IGNORECASE) for key in report))
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 25 - 2
tests/unit/test_prod2u_p4_normal_v3_simplified_delivery.py

@@ -81,6 +81,21 @@ def write_pyserial_wheelhouse(root: Path) -> Path:
 
 
 class NormalV3BuildIdentityTests(unittest.TestCase):
+    def test_motion_status_contract_distinguishes_intermediate_and_unknown_positions(self) -> None:
+        contract = json.loads(HOST_CONTRACT.read_text(encoding="utf-8"))
+        schema = json.loads(
+            (ROOT / "schemas" / "prod2u_p4_normal_host_contract_v3.schema.json").read_text(
+                encoding="utf-8"
+            )
+        )
+
+        motion = contract["responses"]["motion_status"]
+        schema_motion = schema["properties"]["responses"]["const"]["motion_status"]
+        self.assertEqual(motion["position_values"], [0, 100, 254, 255])
+        self.assertEqual(motion["intermediate_position"], 254)
+        self.assertEqual(motion["unknown_position"], 255)
+        self.assertEqual(schema_motion, motion)
+
     def test_epoch_identity_is_cross_platform_and_contains_no_sha(self) -> None:
         build = load_module(BUILD_MODULE, "prod2u_p4_normal_v3_build")
 
@@ -396,8 +411,8 @@ class NormalV3DeliveryFolderTests(unittest.TestCase):
                 "--confirm-ptc-load-disabled",
                 "--confirm-mechanical-travel-safe",
                 "--confirm-p5-active-high-closes-intake",
-                "--confirm-ls1-x-closed-low",
-                "--confirm-ls2-y-closed-low",
+                "--confirm-ls1-x-closed-high",
+                "--confirm-ls2-y-closed-high",
                 "--x-close-dir",
                 "0",
                 "--y-close-dir",
@@ -410,6 +425,14 @@ class NormalV3DeliveryFolderTests(unittest.TestCase):
         self.assertFalse(hasattr(args, "operator_evidence"))
         self.assertFalse(hasattr(args, "fault_injection_approval"))
 
+        with self.assertRaises(SystemExit):
+            cli.build_parser().parse_args(
+                [
+                    "normal-actuator-temp-gate",
+                    "--confirm-ls1-x-closed-low",
+                ]
+            )
+
     def test_packager_creates_one_folder_without_zip_or_inventory(self) -> None:
         with tempfile.TemporaryDirectory() as temporary:
             root = Path(temporary)

+ 2 - 2
tests/unit/test_prod2u_p4_normal_v3_td_files.py

@@ -87,8 +87,8 @@ EXPECTED_PINS = {
     "y_dir": ("H14", "NONE"),
     "z_step": ("H12", "NONE"),
     "z_dir": ("F14", "NONE"),
-    "x_limit_n": ("A11", "PULLUP"),
-    "y_limit_n": ("A5", "PULLUP"),
+    "x_limit_raw": ("A11", "PULLUP"),
+    "y_limit_raw": ("A5", "PULLUP"),
     "temp_scl": ("M8", "NONE"),
     "temp_sda": ("N9", "NONE"),
 }

+ 16 - 0
tests/unit/test_prod2u_p4_protocol_v3.py

@@ -253,6 +253,22 @@ class Prod2UProfile4ProtocolV3Tests(unittest.TestCase):
         with self.assertRaisesRegex(ValueError, "reserved"):
             protocol.decode_motion_status(protocol.decode_frame(bytes(reserved_flags)))
 
+    def test_motion_status_preserves_calibrated_intermediate_positions(self) -> None:
+        wire = protocol.build_motion_status(
+            flags=0b0000_0011,
+            position_valid_mask=0b011,
+            busy_mask=0b001,
+            current_xyz=(0xFE, 0xFE, 0xFF),
+            target_xyz=(0, 0xFE, 0xFF),
+            fault_mask=0,
+        )
+
+        frame = protocol.decode_frame(wire)
+        self.assertEqual(frame.payload, b"\x03\x03\x01\xFE\xFE\xFF\x00\xFE\xFF\x00")
+        status = protocol.decode_motion_status(frame)
+        self.assertEqual(status.current_xyz, (0xFE, 0xFE, 0xFF))
+        self.assertEqual(status.target_xyz, (0, 0xFE, 0xFF))
+
     def test_temperature_response_is_one_sixty_one_byte_compact_frame(self) -> None:
         raw = tuple([0x0C80] * 9 + [0xFF80] * 9 + [0xFFFF] * 9)
         wire = protocol.build_temperature_response(raw)

+ 4 - 4
tests/unit/test_prod2u_p4_wrapper_v3.py

@@ -187,8 +187,8 @@ class Prod2UP4WrapperV3Tests(unittest.TestCase):
                         "-ConfirmPtcLoadDisabled",
                         "-ConfirmMechanicalTravelSafe",
                         "-ConfirmP5ActiveHighClosesIntake",
-                        "-ConfirmLs1XClosedLow",
-                        "-ConfirmLs2YClosedLow",
+                        "-ConfirmLs1XClosedHigh",
+                        "-ConfirmLs2YClosedHigh",
                         "-XCloseDir",
                         "0",
                         "-YCloseDir",
@@ -215,8 +215,8 @@ class Prod2UP4WrapperV3Tests(unittest.TestCase):
                         "--confirm-ptc-load-disabled",
                         "--confirm-mechanical-travel-safe",
                         "--confirm-p5-active-high-closes-intake",
-                        "--confirm-ls1-x-closed-low",
-                        "--confirm-ls2-y-closed-low",
+                        "--confirm-ls1-x-closed-high",
+                        "--confirm-ls2-y-closed-high",
                         "--enable-temperature-test",
                         "--confirm-ct7428-cpld-bus",
                         "--con91-raw-index",

+ 39 - 6
tools/pid_harness.py

@@ -27,6 +27,7 @@ sys.dont_write_bytecode = True
 from prod2u_build_identity import build_source_manifest, source_file_identity, validate_source_manifest
 from prod2u_p4_normal_v3_build import (
     BUILD_EPOCH_ENV as PROD2U_P4_BUILD_EPOCH_ENV,
+    create_resource_delta_report,
     load_or_create_build_identity,
     validate_build_identity,
 )
@@ -101,10 +102,9 @@ PROD2U_P4_NORMAL_V3_UNIT_TESTS = (
     "test_prod2u_p4_protocol_v3.py",
     "test_prod2u_p4_normal_v3_model.py",
     "test_prod2u_p4_cli_v3.py",
-    "test_prod2u_p4_hardware_gate_regressions.py",
     "test_prod2u_p4_normal_v3_receipts.py",
     "test_prod2u_p4_normal_v3_gate.py",
-    "test_prod2u_p4_program_seal.py",
+    "test_prod2u_p4_normal_v3_resources.py",
     "test_prod2u_programmer.py",
     "test_prod2u_programmer_runtime.py",
     "test_prod2u_programmer_process_audit.py",
@@ -119,9 +119,11 @@ PROD2U_P4_NORMAL_V3_HDL_TARGETS = {
     "prod2u_p4_pwm_outputs_tb",
     "prod2u_p4_limit_filter_tb",
     "prod2u_p4_limit_ready_motor_tb",
+    "prod2u_p4_axis_motion_state_tb",
     "prod2u_p4_axis_executor_xy_tb",
     "prod2u_p4_axis_executor_z_tb",
     "prod2u_p4_motor_hub_tb",
+    "prod2u_p4_motor_hub_policy_tb",
     "prod2u_p4_i2c_stop_start_read_tb",
     "prod2u_p4_ct7428_scan_tb",
     "prod2u_p4_temperature_frame_tx_tb",
@@ -142,6 +144,7 @@ PROD2U_P4_NORMAL_V3_FORMAL_TARGETS = {
     "prod2u_p4_core_disable_motor_safety",
     "prod2u_p4_axis_safety",
     "prod2u_p4_axis_limit_final_low",
+    "prod2u_p4_axis_motion_state",
     "prod2u_p4_i2c_release",
 }
 PROD2U_P4_NORMAL_V3_COCOTB_TARGETS = {
@@ -184,10 +187,10 @@ PROD2U_P4_NORMAL_V3_REQUIRED_PINS = {
     "motor_en_n": ("A10", "NONE"),
     "x_step": ("C11", "NONE"),
     "x_dir": ("B12", "NONE"),
-    "x_limit_n": ("A11", "PULLUP"),
+    "x_limit_raw": ("A11", "PULLUP"),
     "y_step": ("D15", "NONE"),
     "y_dir": ("H14", "NONE"),
-    "y_limit_n": ("A5", "PULLUP"),
+    "y_limit_raw": ("A5", "PULLUP"),
     "z_step": ("H12", "NONE"),
     "z_dir": ("F14", "NONE"),
     "temp_scl": ("M8", "NONE"),
@@ -437,6 +440,7 @@ TD_TOP_PROFILES = {
         "adc_file": "constraints/prod2u_p4_normal_v3.adc",
         "sdc_file": "constraints/prod2u_p4_normal_v3.sdc",
         "hardware_binding": "config/prod2u_p4_normal_v3_hw_binding.json",
+        "resource_baseline": "config/prod2u_p4_normal_v3_resource_baseline.json",
         "binding_schema": "prod2u-p4-normal-v3-hw-binding-v1",
         "binding_profile": "prod2u-p4-normal-actuator-temp-binary921-v3",
         "binding_policy": "descriptive",
@@ -1068,10 +1072,10 @@ def td_hardware_binding_gate(profile: Mapping[str, Any]) -> dict[str, Any]:
             "enable_n_ball": "A10",
             "x_step_ball": "C11",
             "x_dir_ball": "B12",
-            "x_limit_n_ball": "A11",
+            "x_limit_raw_ball": "A11",
             "y_step_ball": "D15",
             "y_dir_ball": "H14",
-            "y_limit_n_ball": "A5",
+            "y_limit_raw_ball": "A5",
             "z_step_ball": "H12",
             "z_dir_ball": "F14",
             "z_hardware_status": "not_connected_protocol_reserved",
@@ -1872,6 +1876,7 @@ def hdl_testbenches() -> list[dict[str, Any]]:
             ],
         },
         {"name": "prod2u_p4_axis_executor_xy_tb", "sources": ["src/rtl/prod2u_p4_axis_executor.v", "tests/sim/prod2u_p4_axis_executor_xy_tb.v"]},
+        {"name": "prod2u_p4_axis_motion_state_tb", "sources": ["src/rtl/prod2u_p4_axis_executor.v", "tests/sim/prod2u_p4_axis_motion_state_tb.v"]},
         {"name": "prod2u_p4_axis_executor_z_tb", "sources": ["src/rtl/prod2u_p4_axis_executor.v", "tests/sim/prod2u_p4_axis_executor_z_tb.v"]},
         {
             "name": "prod2u_p4_motor_hub_tb",
@@ -1881,6 +1886,14 @@ def hdl_testbenches() -> list[dict[str, Any]]:
                 "tests/sim/prod2u_p4_motor_hub_tb.v",
             ],
         },
+        {
+            "name": "prod2u_p4_motor_hub_policy_tb",
+            "sources": [
+                "src/rtl/prod2u_p4_axis_executor.v",
+                "src/rtl/prod2u_p4_motor_hub.v",
+                "tests/sim/prod2u_p4_motor_hub_policy_tb.v",
+            ],
+        },
         {"name": "prod2u_p4_i2c_stop_start_read_tb", "sources": ["src/rtl/prod2u_p4_i2c_stop_start_read.v", "tests/sim/prod2u_p4_i2c_stop_start_read_tb.v"]},
         {"name": "prod2u_p4_ct7428_scan_tb", "sources": ["src/rtl/prod2u_p4_ct7428_scan.v", "tests/sim/prod2u_p4_ct7428_scan_tb.v"]},
         {
@@ -2140,6 +2153,7 @@ def formal_targets() -> list[dict[str, Any]]:
         },
         {"name": "prod2u_p4_axis_safety", "sby": "tests/formal/prod2u_p4_axis_safety.sby"},
         {"name": "prod2u_p4_axis_limit_final_low", "sby": "tests/formal/prod2u_p4_axis_limit_final_low.sby"},
+        {"name": "prod2u_p4_axis_motion_state", "sby": "tests/formal/prod2u_p4_axis_motion_state.sby"},
         {"name": "prod2u_p4_i2c_release", "sby": "tests/formal/prod2u_p4_i2c_release.sby"},
     ]
 
@@ -5116,6 +5130,24 @@ def td_build_payload(
     if resources is not None:
         resources["packing"] = packing
     timing = parse_timing_report(phy_build / str(profile["timing_report"]))
+    resource_delta = None
+    if top == PROD2U_P4_NORMAL_V3_PROFILE:
+        baseline_path = ROOT / str(profile["resource_baseline"])
+        try:
+            baseline = json.loads(baseline_path.read_text(encoding="utf-8"))
+            resource_delta = create_resource_delta_report(
+                resources=resources,
+                timing=timing,
+                baseline=baseline,
+            )
+        except (OSError, ValueError, json.JSONDecodeError) as exc:
+            resource_delta = {
+                "schema": "prod2u-p4-normal-v3-resource-delta-v1",
+                "advisory_only": True,
+                "affects_build_status": False,
+                "available": False,
+                "reason": f"resource baseline unavailable: {exc}",
+            }
     resource_gate = td_resource_gate(
         resources,
         max_lut_percent=profile.get("max_lut_percent"),
@@ -5249,6 +5281,7 @@ def td_build_payload(
         "bitstream_sha256": bitstream_sha256,
         "resources": resources,
         "resource_gate": resource_gate,
+        "resource_delta": resource_delta,
         "timing": timing,
         "timing_gate": timing_gate,
         "error_summary": error_summary,

+ 6 - 6
tools/pin_inventory.py

@@ -114,8 +114,8 @@ PROD2U_P4_NORMAL_V3_ASSIGNMENTS = {
     "y_dir": "H14",
     "z_step": "H12",
     "z_dir": "F14",
-    "x_limit_n": "A11",
-    "y_limit_n": "A5",
+    "x_limit_raw": "A11",
+    "y_limit_raw": "A5",
     "temp_scl": "M8",
     "temp_sda": "N9",
 }
@@ -340,9 +340,9 @@ def _prod2u_p4_normal_v3_profile(inventory: dict[str, Any]) -> dict[str, Any]:
     assignment_rows: list[dict[str, Any]] = []
     pins_by_ball = _pin_by_ball(inventory)
 
-    input_signals = {"sys_clk", "host_uart_rx", "x_limit_n", "y_limit_n"}
+    input_signals = {"sys_clk", "host_uart_rx", "x_limit_raw", "y_limit_raw"}
     bidir_signals = {"temp_scl", "temp_sda"}
-    limit_signals = {"x_limit_n", "y_limit_n"}
+    limit_signals = {"x_limit_raw", "y_limit_raw"}
     i2c_signals = {"temp_scl", "temp_sda"}
     pin_constraints: dict[str, dict[str, Any]] = {}
 
@@ -433,10 +433,10 @@ def _prod2u_p4_normal_v3_profile(inventory: dict[str, Any]) -> dict[str, Any]:
             "enable_n_ball": "A10",
             "x_step_ball": "C11",
             "x_dir_ball": "B12",
-            "x_limit_n_ball": "A11",
+            "x_limit_raw_ball": "A11",
             "y_step_ball": "D15",
             "y_dir_ball": "H14",
-            "y_limit_n_ball": "A5",
+            "y_limit_raw_ball": "A5",
             "z_step_ball": "H12",
             "z_dir_ball": "F14",
             "z_hardware_status": "not_connected_protocol_reserved",

+ 4 - 4
tools/prod2u.ps1

@@ -35,8 +35,8 @@ param(
     [switch]$ConfirmPtcLoadDisabled,
     [switch]$ConfirmMechanicalTravelSafe,
     [switch]$ConfirmP5ActiveHighClosesIntake,
-    [switch]$ConfirmLs1XClosedLow,
-    [switch]$ConfirmLs2YClosedLow,
+    [switch]$ConfirmLs1XClosedHigh,
+    [switch]$ConfirmLs2YClosedHigh,
     [int]$XCloseDir = -1,
     [int]$YCloseDir = -1,
     [switch]$EnableTemperatureTest,
@@ -307,8 +307,8 @@ if ($Command -eq "set-all-outputs") {
     if ($ConfirmPtcLoadDisabled) { $arguments += "--confirm-ptc-load-disabled" }
     if ($ConfirmMechanicalTravelSafe) { $arguments += "--confirm-mechanical-travel-safe" }
     if ($ConfirmP5ActiveHighClosesIntake) { $arguments += "--confirm-p5-active-high-closes-intake" }
-    if ($ConfirmLs1XClosedLow) { $arguments += "--confirm-ls1-x-closed-low" }
-    if ($ConfirmLs2YClosedLow) { $arguments += "--confirm-ls2-y-closed-low" }
+    if ($ConfirmLs1XClosedHigh) { $arguments += "--confirm-ls1-x-closed-high" }
+    if ($ConfirmLs2YClosedHigh) { $arguments += "--confirm-ls2-y-closed-high" }
     if ($EnableTemperatureTest) { $arguments += "--enable-temperature-test" }
     if ($ConfirmCt7428CpldBus) { $arguments += "--confirm-ct7428-cpld-bus" }
     if ($Con91RawIndex -ge 0) { $arguments += @("--con91-raw-index", $Con91RawIndex) }

+ 117 - 58
tools/prod2u_p4_cli.py

@@ -311,8 +311,8 @@ def build_parser() -> argparse.ArgumentParser:
     gate.add_argument("--confirm-ptc-load-disabled", action="store_true")
     gate.add_argument("--confirm-mechanical-travel-safe", action="store_true")
     gate.add_argument("--confirm-p5-active-high-closes-intake", action="store_true")
-    gate.add_argument("--confirm-ls1-x-closed-low", action="store_true")
-    gate.add_argument("--confirm-ls2-y-closed-low", action="store_true")
+    gate.add_argument("--confirm-ls1-x-closed-high", action="store_true")
+    gate.add_argument("--confirm-ls2-y-closed-high", action="store_true")
     gate.add_argument("--x-close-dir", type=_bounded_int(0, 1), required=True)
     gate.add_argument("--y-close-dir", type=_bounded_int(0, 1), required=True)
     gate.add_argument("--enable-temperature-test", action="store_true")
@@ -356,8 +356,8 @@ def hardware_stage_plan(
         "initial_disable",
         "boot_identity",
         "baseline_status",
-        "motor_jog",
         "motor_calibration",
+        "motor_jog",
         "xy_open_close",
         "busy_partial",
         "watchdog",
@@ -1047,6 +1047,79 @@ def _calibrate_axis_until_limit(
     raise RuntimeError(f"axis {axis} did not reach its limit within 3200 steps")
 
 
+def _run_xy_calibration_then_jog(
+    session: NormalSession,
+    events: list[dict[str, Any]],
+    stages: list[dict[str, Any]],
+    observations: list[dict[str, Any]],
+    *,
+    x_close_dir: int,
+    y_close_dir: int,
+    sleep: Callable[[float], None],
+    operator_observer: Callable[[str, dict[str, Any]], Mapping[str, Any]] | None,
+) -> None:
+    start = len(events)
+    _calibrate_axis_until_limit(
+        session,
+        events,
+        axis=0,
+        raw_dir=x_close_dir,
+        sleep=sleep,
+    )
+    _calibrate_axis_until_limit(
+        session,
+        events,
+        axis=1,
+        raw_dir=y_close_dir,
+        sleep=sleep,
+    )
+    calibrated = _gate_motor_status(session, events, phase="calibration-status")
+    if (
+        calibrated.status.position_valid_mask != 0x03
+        or calibrated.status.busy_mask != 0
+        or calibrated.status.current_xyz != (0, 0, 0xFF)
+    ):
+        raise RuntimeError("XY calibration did not establish both closed positions")
+    stages.append(_stage("motor_calibration", events=_events_since(events, start)))
+
+    start = len(events)
+    for axis, close_dir, name in (
+        (0, x_close_dir, "x_jog_motion"),
+        (1, y_close_dir, "y_jog_motion"),
+    ):
+        _gate_jog(
+            session,
+            events,
+            phase=f"jog-{axis}",
+            axis=axis,
+            raw_dir=1 - close_dir,
+            speed_code=2,
+            steps=20,
+        )
+        _wait_for_idle(session, events, phase=f"jog-{axis}", sleep=sleep)
+        _confirm_operator_observation(
+            operator_observer,
+            observations,
+            stage=name,
+            context={"axis": axis, "speed_step_per_s": 100, "steps": 20},
+        )
+        _calibrate_axis_until_limit(
+            session,
+            events,
+            axis=axis,
+            raw_dir=close_dir,
+            sleep=sleep,
+        )
+    recalibrated = _gate_motor_status(session, events, phase="post-jog-calibration-status")
+    if (
+        recalibrated.status.position_valid_mask != 0x03
+        or recalibrated.status.busy_mask != 0
+        or recalibrated.status.current_xyz != (0, 0, 0xFF)
+    ):
+        raise RuntimeError("XY jog verification did not return both axes to closed positions")
+    stages.append(_stage("motor_jog", events=_events_since(events, start)))
+
+
 def _start_watchdog_motion(
     session: NormalSession,
     events: list[dict[str, Any]],
@@ -1148,8 +1221,8 @@ def _gate_preflight_failures(args: argparse.Namespace) -> list[str]:
         "confirm_ptc_load_disabled": "ptc_load_not_disabled",
         "confirm_mechanical_travel_safe": "mechanical_travel_not_confirmed",
         "confirm_p5_active_high_closes_intake": "p5_polarity_not_confirmed",
-        "confirm_ls1_x_closed_low": "ls1_x_closed_low_not_confirmed",
-        "confirm_ls2_y_closed_low": "ls2_y_closed_low_not_confirmed",
+        "confirm_ls1_x_closed_high": "ls1_x_closed_high_not_confirmed",
+        "confirm_ls2_y_closed_high": "ls2_y_closed_high_not_confirmed",
     }
     failures = [failure for field, failure in required.items() if getattr(args, field, False) is not True]
     for axis in ("x", "y"):
@@ -1231,8 +1304,8 @@ def run_normal_actuator_temp_gate(
             ptc_load_disabled=True,
             mechanical_travel_safe=True,
             p5_active_high_closes_intake=True,
-            ls1_x_closed_low=True,
-            ls2_y_closed_low=True,
+            ls1_x_closed_high=True,
+            ls2_y_closed_high=True,
             z_hardware="not_connected_protocol_reserved",
             planned_stages=plan["stages"],
         )
@@ -1437,52 +1510,16 @@ def run_normal_actuator_temp_gate(
                 )
             )
 
-        start = len(events)
-        for axis, close_dir, name in (
-            (0, int(args.x_close_dir), "x_jog_motion"),
-            (1, int(args.y_close_dir), "y_jog_motion"),
-        ):
-            _gate_jog(
-                session,
-                events,
-                phase=f"jog-{axis}",
-                axis=axis,
-                raw_dir=1 - close_dir,
-                speed_code=2,
-                steps=20,
-            )
-            _wait_for_idle(session, events, phase=f"jog-{axis}", sleep=sleep)
-            _confirm_operator_observation(
-                operator_observer,
-                observations,
-                stage=name,
-                context={"axis": axis, "speed_step_per_s": 100, "steps": 20},
-            )
-        stages.append(_stage("motor_jog", events=_events_since(events, start)))
-
-        start = len(events)
-        _calibrate_axis_until_limit(
+        _run_xy_calibration_then_jog(
             session,
             events,
-            axis=0,
-            raw_dir=int(args.x_close_dir),
-            sleep=sleep,
-        )
-        _calibrate_axis_until_limit(
-            session,
-            events,
-            axis=1,
-            raw_dir=int(args.y_close_dir),
+            stages,
+            observations,
+            x_close_dir=int(args.x_close_dir),
+            y_close_dir=int(args.y_close_dir),
             sleep=sleep,
+            operator_observer=operator_observer,
         )
-        calibrated = _gate_motor_status(session, events, phase="calibration-status")
-        if (
-            calibrated.status.position_valid_mask != 0x03
-            or calibrated.status.busy_mask != 0
-            or calibrated.status.current_xyz != (0, 0, 0xFF)
-        ):
-            raise RuntimeError("XY calibration did not establish both closed positions")
-        stages.append(_stage("motor_calibration", events=_events_since(events, start)))
 
         start = len(events)
         open_ack = _gate_snapshot(
@@ -1495,24 +1532,29 @@ def run_normal_actuator_temp_gate(
         if open_ack.ack.status != StatusCode.PARTIAL or open_ack.ack.detail != 0x20:
             raise RuntimeError("XY open did not preserve protocol-reserved Z as invalid")
         busy_status = _gate_motor_status(session, events, phase="open-busy")
-        if busy_status.status.busy_mask != 0x03:
+        if (
+            busy_status.status.busy_mask != 0x03
+            or busy_status.status.position_valid_mask != 0x03
+            or busy_status.status.current_xyz[:2] != (0xFE, 0xFE)
+            or busy_status.status.target_xyz != (100, 100, 0xFF)
+        ):
             raise RuntimeError("XY open did not start both connected axes")
         partial_ack = _gate_snapshot(
             session,
             events,
-            phase="busy-partial",
+            phase="busy-idempotent-open",
             solenoid=0,
-            xyz=(0, 0, 0),
+            xyz=(100, 100, 0),
         )
-        if partial_ack.ack.status != StatusCode.PARTIAL or partial_ack.ack.detail != 0x23:
-            raise RuntimeError("busy reverse target did not return XY busy plus Z invalid PARTIAL")
-        after_partial = _gate_motor_status(session, events, phase="busy-partial-status")
+        if partial_ack.ack.status != StatusCode.PARTIAL or partial_ack.ack.detail != 0x20:
+            raise RuntimeError("idempotent XY OPEN did not preserve only Z as invalid")
+        after_partial = _gate_motor_status(session, events, phase="busy-idempotent-open-status")
         if after_partial.status.busy_mask != 0x03 or after_partial.status.target_xyz != (100, 100, 0xFF):
-            raise RuntimeError("busy reverse target changed active XY motion")
+            raise RuntimeError("idempotent XY OPEN changed active motion")
         stages.append(
             _stage(
                 "busy_partial",
-                events=[event for event in _events_since(events, start) if event["phase"].startswith("busy-partial")],
+                events=[event for event in _events_since(events, start) if event["phase"].startswith("busy-idempotent")],
             )
         )
         opened = _wait_for_idle(session, events, phase="open-xy", sleep=sleep)
@@ -1527,6 +1569,22 @@ def run_normal_actuator_temp_gate(
         )
         if close_ack.ack.status != StatusCode.PARTIAL or close_ack.ack.detail != 0x20:
             raise RuntimeError("XY close did not preserve protocol-reserved Z as invalid")
+        rejected_open_ack = _gate_snapshot(
+            session,
+            events,
+            phase="closing-reject-open",
+            solenoid=0,
+            xyz=(100, 100, 0),
+        )
+        if rejected_open_ack.ack.status != StatusCode.PARTIAL or rejected_open_ack.ack.detail != 0x23:
+            raise RuntimeError("CLOSING-to-OPEN did not report XY busy plus Z invalid")
+        after_rejected_open = _gate_motor_status(session, events, phase="closing-reject-open-status")
+        if (
+            after_rejected_open.status.busy_mask != 0x03
+            or after_rejected_open.status.current_xyz[:2] != (0xFE, 0xFE)
+            or after_rejected_open.status.target_xyz != (0, 0, 0xFF)
+        ):
+            raise RuntimeError("rejected CLOSING-to-OPEN changed active XY close motion")
         closed = _wait_for_idle(session, events, phase="close-xy", sleep=sleep)
         if closed.status.current_xyz != (0, 0, 0xFF):
             raise RuntimeError("XY close did not complete")
@@ -1552,7 +1610,8 @@ def run_normal_actuator_temp_gate(
         if (
             elapsed_ms < 4900
             or watchdog_motor.status.busy_mask != 0
-            or watchdog_motor.status.position_valid_mask & 0x02
+            or not (watchdog_motor.status.position_valid_mask & 0x02)
+            or watchdog_motor.status.current_xyz[1] != 0xFE
             or (watchdog_motor.status.flags & 0x0C) != 0x0C
             or not (watchdog_ack.ack.detail & 0x02)
             or watchdog_ack.ack.state_hash16 != SAFE_STATE_HASH16

+ 118 - 0
tools/prod2u_p4_normal_v3_build.py

@@ -19,6 +19,7 @@ SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
 BUILD_IDENTITY_SCHEMA = "prod2u-p4-normal-v3-build-identity-v1"
 BUILD_INFO_SCHEMA = "prod2u-p4-normal-v3-build-info-v1"
 COMPACT_TD_RECEIPT_SCHEMA = "prod2u-p4-normal-v3-td-build-compact-receipt-v1"
+RESOURCE_DELTA_SCHEMA = "prod2u-p4-normal-v3-resource-delta-v1"
 BUILD_EPOCH_ENV = "PROD2U_P4_BUILD_EPOCH"
 TARGET_DEVICE = "EF2L45BG256B"
 
@@ -222,6 +223,123 @@ def verify_bitstream(
     }
 
 
+def _resource_delta(value: object, envelope: object) -> dict[str, Any] | None:
+    if not isinstance(value, (int, float)) or isinstance(value, bool):
+        return None
+    if not isinstance(envelope, Mapping):
+        return None
+    minimum = envelope.get("min")
+    maximum = envelope.get("max")
+    if not isinstance(minimum, (int, float)) or isinstance(minimum, bool):
+        return None
+    if not isinstance(maximum, (int, float)) or isinstance(maximum, bool):
+        return None
+    return {
+        "observed": value,
+        "baseline_min": minimum,
+        "baseline_max": maximum,
+        "delta_from_baseline_max": value - maximum,
+    }
+
+
+def _timing_delta(value: object, envelope: object) -> dict[str, Any] | None:
+    delta = _resource_delta(value, envelope)
+    if delta is None:
+        return None
+    delta["delta_from_baseline_min"] = delta["observed"] - delta["baseline_min"]
+    return delta
+
+
+def create_resource_delta_report(
+    *,
+    resources: Mapping[str, Any] | None,
+    timing: Mapping[str, Any] | None,
+    baseline: Mapping[str, Any],
+) -> dict[str, Any]:
+    envelope = baseline.get("envelope")
+    if not isinstance(envelope, Mapping):
+        raise ValueError("resource baseline envelope is missing")
+    overall_envelope = envelope.get("overall")
+    timing_envelope = envelope.get("timing")
+    hierarchy_envelope = envelope.get("hierarchy")
+    if not isinstance(overall_envelope, Mapping):
+        raise ValueError("resource baseline overall envelope is missing")
+    if not isinstance(timing_envelope, Mapping):
+        raise ValueError("resource baseline timing envelope is missing")
+    if not isinstance(hierarchy_envelope, Mapping):
+        raise ValueError("resource baseline hierarchy envelope is missing")
+
+    utilization = resources.get("utilization") if isinstance(resources, Mapping) else None
+    packing = resources.get("packing") if isinstance(resources, Mapping) else None
+    overall_values: dict[str, object] = {}
+    if isinstance(utilization, Mapping):
+        for output_name, source_name in (
+            ("lut", "lut"),
+            ("reg", "reg"),
+            ("bram", "bram"),
+            ("dsp", "dsp"),
+            ("io", "pad"),
+        ):
+            item = utilization.get(source_name)
+            if isinstance(item, Mapping):
+                overall_values[output_name] = item.get("used")
+    if isinstance(packing, Mapping):
+        overall_values["packed_slices"] = packing.get("total_slices")
+        overall_values["mslice"] = packing.get("mslice")
+
+    overall: dict[str, Any] = {}
+    for name, value in overall_values.items():
+        delta = _resource_delta(value, overall_envelope.get(name))
+        if delta is not None:
+            overall[name] = delta
+
+    timing_report: dict[str, Any] = {}
+    if isinstance(timing, Mapping):
+        for name in (
+            "fmax_mhz",
+            "worst_setup_slack_ns",
+            "worst_hold_slack_ns",
+        ):
+            delta = _timing_delta(timing.get(name), timing_envelope.get(name))
+            if delta is not None:
+                timing_report[name] = delta
+
+    observed_hierarchy: dict[str, Mapping[str, Any]] = {}
+    if isinstance(resources, Mapping):
+        rows = resources.get("hierarchy")
+        if isinstance(rows, list):
+            observed_hierarchy = {
+                str(row.get("instance")): row
+                for row in rows
+                if isinstance(row, Mapping) and isinstance(row.get("instance"), str)
+            }
+    hierarchy: dict[str, Any] = {}
+    for instance, instance_envelope in hierarchy_envelope.items():
+        if not isinstance(instance_envelope, Mapping):
+            continue
+        observed = observed_hierarchy.get(str(instance))
+        if observed is None:
+            continue
+        metrics: dict[str, Any] = {}
+        for name in ("lut", "seq"):
+            delta = _resource_delta(observed.get(name), instance_envelope.get(name))
+            if delta is not None:
+                metrics[name] = delta
+        if metrics:
+            hierarchy[str(instance)] = metrics
+
+    return {
+        "schema": RESOURCE_DELTA_SCHEMA,
+        "advisory_only": True,
+        "affects_build_status": False,
+        "baseline_schema": baseline.get("schema"),
+        "snapshot_commit": baseline.get("snapshot_commit"),
+        "overall": overall,
+        "timing": timing_report,
+        "hierarchy": hierarchy,
+    }
+
+
 def create_compact_td_receipt(value: Mapping[str, Any]) -> dict[str, Any]:
     if value.get("status") != "pass":
         raise ValueError("TD build must pass before creating the compact receipt")

+ 203 - 81
tools/prod2u_p4_normal_v3_model.py

@@ -51,11 +51,21 @@ FAN_COUNT = 4
 AXIS_COUNT = 3
 TEMPERATURE_COUNT = 27
 UNKNOWN_POSITION = 0xFF
+INTERMEDIATE_POSITION = 0xFE
 STANDARD_STEPS = 3200
 SAFE_PTC = (0,) * PTC_COUNT
 SAFE_FAN = (30,) * FAN_COUNT
 SAFE_SOLENOID = 0
 
+AXIS_UNCALIBRATED = "uncalibrated"
+AXIS_CLOSED = "closed"
+AXIS_OPENING = "opening"
+AXIS_OPEN = "open"
+AXIS_CLOSING = "closing"
+AXIS_INTERMEDIATE = "intermediate"
+AXIS_RECOVERY = "recovery"
+AXIS_LOCKED_FAULT = "locked_fault"
+
 LEGACY_P4_ASSET_PATHS = (
     "src/rtl/prod2u_p4_host_rx.v",
     "src/rtl/prod2u_p4_tx_scheduler.v",
@@ -108,6 +118,7 @@ class ModelFrameError(ValueError):
 
 @dataclass
 class AxisState:
+    state: str = AXIS_UNCALIBRATED
     position_valid: bool = False
     busy: bool = False
     current: int = UNKNOWN_POSITION
@@ -342,6 +353,7 @@ class NormalV3Model:
         axis_values = tuple(
             (
                 axis.position_valid,
+                axis.state,
                 axis.busy,
                 axis.current,
                 axis.target,
@@ -379,6 +391,49 @@ class NormalV3Model:
             "axes": [asdict(axis) for axis in self.axes],
         }
 
+    @staticmethod
+    def _set_xy_state(axis: AxisState, state: str) -> None:
+        axis.state = state
+        axis.fault = state == AXIS_LOCKED_FAULT
+        if state in (AXIS_UNCALIBRATED, AXIS_LOCKED_FAULT):
+            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 = True
+            axis.current = INTERMEDIATE_POSITION
+            axis.target = 100
+        elif state == AXIS_CLOSING:
+            axis.position_valid = True
+            axis.current = INTERMEDIATE_POSITION
+            axis.target = 0
+        elif state == AXIS_INTERMEDIATE:
+            axis.position_valid = True
+            axis.current = INTERMEDIATE_POSITION
+            axis.target = INTERMEDIATE_POSITION
+        elif state == AXIS_RECOVERY:
+            axis.position_valid = True
+            axis.current = INTERMEDIATE_POSITION
+            axis.target = 0
+        else:
+            raise ValueError(f"unsupported XY axis state: {state}")
+
+    @staticmethod
+    def _clear_motion(axis: AxisState) -> None:
+        axis.busy = False
+        axis.move_kind = "idle"
+        axis.remaining_steps = 0
+        axis.limit_stop_enabled = False
+        axis.capture_close_dir_on_limit = False
+
     def _result(
         self,
         *,
@@ -414,16 +469,19 @@ class NormalV3Model:
 
     def _force_safe(self, *, disabled: bool, watchdog_timeout: bool) -> None:
         self._safe_outputs()
-        for axis in self.axes:
+        for index, axis in enumerate(self.axes):
             if axis.busy:
-                axis.position_valid = False
-                axis.current = UNKNOWN_POSITION
-                axis.target = UNKNOWN_POSITION
-            axis.busy = False
-            axis.move_kind = "idle"
-            axis.remaining_steps = 0
-            axis.limit_stop_enabled = False
-            axis.capture_close_dir_on_limit = False
+                if index < 2:
+                    if axis.state == AXIS_RECOVERY:
+                        self._set_xy_state(axis, AXIS_LOCKED_FAULT)
+                    elif axis.state != AXIS_UNCALIBRATED:
+                        self._set_xy_state(axis, AXIS_INTERMEDIATE)
+                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.watchdog_timeout = watchdog_timeout
 
@@ -447,6 +505,7 @@ class NormalV3Model:
             if frame_type == FRAME_HOST_BATCH:
                 result = self._apply_snapshot(
                     payload,
+                    limit_active_mask=limit_active_mask & 0x03,
                     limit_ready_mask=limit_ready_mask & 0x03,
                 )
             elif frame_type == FRAME_HOST_CMD:
@@ -482,7 +541,13 @@ class NormalV3Model:
             raise AssertionError("rejected frame changed modeled state")
         return result
 
-    def _apply_snapshot(self, payload: bytes, *, limit_ready_mask: int) -> ModelResult:
+    def _apply_snapshot(
+        self,
+        payload: bytes,
+        *,
+        limit_active_mask: int,
+        limit_ready_mask: int,
+    ) -> ModelResult:
         command = payload[0] if payload else 0
         if len(payload) != 34:
             raise ModelFrameError("snapshot payload length must be 34", status=STATUS_BAD_LENGTH)
@@ -507,17 +572,41 @@ class NormalV3Model:
                 reason=str(exc),
             )
 
-        busy_mask = self.busy_mask
-        invalid_mask = sum(
-            (1 << index)
-            for index, axis in enumerate(self.axes)
-            if not axis.busy
-            and (
-                not axis.position_valid
-                or (index < 2 and not (limit_ready_mask & (1 << index)))
-            )
-        )
-        accepted_mask = (~(busy_mask | invalid_mask)) & 0x07
+        busy_mask = 0
+        invalid_mask = 0
+        accepted_mask = 0
+        for index, target in enumerate(checked_xyz):
+            axis = self.axes[index]
+            bit = 1 << index
+            if index >= 2:
+                if axis.busy:
+                    busy_mask |= bit
+                elif not axis.position_valid:
+                    invalid_mask |= bit
+                else:
+                    accepted_mask |= bit
+                continue
+            if not (limit_ready_mask & bit):
+                if axis.busy:
+                    busy_mask |= bit
+                else:
+                    invalid_mask |= bit
+                continue
+            if axis.state == AXIS_OPENING:
+                accepted_mask |= bit
+            elif axis.state == AXIS_CLOSING:
+                if target == 0:
+                    accepted_mask |= bit
+                else:
+                    busy_mask |= bit
+            elif axis.busy:
+                busy_mask |= bit
+            elif axis.state in (AXIS_CLOSED, AXIS_OPEN):
+                accepted_mask |= bit
+            elif axis.state == AXIS_INTERMEDIATE and target == 0:
+                accepted_mask |= bit
+            else:
+                invalid_mask |= bit
 
         self.ptc_percent = checked_ptc
         self.fan_percent = checked_fan
@@ -526,17 +615,39 @@ class NormalV3Model:
             if not (accepted_mask & (1 << index)):
                 continue
             axis = self.axes[index]
-            axis.target = target
-            axis.fault = False
-            if axis.current == target:
-                continue
-            axis.busy = True
-            axis.move_kind = "standard"
-            axis.raw_dir = (1 - int(axis.close_dir or 0)) if target == 100 else int(axis.close_dir or 0)
-            axis.speed_code = 3
-            axis.remaining_steps = STANDARD_STEPS
-            axis.limit_stop_enabled = index < 2 and target == 0
-            axis.capture_close_dir_on_limit = False
+            if index < 2:
+                idempotent = (
+                    (axis.state == AXIS_CLOSED and target == 0)
+                    or (axis.state == AXIS_OPEN and target == 100)
+                    or (axis.state == AXIS_OPENING and target == 100)
+                    or (axis.state == AXIS_CLOSING and target == 0)
+                )
+                if idempotent:
+                    continue
+                if target == 0 and (limit_active_mask & (1 << index)):
+                    self._set_xy_state(axis, AXIS_CLOSED)
+                    self._clear_motion(axis)
+                    continue
+                self._set_xy_state(axis, AXIS_OPENING if target == 100 else AXIS_CLOSING)
+                axis.busy = True
+                axis.move_kind = "standard"
+                axis.raw_dir = (1 - int(axis.close_dir or 0)) if target == 100 else int(axis.close_dir or 0)
+                axis.speed_code = 3
+                axis.remaining_steps = STANDARD_STEPS
+                axis.limit_stop_enabled = target == 0
+                axis.capture_close_dir_on_limit = False
+            else:
+                axis.target = target
+                axis.fault = False
+                if axis.current == target:
+                    continue
+                axis.busy = True
+                axis.move_kind = "standard"
+                axis.raw_dir = (1 - int(axis.close_dir or 0)) if target == 100 else int(axis.close_dir or 0)
+                axis.speed_code = 3
+                axis.remaining_steps = STANDARD_STEPS
+                axis.limit_stop_enabled = False
+                axis.capture_close_dir_on_limit = False
         self._kick_watchdog()
 
         partial = bool(busy_mask or invalid_mask)
@@ -627,24 +738,42 @@ class NormalV3Model:
         if axis.busy or (axis_index < 2 and not (limit_ready_mask & (1 << axis_index))):
             return self._result(accepted=False, command=MOTION_JOG, status=STATUS_BUSY)
 
-        prior_valid = axis.position_valid
         limit_active = axis_index < 2 and bool(limit_active_mask & (1 << axis_index))
-        at_closing_limit = limit_active and (not prior_valid or raw_dir == axis.close_dir)
-        if at_closing_limit:
-            axis.position_valid = True
-            axis.current = 0
-            axis.target = 0
-            if not prior_valid:
-                axis.close_dir = raw_dir
-            axis.fault = False
-            axis.busy = False
-            axis.move_kind = "idle"
-            axis.remaining_steps = 0
-            axis.limit_stop_enabled = False
-            axis.capture_close_dir_on_limit = False
+        if axis_index < 2:
+            allowed = (
+                axis.state == AXIS_UNCALIBRATED
+                or (axis.state == AXIS_CLOSED and raw_dir != axis.close_dir)
+                or (axis.state == AXIS_OPEN and raw_dir == axis.close_dir)
+                or axis.state == AXIS_INTERMEDIATE
+                or (axis.state == AXIS_RECOVERY and raw_dir == axis.close_dir)
+            )
+            if not allowed:
+                return self._result(accepted=False, command=MOTION_JOG, status=STATUS_BUSY)
+            prior_state = axis.state
+            if limit_active and (
+                prior_state == AXIS_UNCALIBRATED or raw_dir == axis.close_dir
+            ):
+                if prior_state == AXIS_UNCALIBRATED:
+                    axis.close_dir = raw_dir
+                self._set_xy_state(axis, AXIS_CLOSED)
+                self._clear_motion(axis)
+            else:
+                if prior_state in (AXIS_CLOSED, AXIS_OPEN):
+                    self._set_xy_state(axis, AXIS_INTERMEDIATE)
+                axis.busy = True
+                axis.move_kind = "jog"
+                axis.raw_dir = raw_dir
+                axis.speed_code = speed_code
+                axis.remaining_steps = steps
+                axis.limit_stop_enabled = (
+                    prior_state in (AXIS_UNCALIBRATED, AXIS_RECOVERY)
+                    or raw_dir == axis.close_dir
+                )
+                axis.capture_close_dir_on_limit = prior_state == AXIS_UNCALIBRATED
         else:
             axis.busy = True
             axis.position_valid = False
+            axis.state = AXIS_UNCALIBRATED
             axis.current = UNKNOWN_POSITION
             axis.target = UNKNOWN_POSITION
             axis.fault = False
@@ -652,8 +781,8 @@ class NormalV3Model:
             axis.raw_dir = raw_dir
             axis.speed_code = speed_code
             axis.remaining_steps = steps
-            axis.limit_stop_enabled = axis_index < 2 and (not prior_valid or raw_dir == axis.close_dir)
-            axis.capture_close_dir_on_limit = axis_index < 2 and not prior_valid
+            axis.limit_stop_enabled = False
+            axis.capture_close_dir_on_limit = False
         self._kick_watchdog()
         return self._result(accepted=True, command=MOTION_JOG, status=STATUS_OK)
 
@@ -664,6 +793,7 @@ class NormalV3Model:
         if axis.busy:
             return self._result(accepted=False, command=MOTION_MARK_CLOSED, status=STATUS_BUSY)
         axis.position_valid = True
+        axis.state = AXIS_CLOSED
         axis.current = 0
         axis.target = 0
         axis.close_dir = payload[2]
@@ -681,46 +811,38 @@ class NormalV3Model:
             raise ValueError("axis is not busy")
         move_kind = axis.move_kind
         target = axis.target
-        if move_kind == "jog":
-            if axis_index < 2 and limit_hit and axis.limit_stop_enabled:
-                axis.position_valid = True
-                axis.current = 0
-                axis.target = 0
-                if axis.capture_close_dir_on_limit:
-                    axis.close_dir = axis.raw_dir
-                axis.fault = False
+        if axis_index < 2:
+            if move_kind == "jog":
+                if limit_hit and axis.limit_stop_enabled:
+                    if axis.capture_close_dir_on_limit:
+                        axis.close_dir = axis.raw_dir
+                    self._set_xy_state(axis, AXIS_CLOSED)
+                elif axis.state == AXIS_RECOVERY:
+                    self._set_xy_state(axis, AXIS_LOCKED_FAULT)
+            elif move_kind == "standard":
+                if axis.state == AXIS_OPENING:
+                    self._set_xy_state(axis, AXIS_OPEN)
+                elif axis.state == AXIS_CLOSING:
+                    self._set_xy_state(axis, AXIS_CLOSED if limit_hit else AXIS_RECOVERY)
+                else:
+                    raise AssertionError("busy XY standard axis has no motion state")
             else:
+                raise AssertionError("busy XY axis has no modeled move kind")
+        else:
+            if move_kind == "jog":
+                axis.state = AXIS_UNCALIBRATED
                 axis.position_valid = False
                 axis.current = UNKNOWN_POSITION
                 axis.target = UNKNOWN_POSITION
-        elif move_kind == "standard":
-            if target == 100:
+            elif move_kind == "standard":
+                axis.state = AXIS_OPEN if target == 100 else AXIS_CLOSED
                 axis.position_valid = True
-                axis.current = 100
+                axis.current = target
+                axis.target = target
                 axis.fault = False
-            elif axis_index < 2:
-                if limit_hit:
-                    axis.position_valid = True
-                    axis.current = 0
-                    axis.target = 0
-                    axis.fault = False
-                else:
-                    axis.position_valid = False
-                    axis.current = UNKNOWN_POSITION
-                    axis.target = UNKNOWN_POSITION
-                    axis.fault = True
             else:
-                axis.position_valid = True
-                axis.current = 0
-                axis.target = 0
-                axis.fault = False
-        else:
-            raise AssertionError("busy axis has no modeled move kind")
-        axis.busy = False
-        axis.move_kind = "idle"
-        axis.remaining_steps = 0
-        axis.limit_stop_enabled = False
-        axis.capture_close_dir_on_limit = False
+                raise AssertionError("busy Z axis has no modeled move kind")
+        self._clear_motion(axis)
 
     def motor_status_payload(self) -> bytes:
         flags = int(bool(self.busy_mask))

+ 2 - 2
tools/prod2u_p4_protocol.py

@@ -531,8 +531,8 @@ def _position_triplet(values: Iterable[int], label: str) -> tuple[int, int, int]
     if len(result) != 3:
         raise ValueError(f"{label} must contain exactly three values")
     for value in result:
-        if value not in (0, 100, 0xFF):
-            raise ValueError(f"{label} values must be 0, 100, or 255")
+        if value not in (0, 100, 0xFE, 0xFF):
+            raise ValueError(f"{label} values must be 0, 100, 254, or 255")
     return result[0], result[1], result[2]