Procházet zdrojové kódy

feat(prod2u): add compile-time per-axis motor polarity masks

Enable project.json-driven LIMIT/DIR/LS-HS polarity so firmware can be
resynthesized for wiring variants without runtime config or a second image.

Co-authored-by: Cursor <cursoragent@cursor.com>
root před 3 měsíci
rodič
revize
f23d6d4c57

+ 3 - 0
projects/prod2u-door-temp/project.json

@@ -79,6 +79,7 @@
     "heartbeat_value": 0,
     "heartbeat_value": 0,
     "open_dir_value": 0,
     "open_dir_value": 0,
     "close_dir_value": 1,
     "close_dir_value": 1,
+    "dir_close_level": [1, 1, 1],
     "mapping": {
     "mapping": {
       "x": {"axis": "x", "role": "door", "step_ball": "C12", "dir_ball": "B12", "step_connector": "CON104", "step_connector_pin": 2, "dir_connector": "CON104", "dir_connector_pin": 3},
       "x": {"axis": "x", "role": "door", "step_ball": "C12", "dir_ball": "B12", "step_connector": "CON104", "step_connector_pin": 2, "dir_connector": "CON104", "dir_connector_pin": 3},
       "y": {"axis": "y", "role": "door", "step_ball": "L12", "dir_ball": "J11", "step_connector": "CON105", "step_connector_pin": 2, "dir_connector": "CON105", "dir_connector_pin": 3},
       "y": {"axis": "y", "role": "door", "step_ball": "L12", "dir_ball": "J11", "step_connector": "CON105", "step_connector_pin": 2, "dir_connector": "CON105", "dir_connector_pin": 3},
@@ -96,6 +97,8 @@
   "limits": {
   "limits": {
     "limit_count": 6,
     "limit_count": 6,
     "active_level": "high",
     "active_level": "high",
+    "limit_active_high": [true, true, true],
+    "close_limit_is_ls": [true, true, true],
     "functional_use": true,
     "functional_use": true,
     "runtime_use": true,
     "runtime_use": true,
     "startup": {
     "startup": {

+ 31 - 0
schemas/project.schema.json

@@ -278,6 +278,7 @@
                                                        "heartbeat_value",
                                                        "heartbeat_value",
                                                        "open_dir_value",
                                                        "open_dir_value",
                                                        "close_dir_value",
                                                        "close_dir_value",
+                                                       "dir_close_level",
                                                        "mapping",
                                                        "mapping",
                                                        "enable_n"
                                                        "enable_n"
                                                    ],
                                                    ],
@@ -322,6 +323,16 @@
                                                          "close_dir_value":  {
                                                          "close_dir_value":  {
                                                                                  "type":  "integer"
                                                                                  "type":  "integer"
                                                                              },
                                                                              },
+                                                         "dir_close_level":  {
+                                                                                 "type":  "array",
+                                                                                 "minItems":  3,
+                                                                                 "maxItems":  3,
+                                                                                 "items":  {
+                                                                                               "type":  "integer",
+                                                                                               "enum":  [0, 1]
+                                                                                           },
+                                                                                 "description":  "Per-axis physical DIR level for logical close; index0=X,1=Y,2=Z (bit0=X)."
+                                                                             },
                                                          "mapping":  {
                                                          "mapping":  {
                                                                          "type":  "object",
                                                                          "type":  "object",
                                                                          "required":  [
                                                                          "required":  [
@@ -383,6 +394,8 @@
                                       "required":  [
                                       "required":  [
                                                        "limit_count",
                                                        "limit_count",
                                                        "active_level",
                                                        "active_level",
+                                                       "limit_active_high",
+                                                       "close_limit_is_ls",
                                                        "functional_use",
                                                        "functional_use",
                                                        "runtime_use",
                                                        "runtime_use",
                                                        "startup",
                                                        "startup",
@@ -395,6 +408,24 @@
                                                          "active_level":  {
                                                          "active_level":  {
                                                                               "type":  "string"
                                                                               "type":  "string"
                                                                           },
                                                                           },
+                                                         "limit_active_high":  {
+                                                                                   "type":  "array",
+                                                                                   "minItems":  3,
+                                                                                   "maxItems":  3,
+                                                                                   "items":  {
+                                                                                                 "type":  "boolean"
+                                                                                             },
+                                                                                   "description":  "Per-axis limit active-high; index0=X,1=Y,2=Z (bit0=X)."
+                                                                               },
+                                                         "close_limit_is_ls":  {
+                                                                                   "type":  "array",
+                                                                                   "minItems":  3,
+                                                                                   "maxItems":  3,
+                                                                                   "items":  {
+                                                                                                 "type":  "boolean"
+                                                                                             },
+                                                                                   "description":  "Per-axis: true means logical close limit is LS (else HS); index0=X,1=Y,2=Z."
+                                                                               },
                                                          "functional_use":  {
                                                          "functional_use":  {
                                                                                 "type":  "boolean"
                                                                                 "type":  "boolean"
                                                                             },
                                                                             },

+ 15 - 0
src/generated/host-contract.json

@@ -86,7 +86,17 @@
         "side": "high"
         "side": "high"
       }
       }
     ],
     ],
+    "close_limit_is_ls": [
+      true,
+      true,
+      true
+    ],
     "functional_use": true,
     "functional_use": true,
+    "limit_active_high": [
+      true,
+      true,
+      true
+    ],
     "limit_count": 6,
     "limit_count": 6,
     "runtime_use": true,
     "runtime_use": true,
     "startup": {
     "startup": {
@@ -116,6 +126,11 @@
       2
       2
     ],
     ],
     "count": 3,
     "count": 3,
+    "dir_close_level": [
+      1,
+      1,
+      1
+    ],
     "dir_setup_cycles": 25000,
     "dir_setup_cycles": 25000,
     "enable_n": {
     "enable_n": {
       "active_level": "low",
       "active_level": "low",

+ 3 - 0
src/generated/prod2u_door_temp_params.vh

@@ -2,6 +2,9 @@
 `define P4_AXIS_COUNT 3
 `define P4_AXIS_COUNT 3
 `define P4_LIMIT_COUNT 6
 `define P4_LIMIT_COUNT 6
 `define P4_RUNTIME_LIMIT_USE 1
 `define P4_RUNTIME_LIMIT_USE 1
+`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b111
+`define P4_DIR_CLOSE_LEVEL_MASK 3'b111
+`define P4_CLOSE_LIMIT_IS_LS_MASK 3'b111
 `define P4_CLOCK_HZ 25000000
 `define P4_CLOCK_HZ 25000000
 `define P4_UART_BAUD 115200
 `define P4_UART_BAUD 115200
 `define P4_UART_CLKS_PER_BIT 217
 `define P4_UART_CLKS_PER_BIT 217

+ 4 - 2
src/modules/door_action_dispatcher.v

@@ -1,8 +1,9 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
-// Multi-axis jog dispatcher. DIR=0 open/up, DIR=1 close/down.
+// Multi-axis jog dispatcher. motor_dir_mask is logical: 0=open, 1=close.
+// Physical DIR is applied only at the top-level IO adapter via dir_close_level.
 // Commands: 00 = no new action (does not emergency-stop a running motor),
 // Commands: 00 = no new action (does not emergency-stop a running motor),
-// 01 DIR0 open, 02 DIR1 close. SET_ALL byte8->Z, byte9->X, byte10->Y.
+// 01 logical open, 02 logical close. SET_ALL byte8->Z, byte9->X, byte10->Y.
 // Bit packing: bit0=X, bit1=Y, bit2=Z. New door commands are ignored while busy.
 // Bit packing: bit0=X, bit1=Y, bit2=Z. New door commands are ignored while busy.
 module door_action_dispatcher #(
 module door_action_dispatcher #(
     parameter integer OPEN_DIR = 0,
     parameter integer OPEN_DIR = 0,
@@ -26,6 +27,7 @@ module door_action_dispatcher #(
     wire x_active = (exhaust_x_cmd != 2'd0);
     wire x_active = (exhaust_x_cmd != 2'd0);
     wire y_active = (exhaust_y_cmd != 2'd0);
     wire y_active = (exhaust_y_cmd != 2'd0);
     wire z_active = (z_door_cmd != 2'd0);
     wire z_active = (z_door_cmd != 2'd0);
+    // Logical direction only; OPEN_DIR/CLOSE_DIR must remain 0/1.
     wire x_dir_bit = (exhaust_x_cmd == 2'd2) ? CLOSE_DIR[0] : OPEN_DIR[0];
     wire x_dir_bit = (exhaust_x_cmd == 2'd2) ? CLOSE_DIR[0] : OPEN_DIR[0];
     wire y_dir_bit = (exhaust_y_cmd == 2'd2) ? CLOSE_DIR[0] : OPEN_DIR[0];
     wire y_dir_bit = (exhaust_y_cmd == 2'd2) ? CLOSE_DIR[0] : OPEN_DIR[0];
     wire z_dir_bit = (z_door_cmd == 2'd2) ? CLOSE_DIR[0] : OPEN_DIR[0];
     wire z_dir_bit = (z_door_cmd == 2'd2) ? CLOSE_DIR[0] : OPEN_DIR[0];

+ 18 - 16
src/modules/startup_close_seek.v

@@ -1,8 +1,10 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
-// Power-on / reconfig close-seek one-shot: close-search toward LS (DIR=1) up to
-// CLOSE_STEPS rising edges, latch found_ls, then optional backoff (DIR=0) up to
-// BACKOFF_STEPS for axes that never saw LS. startup_done is sticky after success.
+// Power-on / reconfig close-seek one-shot: logical CLOSE toward close_limit up to
+// CLOSE_STEPS rising edges, latch found_close, then optional logical OPEN backoff
+// up to BACKOFF_STEPS for axes that never saw close_limit. startup_done is sticky
+// after success. motor_dir_mask is logical (1=close, 0=open); physical DIR is
+// applied only at the top-level IO adapter.
 // Step pacing uses door_motor_engine tick_500us; this FSM has no local tick port.
 // Step pacing uses door_motor_engine tick_500us; this FSM has no local tick port.
 module startup_close_seek #(
 module startup_close_seek #(
     parameter integer CLOSE_STEPS = 5000,
     parameter integer CLOSE_STEPS = 5000,
@@ -18,8 +20,8 @@ module startup_close_seek #(
     input  wire       clk,
     input  wire       clk,
     input  wire       rst_n,
     input  wire       rst_n,
     input  wire       limit_sync_valid,
     input  wire       limit_sync_valid,
-    input  wire [AXIS_COUNT-1:0] limit_ls_sync,
-    input  wire [AXIS_COUNT-1:0] limit_hs_sync,
+    input  wire [AXIS_COUNT-1:0] close_limit,
+    input  wire [AXIS_COUNT-1:0] open_limit,
     output reg        startup_done,
     output reg        startup_done,
     output reg        motor_start,
     output reg        motor_start,
     output reg  [AXIS_COUNT-1:0] motor_active_mask,
     output reg  [AXIS_COUNT-1:0] motor_active_mask,
@@ -40,13 +42,13 @@ module startup_close_seek #(
     localparam [2:0] ST_DONE        = 3'd7;
     localparam [2:0] ST_DONE        = 3'd7;
 
 
     reg [2:0] state;
     reg [2:0] state;
-    reg [AXIS_COUNT-1:0] found_ls;
+    reg [AXIS_COUNT-1:0] found_close;
     reg [AXIS_COUNT-1:0] close_participants;
     reg [AXIS_COUNT-1:0] close_participants;
-    wire [AXIS_COUNT-1:0] missed_ls_mask = close_participants & ~found_ls;
+    wire [AXIS_COUNT-1:0] missed_close_mask = close_participants & ~found_close;
 
 
     assign motor_stop_mask =
     assign motor_stop_mask =
-        (state == ST_CLOSE_WAIT) ? (limit_ls_sync & motor_active_mask) :
-        (state == ST_BACKOFF_WAIT) ? (limit_hs_sync & motor_active_mask) :
+        (state == ST_CLOSE_WAIT) ? (close_limit & motor_active_mask) :
+        (state == ST_BACKOFF_WAIT) ? (open_limit & motor_active_mask) :
         AXIS_ZERO;
         AXIS_ZERO;
 
 
     always @(posedge clk or negedge rst_n) begin
     always @(posedge clk or negedge rst_n) begin
@@ -57,11 +59,11 @@ module startup_close_seek #(
             motor_active_mask <= AXIS_ZERO;
             motor_active_mask <= AXIS_ZERO;
             motor_dir_mask <= AXIS_ZERO;
             motor_dir_mask <= AXIS_ZERO;
             motor_step_count <= {STEP_COUNT_WIDTH{1'b0}};
             motor_step_count <= {STEP_COUNT_WIDTH{1'b0}};
-            found_ls <= AXIS_ZERO;
+            found_close <= AXIS_ZERO;
             close_participants <= AXIS_ZERO;
             close_participants <= AXIS_ZERO;
         end else begin
         end else begin
             if (state == ST_CLOSE_WAIT)
             if (state == ST_CLOSE_WAIT)
-                found_ls <= found_ls | limit_ls_sync;
+                found_close <= found_close | close_limit;
 
 
             case (state)
             case (state)
                 ST_WAIT_SYNC: begin
                 ST_WAIT_SYNC: begin
@@ -71,9 +73,9 @@ module startup_close_seek #(
                 end
                 end
                 ST_CHECK: begin
                 ST_CHECK: begin
                     motor_start <= 1'b0;
                     motor_start <= 1'b0;
-                    found_ls <= limit_ls_sync & AXIS_ENABLE_MASK;
-                    close_participants <= (~limit_ls_sync) & AXIS_ENABLE_MASK;
-                    if ((~limit_ls_sync & AXIS_ENABLE_MASK) == AXIS_ZERO) begin
+                    found_close <= close_limit & AXIS_ENABLE_MASK;
+                    close_participants <= (~close_limit) & AXIS_ENABLE_MASK;
+                    if ((~close_limit & AXIS_ENABLE_MASK) == AXIS_ZERO) begin
                         state <= ST_DONE;
                         state <= ST_DONE;
                         startup_done <= 1'b1;
                         startup_done <= 1'b1;
                     end else begin
                     end else begin
@@ -93,7 +95,7 @@ module startup_close_seek #(
                         state <= ST_EVAL;
                         state <= ST_EVAL;
                 end
                 end
                 ST_EVAL: begin
                 ST_EVAL: begin
-                    if (missed_ls_mask == AXIS_ZERO) begin
+                    if (missed_close_mask == AXIS_ZERO) begin
                         state <= ST_DONE;
                         state <= ST_DONE;
                         startup_done <= 1'b1;
                         startup_done <= 1'b1;
                     end else begin
                     end else begin
@@ -101,7 +103,7 @@ module startup_close_seek #(
                     end
                     end
                 end
                 end
                 ST_BACKOFF_START: begin
                 ST_BACKOFF_START: begin
-                    motor_active_mask <= missed_ls_mask;
+                    motor_active_mask <= missed_close_mask;
                     motor_dir_mask <= AXIS_ZERO;
                     motor_dir_mask <= AXIS_ZERO;
                     motor_step_count <= BACKOFF_STEPS[STEP_COUNT_WIDTH-1:0];
                     motor_step_count <= BACKOFF_STEPS[STEP_COUNT_WIDTH-1:0];
                     motor_start <= 1'b1;
                     motor_start <= 1'b1;

+ 46 - 25
src/top/prod2u_p4_normal_v3_top.v

@@ -33,6 +33,10 @@ module prod2u_p4_normal_v3_top (
     localparam integer MOTOR_STEP_WIDTH =
     localparam integer MOTOR_STEP_WIDTH =
         (`P4_STARTUP_CLOSE_STEPS <= 1) ? 1 : $clog2(`P4_STARTUP_CLOSE_STEPS + 1);
         (`P4_STARTUP_CLOSE_STEPS <= 1) ? 1 : $clog2(`P4_STARTUP_CLOSE_STEPS + 1);
     localparam [MOTOR_STEP_WIDTH-1:0] HOST_MOTOR_STEPS = `P4_FIXED_MOTOR_STEPS;
     localparam [MOTOR_STEP_WIDTH-1:0] HOST_MOTOR_STEPS = `P4_FIXED_MOTOR_STEPS;
+    // Compile-time polarity / endpoint role (bit0=X,1=Y,2=Z).
+    localparam [AXIS_COUNT-1:0] LIMIT_ACTIVE_HIGH = `P4_LIMIT_ACTIVE_HIGH_MASK;
+    localparam [AXIS_COUNT-1:0] DIR_CLOSE_LEVEL = `P4_DIR_CLOSE_LEVEL_MASK;
+    localparam [AXIS_COUNT-1:0] CLOSE_LIMIT_IS_LS = `P4_CLOSE_LIMIT_IS_LS_MASK;
 
 
     wire sys_rst_n;
     wire sys_rst_n;
     wire uart_rx_valid;
     wire uart_rx_valid;
@@ -85,6 +89,11 @@ module prod2u_p4_normal_v3_top (
     (* async_reg = "true" *) reg z_limit_hs_sync0, z_limit_hs_sync1;
     (* async_reg = "true" *) reg z_limit_hs_sync0, z_limit_hs_sync1;
     wire [AXIS_COUNT-1:0] limit_ls_sync;
     wire [AXIS_COUNT-1:0] limit_ls_sync;
     wire [AXIS_COUNT-1:0] limit_hs_sync;
     wire [AXIS_COUNT-1:0] limit_hs_sync;
+    wire [AXIS_COUNT-1:0] ls_reached;
+    wire [AXIS_COUNT-1:0] hs_reached;
+    wire [AXIS_COUNT-1:0] close_limit;
+    wire [AXIS_COUNT-1:0] open_limit;
+    wire [AXIS_COUNT-1:0] selected_limit;
     reg        limit_sync_valid;
     reg        limit_sync_valid;
     reg [1:0]  limit_sync_valid_cnt;
     reg [1:0]  limit_sync_valid_cnt;
 
 
@@ -145,36 +154,48 @@ module prod2u_p4_normal_v3_top (
 
 
     genvar gi;
     genvar gi;
     generate
     generate
-        for (gi = 0; gi < AXIS_COUNT; gi = gi + 1) begin : gen_runtime_limit_stop
+        for (gi = 0; gi < AXIS_COUNT; gi = gi + 1) begin : gen_limit_normalize
+            // Boundary normalize: raw sync -> reached -> logical open/close limits.
+            assign ls_reached[gi] =
+                LIMIT_ACTIVE_HIGH[gi] ? limit_ls_sync[gi] : ~limit_ls_sync[gi];
+            assign hs_reached[gi] =
+                LIMIT_ACTIVE_HIGH[gi] ? limit_hs_sync[gi] : ~limit_hs_sync[gi];
+            assign close_limit[gi] =
+                CLOSE_LIMIT_IS_LS[gi] ? ls_reached[gi] : hs_reached[gi];
+            assign open_limit[gi] =
+                CLOSE_LIMIT_IS_LS[gi] ? hs_reached[gi] : ls_reached[gi];
+            // motor_dir_mask / engine_dir are logical: 1=close, 0=open.
             assign runtime_limit_stop_mask[gi] =
             assign runtime_limit_stop_mask[gi] =
-                motor_dir_mask[gi] ? limit_ls_sync[gi] : limit_hs_sync[gi];
+                motor_dir_mask[gi] ? close_limit[gi] : open_limit[gi];
+            assign selected_limit[gi] =
+                engine_dir[gi] ? close_limit[gi] : open_limit[gi];
         end
         end
     endgenerate
     endgenerate
 
 
-    assign x_step = engine_step[0] &
-        ~(engine_dir[0] ? x_limit_ls_sync1 : x_limit_hs_sync1);
-    assign y_step = engine_step[1] &
-        ~(engine_dir[1] ? y_limit_ls_sync1 : y_limit_hs_sync1);
-    assign z_step = engine_step[2] &
-        ~(engine_dir[2] ? z_limit_ls_sync1 : z_limit_hs_sync1);
-    assign x_dir = engine_dir[0];
-    assign y_dir = engine_dir[1];
-    assign z_dir = engine_dir[2];
+    // Dual hard-stop: FSM stop_mask + final STEP gate on selected logical limit.
+    assign x_step = engine_step[0] & ~selected_limit[0];
+    assign y_step = engine_step[1] & ~selected_limit[1];
+    assign z_step = engine_step[2] & ~selected_limit[2];
+    // Physical DIR only at the IO adapter edge.
+    assign x_dir = engine_dir[0] ? DIR_CLOSE_LEVEL[0] : ~DIR_CLOSE_LEVEL[0];
+    assign y_dir = engine_dir[1] ? DIR_CLOSE_LEVEL[1] : ~DIR_CLOSE_LEVEL[1];
+    assign z_dir = engine_dir[2] ? DIR_CLOSE_LEVEL[2] : ~DIR_CLOSE_LEVEL[2];
 
 
     always @(posedge sys_clk or negedge sys_rst_n) begin
     always @(posedge sys_clk or negedge sys_rst_n) begin
         if (!sys_rst_n) begin
         if (!sys_rst_n) begin
-            x_limit_ls_sync0 <= 1'b0;
-            x_limit_ls_sync1 <= 1'b0;
-            x_limit_hs_sync0 <= 1'b0;
-            x_limit_hs_sync1 <= 1'b0;
-            y_limit_ls_sync0 <= 1'b0;
-            y_limit_ls_sync1 <= 1'b0;
-            y_limit_hs_sync0 <= 1'b0;
-            y_limit_hs_sync1 <= 1'b0;
-            z_limit_ls_sync0 <= 1'b0;
-            z_limit_ls_sync1 <= 1'b0;
-            z_limit_hs_sync0 <= 1'b0;
-            z_limit_hs_sync1 <= 1'b0;
+            // Active-low reset init: load raw inactive level to avoid false limits.
+            x_limit_ls_sync0 <= ~LIMIT_ACTIVE_HIGH[0];
+            x_limit_ls_sync1 <= ~LIMIT_ACTIVE_HIGH[0];
+            x_limit_hs_sync0 <= ~LIMIT_ACTIVE_HIGH[0];
+            x_limit_hs_sync1 <= ~LIMIT_ACTIVE_HIGH[0];
+            y_limit_ls_sync0 <= ~LIMIT_ACTIVE_HIGH[1];
+            y_limit_ls_sync1 <= ~LIMIT_ACTIVE_HIGH[1];
+            y_limit_hs_sync0 <= ~LIMIT_ACTIVE_HIGH[1];
+            y_limit_hs_sync1 <= ~LIMIT_ACTIVE_HIGH[1];
+            z_limit_ls_sync0 <= ~LIMIT_ACTIVE_HIGH[2];
+            z_limit_ls_sync1 <= ~LIMIT_ACTIVE_HIGH[2];
+            z_limit_hs_sync0 <= ~LIMIT_ACTIVE_HIGH[2];
+            z_limit_hs_sync1 <= ~LIMIT_ACTIVE_HIGH[2];
             limit_sync_valid <= 1'b0;
             limit_sync_valid <= 1'b0;
             limit_sync_valid_cnt <= 2'd0;
             limit_sync_valid_cnt <= 2'd0;
         end else begin
         end else begin
@@ -277,8 +298,8 @@ module prod2u_p4_normal_v3_top (
     ) u_startup_close_seek (
     ) u_startup_close_seek (
         .clk(sys_clk), .rst_n(sys_rst_n),
         .clk(sys_clk), .rst_n(sys_rst_n),
         .limit_sync_valid(limit_sync_valid),
         .limit_sync_valid(limit_sync_valid),
-        .limit_ls_sync(limit_ls_sync),
-        .limit_hs_sync(limit_hs_sync),
+        .close_limit(close_limit),
+        .open_limit(open_limit),
         .startup_done(startup_done), .motor_start(startup_motor_start),
         .startup_done(startup_done), .motor_start(startup_motor_start),
         .motor_active_mask(startup_motor_active_mask),
         .motor_active_mask(startup_motor_active_mask),
         .motor_dir_mask(startup_motor_dir_mask),
         .motor_dir_mask(startup_motor_dir_mask),

+ 18 - 21
tests/formal/runtime_limit_hard_stop_formal.v

@@ -24,7 +24,16 @@ module runtime_limit_hard_stop_formal (
     localparam integer FORMAL_DIR_SETUP_TICKS = 1;
     localparam integer FORMAL_DIR_SETUP_TICKS = 1;
     localparam integer AXIS_COUNT = 3;
     localparam integer AXIS_COUNT = 3;
 
 
+    // Default compile-time polarity: close_limit=LS, open_limit=HS (active-high).
+    wire [2:0] close_limit = limit_ls_sync;
+    wire [2:0] open_limit = limit_hs_sync;
     wire [2:0] runtime_limit_stop_mask;
     wire [2:0] runtime_limit_stop_mask;
+    wire [2:0] selected_limit;
+    wire [2:0] gated_step;
+    wire busy;
+    wire done;
+    wire [2:0] engine_step;
+    wire [2:0] engine_dir;
     reg [2:0] reset_cycles;
     reg [2:0] reset_cycles;
     reg [2:0] prev_gated_step;
     reg [2:0] prev_gated_step;
     reg past_valid;
     reg past_valid;
@@ -32,18 +41,16 @@ module runtime_limit_hard_stop_formal (
     genvar gi;
     genvar gi;
     generate
     generate
         for (gi = 0; gi < AXIS_COUNT; gi = gi + 1) begin : gen_runtime_limit_stop
         for (gi = 0; gi < AXIS_COUNT; gi = gi + 1) begin : gen_runtime_limit_stop
+            // motor_dir_mask / engine_dir are logical: 1=close, 0=open.
             assign runtime_limit_stop_mask[gi] =
             assign runtime_limit_stop_mask[gi] =
-                motor_dir_mask[gi] ? limit_ls_sync[gi] : limit_hs_sync[gi];
+                motor_dir_mask[gi] ? close_limit[gi] : open_limit[gi];
+            assign selected_limit[gi] =
+                engine_dir[gi] ? close_limit[gi] : open_limit[gi];
         end
         end
     endgenerate
     endgenerate
 
 
     wire [2:0] motor_stop_mask = startup_done ? runtime_limit_stop_mask : 3'b000;
     wire [2:0] motor_stop_mask = startup_done ? runtime_limit_stop_mask : 3'b000;
 
 
-    wire busy;
-    wire done;
-    wire [2:0] engine_step;
-    wire [2:0] engine_dir;
-
     door_motor_engine #(
     door_motor_engine #(
         .AXIS_COUNT(AXIS_COUNT),
         .AXIS_COUNT(AXIS_COUNT),
         .MAX_STEPS(FORMAL_MAX_STEPS),
         .MAX_STEPS(FORMAL_MAX_STEPS),
@@ -64,25 +71,15 @@ module runtime_limit_hard_stop_formal (
         .dir(engine_dir)
         .dir(engine_dir)
     );
     );
 
 
-    // Top pin gate: immediate truncate of external STEP on target-side sync.
-    wire [2:0] gated_step;
-    assign gated_step[0] = engine_step[0] &
-        ~(engine_dir[0] ? limit_ls_sync[0] : limit_hs_sync[0]);
-    assign gated_step[1] = engine_step[1] &
-        ~(engine_dir[1] ? limit_ls_sync[1] : limit_hs_sync[1]);
-    assign gated_step[2] = engine_step[2] &
-        ~(engine_dir[2] ? limit_ls_sync[2] : limit_hs_sync[2]);
+    // Top pin gate: immediate truncate of external STEP on selected logical limit.
+    assign gated_step[0] = engine_step[0] & ~selected_limit[0];
+    assign gated_step[1] = engine_step[1] & ~selected_limit[1];
+    assign gated_step[2] = engine_step[2] & ~selected_limit[2];
 
 
     // Top permanent enable (FPGA ball constant 1 / permanent_high).
     // Top permanent enable (FPGA ball constant 1 / permanent_high).
     wire motor_en_n = 1'b1;
     wire motor_en_n = 1'b1;
 
 
-    wire [2:0] target_limit_for_engine_dir;
-    assign target_limit_for_engine_dir[0] =
-        engine_dir[0] ? limit_ls_sync[0] : limit_hs_sync[0];
-    assign target_limit_for_engine_dir[1] =
-        engine_dir[1] ? limit_ls_sync[1] : limit_hs_sync[1];
-    assign target_limit_for_engine_dir[2] =
-        engine_dir[2] ? limit_ls_sync[2] : limit_hs_sync[2];
+    wire [2:0] target_limit_for_engine_dir = selected_limit;
 
 
     initial begin
     initial begin
         reset_cycles = 3'd0;
         reset_cycles = 3'd0;

+ 18 - 13
tests/formal/startup_close_seek_formal.v

@@ -46,6 +46,10 @@ module startup_close_seek_formal (
         end
         end
     end
     end
 
 
+    // Default polarity: close_limit=LS, open_limit=HS.
+    wire [AXIS_COUNT-1:0] close_limit = limit_ls_sync;
+    wire [AXIS_COUNT-1:0] open_limit = limit_hs_sync;
+
     startup_close_seek #(
     startup_close_seek #(
         .CLOSE_STEPS(FORMAL_CLOSE_STEPS),
         .CLOSE_STEPS(FORMAL_CLOSE_STEPS),
         .BACKOFF_STEPS(FORMAL_BACKOFF_STEPS),
         .BACKOFF_STEPS(FORMAL_BACKOFF_STEPS),
@@ -55,8 +59,8 @@ module startup_close_seek_formal (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
         .limit_sync_valid(formal_sync_valid),
         .limit_sync_valid(formal_sync_valid),
-        .limit_ls_sync(limit_ls_sync),
-        .limit_hs_sync(limit_hs_sync),
+        .close_limit(close_limit),
+        .open_limit(open_limit),
         .startup_done(startup_done),
         .startup_done(startup_done),
         .motor_start(motor_start),
         .motor_start(motor_start),
         .motor_active_mask(motor_active_mask),
         .motor_active_mask(motor_active_mask),
@@ -86,14 +90,15 @@ module startup_close_seek_formal (
         .dir(engine_dir)
         .dir(engine_dir)
     );
     );
 
 
-    // Top-style external STEP truncate gate (dir-select LS/HS).
+    // Top-style external STEP truncate gate on selected logical limit.
+    wire [AXIS_COUNT-1:0] selected_limit;
     wire [AXIS_COUNT-1:0] gated_step;
     wire [AXIS_COUNT-1:0] gated_step;
-    assign gated_step[0] = engine_step[0] &
-        ~(engine_dir[0] ? limit_ls_sync[0] : limit_hs_sync[0]);
-    assign gated_step[1] = engine_step[1] &
-        ~(engine_dir[1] ? limit_ls_sync[1] : limit_hs_sync[1]);
-    assign gated_step[2] = engine_step[2] &
-        ~(engine_dir[2] ? limit_ls_sync[2] : limit_hs_sync[2]);
+    assign selected_limit[0] = engine_dir[0] ? close_limit[0] : open_limit[0];
+    assign selected_limit[1] = engine_dir[1] ? close_limit[1] : open_limit[1];
+    assign selected_limit[2] = engine_dir[2] ? close_limit[2] : open_limit[2];
+    assign gated_step[0] = engine_step[0] & ~selected_limit[0];
+    assign gated_step[1] = engine_step[1] & ~selected_limit[1];
+    assign gated_step[2] = engine_step[2] & ~selected_limit[2];
 
 
     wire motor_en_n = 1'b1;
     wire motor_en_n = 1'b1;
 
 
@@ -182,12 +187,12 @@ module startup_close_seek_formal (
                     assert (!( !prev_gated_step[0] && gated_step[0] ));
                     assert (!( !prev_gated_step[0] && gated_step[0] ));
             end
             end
 
 
-            // Truncate pin path: target-side sync => gated STEP 0 same cycle.
-            if (engine_dir[0] ? limit_ls_sync[0] : limit_hs_sync[0])
+            // Truncate pin path: selected logical limit => gated STEP 0 same cycle.
+            if (selected_limit[0])
                 assert (gated_step[0] == 1'b0);
                 assert (gated_step[0] == 1'b0);
-            if (engine_dir[1] ? limit_ls_sync[1] : limit_hs_sync[1])
+            if (selected_limit[1])
                 assert (gated_step[1] == 1'b0);
                 assert (gated_step[1] == 1'b0);
-            if (engine_dir[2] ? limit_ls_sync[2] : limit_hs_sync[2])
+            if (selected_limit[2])
                 assert (gated_step[2] == 1'b0);
                 assert (gated_step[2] == 1'b0);
 
 
             // Missed-axis backoff budget: at most BACKOFF_STEPS rising edges.
             // Missed-axis backoff budget: at most BACKOFF_STEPS rising edges.

+ 1 - 1
tests/sim/startup_close_seek_tb.v

@@ -36,7 +36,7 @@ module startup_close_seek_tb;
     ) dut (
     ) dut (
         .clk(clk), .rst_n(rst_n),
         .clk(clk), .rst_n(rst_n),
         .limit_sync_valid(limit_sync_valid),
         .limit_sync_valid(limit_sync_valid),
-        .limit_ls_sync(limit_ls), .limit_hs_sync(limit_hs),
+        .close_limit(limit_ls), .open_limit(limit_hs),
         .startup_done(startup_done), .motor_start(motor_start),
         .startup_done(startup_done), .motor_start(motor_start),
         .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
         .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
         .motor_step_count(motor_step_count), .motor_stop_mask(motor_stop_mask),
         .motor_step_count(motor_step_count), .motor_stop_mask(motor_stop_mask),

+ 1 - 1
tests/sim/startup_motor_stop_tb.v

@@ -41,7 +41,7 @@ module startup_motor_stop_tb;
     ) u_startup (
     ) u_startup (
         .clk(clk), .rst_n(rst_n),
         .clk(clk), .rst_n(rst_n),
         .limit_sync_valid(limit_valid),
         .limit_sync_valid(limit_valid),
-        .limit_ls_sync(limit_ls), .limit_hs_sync(limit_hs),
+        .close_limit(limit_ls), .open_limit(limit_hs),
         .startup_done(startup_done), .motor_start(motor_start),
         .startup_done(startup_done), .motor_start(motor_start),
         .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
         .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
         .motor_step_count(motor_step_count), .motor_stop_mask(motor_stop_mask),
         .motor_step_count(motor_step_count), .motor_stop_mask(motor_stop_mask),

+ 7 - 0
tests/unit/test_build_firmware_package.py

@@ -115,6 +115,13 @@ class BuildFirmwarePackageTests(unittest.TestCase):
                 self.assertEqual(manifest["verification_scope"], "offline")
                 self.assertEqual(manifest["verification_scope"], "offline")
                 self.assertTrue(manifest["source_closure_unchanged"])
                 self.assertTrue(manifest["source_closure_unchanged"])
                 self.assertEqual(manifest["schema"], "prod2u-door-temp-final-package-manifest-v2")
                 self.assertEqual(manifest["schema"], "prod2u-door-temp-final-package-manifest-v2")
+                polarity = manifest["motor_polarity_config"]
+                self.assertEqual(polarity["masks"]["limit_active_high_mask"], "3'b111")
+                self.assertEqual(polarity["masks"]["dir_close_level_mask"], "3'b111")
+                self.assertEqual(polarity["masks"]["close_limit_is_ls_mask"], "3'b111")
+                self.assertEqual(len(polarity["sha256"]), 64)
+                identity = builder.motor_polarity_config_identity(ROOT)
+                self.assertEqual(polarity["sha256"], identity["sha256"])
                 sums = zipf.read("SHA256SUMS.txt").decode("utf-8")
                 sums = zipf.read("SHA256SUMS.txt").decode("utf-8")
                 self.assertIn("fw.bit", sums)
                 self.assertIn("fw.bit", sums)
 
 

+ 232 - 0
tests/unit/test_motor_polarity_config.py

@@ -0,0 +1,232 @@
+"""Compile-time motor polarity / endpoint-role config contract tests."""
+
+from __future__ import annotations
+
+import copy
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+from tools.generate_project import _axis_mask_literal, _render_params, generate_project, load_project
+
+ROOT = Path(__file__).resolve().parents[2]
+PROJECT_PATH = ROOT / "projects" / "prod2u-door-temp" / "project.json"
+PARAMS_PATH = ROOT / "src" / "generated" / "prod2u_door_temp_params.vh"
+
+
+class MotorPolarityConfigTests(unittest.TestCase):
+    def test_project_json_has_explicit_default_polarity_arrays(self):
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        self.assertEqual(project["limits"]["limit_active_high"], [True, True, True])
+        self.assertEqual(project["limits"]["close_limit_is_ls"], [True, True, True])
+        self.assertEqual(project["motors"]["dir_close_level"], [1, 1, 1])
+
+    def test_axis_mask_bit_order_x_is_lsb(self):
+        self.assertEqual(_axis_mask_literal([True, False, True], 3), "3'b101")
+        self.assertEqual(_axis_mask_literal([1, 0, 0], 3), "3'b001")
+        self.assertEqual(_axis_mask_literal([0, 1, 0], 3), "3'b010")
+        self.assertEqual(_axis_mask_literal([0, 0, 1], 3), "3'b100")
+
+    def test_generated_params_emit_default_masks(self):
+        params = PARAMS_PATH.read_text(encoding="utf-8")
+        self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b111", params)
+        self.assertIn("`define P4_DIR_CLOSE_LEVEL_MASK 3'b111", params)
+        self.assertIn("`define P4_CLOSE_LIMIT_IS_LS_MASK 3'b111", params)
+
+    def test_fresh_generation_matches_checked_in_masks(self):
+        with tempfile.TemporaryDirectory() as directory:
+            out = Path(directory)
+            generate_project(PROJECT_PATH, out)
+            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
+            checked = PARAMS_PATH.read_text(encoding="utf-8")
+            for define in (
+                "P4_LIMIT_ACTIVE_HIGH_MASK",
+                "P4_DIR_CLOSE_LEVEL_MASK",
+                "P4_CLOSE_LIMIT_IS_LS_MASK",
+            ):
+                self.assertIn(f"`define {define} 3'b111", params)
+                self.assertIn(f"`define {define} 3'b111", checked)
+
+    def test_checked_in_masks_match_project_json(self):
+        """Fail closed when params.vh polarity masks drift from project.json."""
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        params = PARAMS_PATH.read_text(encoding="utf-8")
+        expected = {
+            "P4_LIMIT_ACTIVE_HIGH_MASK": _axis_mask_literal(
+                project["limits"]["limit_active_high"], 3
+            ),
+            "P4_DIR_CLOSE_LEVEL_MASK": _axis_mask_literal(
+                project["motors"]["dir_close_level"], 3
+            ),
+            "P4_CLOSE_LIMIT_IS_LS_MASK": _axis_mask_literal(
+                project["limits"]["close_limit_is_ls"], 3
+            ),
+        }
+        for name, literal in expected.items():
+            self.assertEqual(_mask_define(params, name), literal, name)
+
+    def test_render_params_respects_alternate_masks(self):
+        project = load_project(PROJECT_PATH)
+        alt = copy.deepcopy(project)
+        # Bypass production lock by rendering from a mutated copy directly.
+        alt["limits"]["limit_active_high"] = [False, False, False]
+        alt["motors"]["dir_close_level"] = [0, 0, 0]
+        alt["limits"]["close_limit_is_ls"] = [False, False, False]
+        params = _render_params(alt)
+        self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b000", params)
+        self.assertIn("`define P4_DIR_CLOSE_LEVEL_MASK 3'b000", params)
+        self.assertIn("`define P4_CLOSE_LIMIT_IS_LS_MASK 3'b000", params)
+
+    def test_mixed_axis_mask_order(self):
+        project = load_project(PROJECT_PATH)
+        alt = copy.deepcopy(project)
+        # X default, Y active-low + DIR invert, Z LS/HS swap.
+        alt["limits"]["limit_active_high"] = [True, False, True]
+        alt["motors"]["dir_close_level"] = [1, 0, 1]
+        alt["limits"]["close_limit_is_ls"] = [True, True, False]
+        params = _render_params(alt)
+        self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b101", params)
+        self.assertIn("`define P4_DIR_CLOSE_LEVEL_MASK 3'b101", params)
+        self.assertIn("`define P4_CLOSE_LIMIT_IS_LS_MASK 3'b011", params)
+
+    def test_rejects_wrong_length_dir_close_level(self):
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        project["motors"]["dir_close_level"] = [1, 1]
+        with tempfile.TemporaryDirectory() as directory:
+            bad = Path(directory) / "project.json"
+            bad.write_text(json.dumps(project), encoding="utf-8")
+            with self.assertRaises(Exception):
+                load_project(bad)
+
+    def test_rejects_non_boolean_limit_active_high(self):
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        project["limits"]["limit_active_high"] = [1, 1, 1]
+        with tempfile.TemporaryDirectory() as directory:
+            bad = Path(directory) / "project.json"
+            bad.write_text(json.dumps(project), encoding="utf-8")
+            with self.assertRaises(Exception):
+                load_project(bad)
+
+
+def _mask_define(params: str, name: str) -> str:
+    needle = f"`define {name} "
+    for line in params.splitlines():
+        if line.startswith(needle):
+            return line[len(needle) :].strip()
+    raise AssertionError(f"missing {name}")
+
+
+class AlternateConfigMaskMatrixTests(unittest.TestCase):
+    """Thin generator matrix: prove representative alt configs emit correct masks.
+
+    Production load_project locks defaults; these cases mutate a deep copy and
+    call _render_params only (no second firmware / no project.json rewrite).
+    """
+
+    # name -> (limit_active_high, dir_close_level, close_limit_is_ls,
+    #          expected_active_mask, expected_dir_mask, expected_close_ls_mask)
+    CASES = (
+        (
+            "all_default",
+            [True, True, True],
+            [1, 1, 1],
+            [True, True, True],
+            "3'b111",
+            "3'b111",
+            "3'b111",
+        ),
+        (
+            "all_active_low",
+            [False, False, False],
+            [1, 1, 1],
+            [True, True, True],
+            "3'b000",
+            "3'b111",
+            "3'b111",
+        ),
+        (
+            "dir_all_invert",
+            [True, True, True],
+            [0, 0, 0],
+            [True, True, True],
+            "3'b111",
+            "3'b000",
+            "3'b111",
+        ),
+        (
+            "ls_hs_all_swap",
+            [True, True, True],
+            [1, 1, 1],
+            [False, False, False],
+            "3'b111",
+            "3'b111",
+            "3'b000",
+        ),
+        (
+            "all_three_inverted",
+            [False, False, False],
+            [0, 0, 0],
+            [False, False, False],
+            "3'b000",
+            "3'b000",
+            "3'b000",
+        ),
+        (
+            "mixed_xyz",
+            # X default / Y active-low + DIR invert / Z LS-HS swap
+            [True, False, True],
+            [1, 0, 1],
+            [True, True, False],
+            "3'b101",
+            "3'b101",
+            "3'b011",
+        ),
+    )
+
+    def test_alternate_config_mask_matrix(self):
+        base = load_project(PROJECT_PATH)
+        for (
+            name,
+            limit_active_high,
+            dir_close_level,
+            close_limit_is_ls,
+            exp_active,
+            exp_dir,
+            exp_close_ls,
+        ) in self.CASES:
+            with self.subTest(name=name):
+                alt = copy.deepcopy(base)
+                alt["limits"]["limit_active_high"] = list(limit_active_high)
+                alt["motors"]["dir_close_level"] = list(dir_close_level)
+                alt["limits"]["close_limit_is_ls"] = list(close_limit_is_ls)
+                params = _render_params(alt)
+                self.assertEqual(
+                    _mask_define(params, "P4_LIMIT_ACTIVE_HIGH_MASK"),
+                    exp_active,
+                    name,
+                )
+                self.assertEqual(
+                    _mask_define(params, "P4_DIR_CLOSE_LEVEL_MASK"),
+                    exp_dir,
+                    name,
+                )
+                self.assertEqual(
+                    _mask_define(params, "P4_CLOSE_LIMIT_IS_LS_MASK"),
+                    exp_close_ls,
+                    name,
+                )
+                # Bit-order cross-check via shared helper (LSB=X).
+                self.assertEqual(
+                    _axis_mask_literal(limit_active_high, 3), exp_active, name
+                )
+                self.assertEqual(
+                    _axis_mask_literal(dir_close_level, 3), exp_dir, name
+                )
+                self.assertEqual(
+                    _axis_mask_literal(close_limit_is_ls, 3), exp_close_ls, name
+                )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 1 - 1
tests/unit/test_startup_close_seek.py

@@ -74,7 +74,7 @@ class StartupCloseSeekContractTests(unittest.TestCase):
         source = (ROOT / "src" / "modules" / "startup_close_seek.v").read_text(encoding="utf-8")
         source = (ROOT / "src" / "modules" / "startup_close_seek.v").read_text(encoding="utf-8")
         for marker in (
         for marker in (
             "ST_WAIT_SYNC", "ST_CLOSE_START", "ST_CLOSE_WAIT", "ST_BACKOFF_START",
             "ST_WAIT_SYNC", "ST_CLOSE_START", "ST_CLOSE_WAIT", "ST_BACKOFF_START",
-            "limit_sync_valid", "limit_ls_sync", "limit_hs_sync", "motor_stop_mask",
+            "limit_sync_valid", "close_limit", "open_limit", "motor_stop_mask",
             "CLOSE_STEPS", "BACKOFF_STEPS", "AXIS_COUNT",
             "CLOSE_STEPS", "BACKOFF_STEPS", "AXIS_COUNT",
         ):
         ):
             self.assertIn(marker, source)
             self.assertIn(marker, source)

+ 1 - 1
tests/unit/test_startup_mutation.py

@@ -71,7 +71,7 @@ module tb;
     ) dut (
     ) dut (
         .clk(clk), .rst_n(rst_n),
         .clk(clk), .rst_n(rst_n),
         .limit_sync_valid(limit_sync_valid),
         .limit_sync_valid(limit_sync_valid),
-        .limit_ls_sync(limit_ls), .limit_hs_sync(limit_hs),
+        .close_limit(limit_ls), .open_limit(limit_hs),
         .startup_done(startup_done), .motor_start(motor_start),
         .startup_done(startup_done), .motor_start(motor_start),
         .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
         .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
         .motor_step_count(motor_step_count), .motor_stop_mask(motor_stop_mask),
         .motor_step_count(motor_step_count), .motor_stop_mask(motor_stop_mask),

+ 5 - 18
tests/unit/test_top_step_gate_matches_formal.py

@@ -14,25 +14,12 @@ FORMAL = ROOT / "tests/formal/runtime_limit_hard_stop_formal.v"
 
 
 def _normalize_gate_expr(expr: str) -> str:
 def _normalize_gate_expr(expr: str) -> str:
     text = re.sub(r"\s+", "", expr)
     text = re.sub(r"\s+", "", expr)
-    # Formal uses limit_*_sync[i]; top uses x/y/z_limit_*_sync1.
-    text = text.replace("x_limit_ls_sync1", "limit_ls_sync[0]")
-    text = text.replace("x_limit_hs_sync1", "limit_hs_sync[0]")
-    text = text.replace("y_limit_ls_sync1", "limit_ls_sync[1]")
-    text = text.replace("y_limit_hs_sync1", "limit_hs_sync[1]")
-    text = text.replace("z_limit_ls_sync1", "limit_ls_sync[2]")
-    text = text.replace("z_limit_hs_sync1", "limit_hs_sync[2]")
     text = text.replace("engine_step[0]", "engine_step")
     text = text.replace("engine_step[0]", "engine_step")
-    text = text.replace("engine_dir[0]", "engine_dir")
     text = text.replace("engine_step[1]", "engine_step")
     text = text.replace("engine_step[1]", "engine_step")
-    text = text.replace("engine_dir[1]", "engine_dir")
     text = text.replace("engine_step[2]", "engine_step")
     text = text.replace("engine_step[2]", "engine_step")
-    text = text.replace("engine_dir[2]", "engine_dir")
-    text = text.replace("limit_ls_sync[0]", "LS")
-    text = text.replace("limit_hs_sync[0]", "HS")
-    text = text.replace("limit_ls_sync[1]", "LS")
-    text = text.replace("limit_hs_sync[1]", "HS")
-    text = text.replace("limit_ls_sync[2]", "LS")
-    text = text.replace("limit_hs_sync[2]", "HS")
+    text = text.replace("selected_limit[0]", "selected_limit")
+    text = text.replace("selected_limit[1]", "selected_limit")
+    text = text.replace("selected_limit[2]", "selected_limit")
     return text
     return text
 
 
 
 
@@ -70,9 +57,9 @@ class TopStepGateMatchesFormalTests(unittest.TestCase):
                 formal_gates[axis],
                 formal_gates[axis],
                 f"axis {axis}: top={top_gates[axis]!r} formal={formal_gates[axis]!r}",
                 f"axis {axis}: top={top_gates[axis]!r} formal={formal_gates[axis]!r}",
             )
             )
-        # Canonical shape: engine_step & ~(engine_dir ? LS : HS)
+        # Canonical shape: engine_step & ~selected_limit
         for axis, expr in top_gates.items():
         for axis, expr in top_gates.items():
-            self.assertIn("engine_step&~(engine_dir?LS:HS)", expr, axis)
+            self.assertIn("engine_step&~selected_limit", expr, axis)
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 58 - 0
tools/build_firmware_package.py

@@ -58,6 +58,61 @@ def _read_json(path: Path) -> Any:
     return json.loads(path.read_text(encoding="utf-8-sig"))
     return json.loads(path.read_text(encoding="utf-8-sig"))
 
 
 
 
+def _mask_define_from_params(params_text: str, name: str) -> str:
+    needle = f"`define {name} "
+    for line in params_text.splitlines():
+        if line.startswith(needle):
+            return line[len(needle) :].strip()
+    raise PackagingError(f"missing `{name}` in prod2u_door_temp_params.vh")
+
+
+def _axis_mask_literal_from_values(values: list[Any], axis_count: int = 3) -> str:
+    if len(values) != axis_count:
+        raise PackagingError(f"axis mask length mismatch: expected {axis_count}, got {len(values)}")
+    bits = "".join("1" if bool(v) else "0" for v in reversed(values))
+    return f"{axis_count}'b{bits}"
+
+
+def motor_polarity_config_identity(repo_root: Path | None = None) -> dict[str, Any]:
+    """Fingerprint motor polarity masks from project.json and bind to params.vh.
+
+    Fail-closed when checked-in params drift from the project contract.
+    """
+    root = repo_root or ROOT
+    project = _read_json(root / "projects" / "prod2u-door-temp" / "project.json")
+    params_path = root / "src" / "generated" / "prod2u_door_temp_params.vh"
+    params_text = params_path.read_text(encoding="utf-8")
+    expected = {
+        "limit_active_high_mask": _axis_mask_literal_from_values(
+            list(project["limits"]["limit_active_high"])
+        ),
+        "dir_close_level_mask": _axis_mask_literal_from_values(
+            list(project["motors"]["dir_close_level"])
+        ),
+        "close_limit_is_ls_mask": _axis_mask_literal_from_values(
+            list(project["limits"]["close_limit_is_ls"])
+        ),
+    }
+    observed = {
+        "limit_active_high_mask": _mask_define_from_params(params_text, "P4_LIMIT_ACTIVE_HIGH_MASK"),
+        "dir_close_level_mask": _mask_define_from_params(params_text, "P4_DIR_CLOSE_LEVEL_MASK"),
+        "close_limit_is_ls_mask": _mask_define_from_params(params_text, "P4_CLOSE_LIMIT_IS_LS_MASK"),
+    }
+    if observed != expected:
+        raise PackagingError(
+            f"motor polarity masks mismatch project.json vs params.vh: "
+            f"expected={expected} observed={observed}"
+        )
+    fingerprint_payload = json.dumps(expected, sort_keys=True, separators=(",", ":")).encode("utf-8")
+    return {
+        "limit_active_high": list(project["limits"]["limit_active_high"]),
+        "dir_close_level": list(project["motors"]["dir_close_level"]),
+        "close_limit_is_ls": list(project["limits"]["close_limit_is_ls"]),
+        "masks": expected,
+        "sha256": _sha256_bytes(fingerprint_payload),
+    }
+
+
 def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes:
 def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes:
     """Return the contents of a tracked path at a specific commit."""
     """Return the contents of a tracked path at a specific commit."""
     completed = subprocess.run(
     completed = subprocess.run(
@@ -382,6 +437,8 @@ def build_firmware_package(
             f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
             f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
         )
         )
 
 
+    motor_polarity = motor_polarity_config_identity(ROOT)
+
     comparison = generate_source_closure_comparison(
     comparison = generate_source_closure_comparison(
         td_report=td_report,
         td_report=td_report,
         artifact_commit=artifact_commit,
         artifact_commit=artifact_commit,
@@ -445,6 +502,7 @@ def build_firmware_package(
         "source_closure_unchanged": bool(comparison["source_closure_equal"]),
         "source_closure_unchanged": bool(comparison["source_closure_equal"]),
         "source_closure_comparison_mode": comparison["mode"],
         "source_closure_comparison_mode": comparison["mode"],
         "project_config_sha256": current_project_sha,
         "project_config_sha256": current_project_sha,
+        "motor_polarity_config": motor_polarity,
         "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
         "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
         "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
         "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
         "source_closure_comparison_sha256": comparison_sha256,
         "source_closure_comparison_sha256": comparison_sha256,

+ 54 - 1
tools/generate_project.py

@@ -88,6 +88,18 @@ def _list(value: Any, name: str, length: int | None = None) -> list[Any]:
     return value
     return value
 
 
 
 
+def _axis_mask_literal(values: list[Any], axis_count: int) -> str:
+    """Build AXIS_COUNT'b... with bit0=X (LSB / rightmost), index0=X,1=Y,2=Z."""
+    _require(len(values) == axis_count, "axis mask length mismatch")
+    bits_lsb_first: list[str] = []
+    for value in values:
+        if isinstance(value, bool):
+            bits_lsb_first.append("1" if value else "0")
+        else:
+            bits_lsb_first.append("1" if int(value) else "0")
+    return f"{axis_count}'b" + "".join(reversed(bits_lsb_first))
+
+
 def _validate_channel(channel: Any, index: int, kind: str) -> None:
 def _validate_channel(channel: Any, index: int, kind: str) -> None:
     item = _object(channel, f"{kind}_channels[{index}]")
     item = _object(channel, f"{kind}_channels[{index}]")
     _keys(item, {"index", "name", "signal", "board_signal", "ball", "connector", "connector_pin", "polarity"}, f"{kind}_channels[{index}]")
     _keys(item, {"index", "name", "signal", "board_signal", "ball", "connector", "connector_pin", "polarity"}, f"{kind}_channels[{index}]")
@@ -206,6 +218,7 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
             "heartbeat_value",
             "heartbeat_value",
             "open_dir_value",
             "open_dir_value",
             "close_dir_value",
             "close_dir_value",
+            "dir_close_level",
             "mapping",
             "mapping",
             "enable_n",
             "enable_n",
         },
         },
@@ -222,6 +235,15 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     _integer(motors["dir_setup_cycles"], "motors.dir_setup_cycles", minimum=0)
     _integer(motors["dir_setup_cycles"], "motors.dir_setup_cycles", minimum=0)
     _require(isinstance(motors["command_values"], list) and motors["command_values"], "invalid motor commands")
     _require(isinstance(motors["command_values"], list) and motors["command_values"], "invalid motor commands")
     _require(motors["heartbeat_value"] in motors["command_values"], "motor heartbeat is not a command")
     _require(motors["heartbeat_value"] in motors["command_values"], "motor heartbeat is not a command")
+    _integer(motors["open_dir_value"], "motors.open_dir_value", minimum=0)
+    _integer(motors["close_dir_value"], "motors.close_dir_value", minimum=0)
+    _require(motors["open_dir_value"] == 0, "logical open_dir_value must be 0")
+    _require(motors["close_dir_value"] == 1, "logical close_dir_value must be 1")
+    dir_close_level = _list(motors["dir_close_level"], "motors.dir_close_level", length=motors["count"])
+    for index, level in enumerate(dir_close_level):
+        _require(isinstance(level, int) and not isinstance(level, bool) and level in (0, 1),
+                 f"motors.dir_close_level[{index}] must be 0 or 1")
+    _require(dir_close_level == [1, 1, 1], "production dir_close_level must be [1,1,1]")
     mapping = _object(motors["mapping"], "motors.mapping")
     mapping = _object(motors["mapping"], "motors.mapping")
     _require(motors["count"] == 3 and motors["order"] == ["x", "y", "z"], "production motor count/order must be x,y,z")
     _require(motors["count"] == 3 and motors["order"] == ["x", "y", "z"], "production motor count/order must be x,y,z")
     _keys(mapping, {"x", "y", "z"}, "motors.mapping")
     _keys(mapping, {"x", "y", "z"}, "motors.mapping")
@@ -237,10 +259,35 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     _require(enable["policy"] == "permanent_high", "motor enable policy must be permanent_high")
     _require(enable["policy"] == "permanent_high", "motor enable policy must be permanent_high")
 
 
     limits = _object(payload["limits"], "limits")
     limits = _object(payload["limits"], "limits")
-    _keys(limits, {"limit_count", "active_level", "functional_use", "runtime_use", "startup", "channels"}, "limits")
+    _keys(
+        limits,
+        {
+            "limit_count",
+            "active_level",
+            "limit_active_high",
+            "close_limit_is_ls",
+            "functional_use",
+            "runtime_use",
+            "startup",
+            "channels",
+        },
+        "limits",
+    )
     _require(limits["limit_count"] == len(limits["channels"]) == 6, "limit count/list mismatch")
     _require(limits["limit_count"] == len(limits["channels"]) == 6, "limit count/list mismatch")
     _require(limits["active_level"] == "high" and limits["functional_use"] is True, "limit policy mismatch")
     _require(limits["active_level"] == "high" and limits["functional_use"] is True, "limit policy mismatch")
     _require(limits["runtime_use"] is True, "runtime limit use must be true")
     _require(limits["runtime_use"] is True, "runtime limit use must be true")
+    limit_active_high = _list(limits["limit_active_high"], "limits.limit_active_high", length=motors["count"])
+    for index, active_high in enumerate(limit_active_high):
+        _require(isinstance(active_high, bool), f"limits.limit_active_high[{index}] must be a boolean")
+    _require(limit_active_high == [True, True, True], "production limit_active_high must be [true,true,true]")
+    close_limit_is_ls = _list(limits["close_limit_is_ls"], "limits.close_limit_is_ls", length=motors["count"])
+    for index, close_is_ls in enumerate(close_limit_is_ls):
+        _require(isinstance(close_is_ls, bool), f"limits.close_limit_is_ls[{index}] must be a boolean")
+    _require(close_limit_is_ls == [True, True, True], "production close_limit_is_ls must be [true,true,true]")
+    _require(
+        all(limit_active_high) == (limits["active_level"] == "high"),
+        "limits.active_level must match limit_active_high aggregate",
+    )
     startup = _object(limits["startup"], "limits.startup")
     startup = _object(limits["startup"], "limits.startup")
     _keys(
     _keys(
         startup,
         startup,
@@ -570,11 +617,17 @@ def _render_params(project: Mapping[str, Any]) -> str:
     frame_inter_byte_timeout_cycles = project["device"]["clock_hz"] * project["timeouts"]["frame_inter_byte_ms"] // 1000
     frame_inter_byte_timeout_cycles = project["device"]["clock_hz"] * project["timeouts"]["frame_inter_byte_ms"] // 1000
     startup_dir_bit = startup["direction_value"]
     startup_dir_bit = startup["direction_value"]
     startup_dir_mask = f"{axis_count}'b" + (str(startup_dir_bit) * axis_count)
     startup_dir_mask = f"{axis_count}'b" + (str(startup_dir_bit) * axis_count)
+    limit_active_high_mask = _axis_mask_literal(limits["limit_active_high"], axis_count)
+    dir_close_level_mask = _axis_mask_literal(motors["dir_close_level"], axis_count)
+    close_limit_is_ls_mask = _axis_mask_literal(limits["close_limit_is_ls"], axis_count)
     lines = [
     lines = [
         "// Generated from project.json. Do not edit.",
         "// Generated from project.json. Do not edit.",
         f"`define P4_AXIS_COUNT {axis_count}",
         f"`define P4_AXIS_COUNT {axis_count}",
         f"`define P4_LIMIT_COUNT {limits['limit_count']}",
         f"`define P4_LIMIT_COUNT {limits['limit_count']}",
         f"`define P4_RUNTIME_LIMIT_USE {1 if limits['runtime_use'] else 0}",
         f"`define P4_RUNTIME_LIMIT_USE {1 if limits['runtime_use'] else 0}",
+        f"`define P4_LIMIT_ACTIVE_HIGH_MASK {limit_active_high_mask}",
+        f"`define P4_DIR_CLOSE_LEVEL_MASK {dir_close_level_mask}",
+        f"`define P4_CLOSE_LIMIT_IS_LS_MASK {close_limit_is_ls_mask}",
         f"`define P4_CLOCK_HZ {project['device']['clock_hz']}",
         f"`define P4_CLOCK_HZ {project['device']['clock_hz']}",
         f"`define P4_UART_BAUD {uart['baud']}",
         f"`define P4_UART_BAUD {uart['baud']}",
         f"`define P4_UART_CLKS_PER_BIT {uart['clks_per_bit']}",
         f"`define P4_UART_CLKS_PER_BIT {uart['clks_per_bit']}",