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

feat(door): percent positioning motion stack on preview branch

Replace fixed-step jog with open-loop percent close positioning,
seek-close/measure-open calibration, 30s watchdog FAN10, and
GET_MOTOR_STATUS 0x03/0x83. Stay on preview/door-percent-positioning;
do not touch dev.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 месяцев назад
Родитель
Сommit
3ad444fbc8
86 измененных файлов с 3762 добавлено и 3649 удалено
  1. 19 21
      ACCEPTANCE_MATRIX.md
  2. 19 14
      AGENTS.md
  3. 16 47
      FINAL_DELIVERY_REPORT.md
  4. 10 11
      OPEN_QUESTIONS.md
  5. 18 20
      PLAN.md
  6. 24 22
      README.zh-CN.md
  7. 18 47
      config/prod2u_p4_verification_targets_v1.json
  8. 3 3
      config/source_closure.json
  9. 26 22
      docs/HARDWARE_BRINGUP_NOTES.zh-CN.md
  10. 32 27
      docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md
  11. 7 11
      docs/TD_USAGE.zh-CN.md
  12. 95 22
      docs/prod2u-door-temp-protocol.zh-CN.md
  13. 44 15
      projects/prod2u-door-temp/project.json
  14. 26 14
      projects/prod2u-door-temp/requirements.zh-CN.md
  15. 0 0
      reference/historical/legacy-old-contract/door_action_dispatcher.v
  16. 0 0
      reference/historical/legacy-old-contract/door_motor_engine.v
  17. 0 0
      reference/historical/legacy-old-contract/startup_close_seek.v
  18. 0 0
      reference/historical/legacy-old-contract/tests/door_action_dispatcher_axis3.sby
  19. 0 0
      reference/historical/legacy-old-contract/tests/door_action_dispatcher_axis3_formal.v
  20. 0 0
      reference/historical/legacy-old-contract/tests/door_action_dispatcher_tb.v
  21. 0 0
      reference/historical/legacy-old-contract/tests/door_motor_engine_stop_tb.v
  22. 0 0
      reference/historical/legacy-old-contract/tests/door_motor_engine_tb.v
  23. 0 0
      reference/historical/legacy-old-contract/tests/startup_close_seek.sby
  24. 0 0
      reference/historical/legacy-old-contract/tests/startup_close_seek_formal.v
  25. 0 0
      reference/historical/legacy-old-contract/tests/startup_close_seek_tb.v
  26. 0 0
      reference/historical/legacy-old-contract/tests/startup_motor_stop_tb.v
  27. 168 45
      schemas/project.schema.json
  28. 6 4
      src/common/frame_tx.v
  29. 13 3
      src/generated/golden-vectors.json
  30. 113 26
      src/generated/host-contract.json
  31. 36 7
      src/generated/prod2u_door_temp_params.vh
  32. 3 3
      src/generated/project-summary.json
  33. 17 8
      src/generated/td-source-manifest.json
  34. 644 0
      src/modules/door_axis_controller.v
  35. 269 0
      src/modules/door_motion_controller.v
  36. 84 0
      src/modules/door_percent_planner.v
  37. 16 2
      src/modules/host_watchdog.v
  38. 77 25
      src/project/command_controller.v
  39. 35 36
      src/project/project_adapter.v
  40. 85 90
      src/top/prod2u_p4_normal_v3_top.v
  41. 3 3
      td/prod2u_p4_normal_v3.prj
  42. 3 3
      td/syn/prod2u_p4_normal_v3.tcl
  43. 1 1
      tests/cocotb/run_prod2u_door_temp_uart_e2e.py
  44. 94 127
      tests/cocotb/test_prod2u_door_temp_uart_e2e.py
  45. 8 7
      tests/formal/README.md
  46. 21 0
      tests/formal/door_axis_cal.sby
  47. 38 0
      tests/formal/door_axis_cal_formal.v
  48. 23 0
      tests/formal/door_percent_planner.sby
  49. 45 0
      tests/formal/door_percent_planner_formal.v
  50. 0 2
      tests/formal/frame_command_contract.sby
  51. 42 45
      tests/formal/frame_command_contract_formal.v
  52. 0 2
      tests/formal/host_watchdog_contract.sby
  53. 21 97
      tests/formal/host_watchdog_contract_formal.v
  54. 0 2
      tests/formal/runtime_limit_hard_stop.sby
  55. 24 161
      tests/formal/runtime_limit_hard_stop_formal.v
  56. 7 10
      tests/formal/simple_motor_temperature_contract.sby
  57. 25 105
      tests/formal/simple_motor_temperature_contract_formal.v
  58. 140 0
      tests/sim/door_motion_controller_tb.v
  59. 64 0
      tests/sim/door_percent_planner_tb.v
  60. 16 3
      tests/sim/host_watchdog_tb.v
  61. 56 487
      tests/sim/prod2u_p4_alt_config_polarity_tb.v
  62. 22 436
      tests/sim/prod2u_p4_alt_config_startup_tb.v
  63. 19 290
      tests/sim/prod2u_p4_normal_v3_top_runtime_limit_tb.v
  64. 41 97
      tests/sim/prod2u_p4_normal_v3_top_startup_tb.v
  65. 96 141
      tests/sim/project_adapter_tb.v
  66. 39 211
      tests/unit/test_activity_docs_truth.py
  67. 73 0
      tests/unit/test_door_percent_calibration_contract.py
  68. 99 0
      tests/unit/test_door_percent_planner_exhaustive.py
  69. 19 19
      tests/unit/test_negative_tool_fixtures.py
  70. 4 3
      tests/unit/test_phase1_contract.py
  71. 40 98
      tests/unit/test_phase2_contract.py
  72. 50 205
      tests/unit/test_phase3_formal_contract.py
  73. 34 132
      tests/unit/test_product_contract_coverage.py
  74. 7 4
      tests/unit/test_project_config.py
  75. 20 37
      tests/unit/test_project_generation.py
  76. 50 33
      tests/unit/test_protocol.py
  77. 0 84
      tests/unit/test_startup_close_seek.py
  78. 0 119
      tests/unit/test_startup_mutation.py
  79. 26 20
      tests/unit/test_three_axis_door_contract.py
  80. 8 20
      tests/unit/test_top_step_gate_matches_formal.py
  81. 4 5
      tests/verilator_waivers.vlt
  82. 36 0
      tools/door_percent_planner_ref.py
  83. 289 60
      tools/generate_project.py
  84. 8 0
      tools/prod2u_p4_harness.py
  85. 223 34
      tools/prod2u_simple_protocol.py
  86. 1 1
      tools/test_profiles.py

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


+ 19 - 14
AGENTS.md

@@ -6,14 +6,14 @@ Current authority is limited to the above contract files, this `AGENTS.md`, and
 
 ## Execution priorities
 
-1. Core limit one-shot behavior and startup close/seek first.
+1. Core limit one-shot behavior and startup calibration (seek-close then measure-open) first.
 2. Keep behavior simple and deterministic inside the declared constraints.
 3. Form a minimally usable, synthesizable version quickly.
 4. Reduce LUT and Slice after core function is correct.
 5. Reduce LUT and Packed Slice after core function is correct.
 6. Generalization, security, exception coverage, compatibility, long-term maintenance, performance tuning, and perfect documentation are lower priority.
 
-"Reliable" means deterministic under these assumptions: host obeys command order; no new command is sent while a motor is running; duty is 0..100; motor command is 00/01/02; no undeclared concurrency; hardware wiring matches the current project/ADC.
+"Reliable" means deterministic under these assumptions: host may send a new door percent while an axis is moving (latest-wins; at most one already-started STEP finishes); duty and door percent are 0..100; mid positions are open-loop estimates from gated STEP rises and startup-measured travel; no undeclared command queue; hardware wiring matches the current project/ADC.
 
 ## Model and effort policy
 
@@ -40,16 +40,21 @@ Current authority is limited to the above contract files, this `AGENTS.md`, and
 
 ## Product contract
 
+> **破坏性协议迁移(勿按旧上位机假设发帧)**  
+> 旧合同:门字节 `00`=不启动 jog / 心跳,`01`=开 450 步,`02`=关 450 步;busy 忽略新门命令;watchdog 10 s → FAN 20;startup 关门寻限 + 未命中则 500 步 backoff。  
+> **新合同**:门字节为闭合百分比 `00`=全开 … `64`=全关;合法 SET_ALL latest-wins;位置按 gated STEP 计数;标定先 seek-close 再 measure-open;watchdog **30 s → PTC 0 / FAN 10**;新增 `GET_MOTOR_STATUS 0x03` / `MOTOR_STATUS_DATA 0x83`(31 字节 payload)。无 ACK / 无命令队列。旧上位机若继续把三门填 `00` 当心跳,将驱动三轴核对并运行到**全开**限位。
+
 - UART: 25 MHz, 115200 8N1, 217 clocks/bit, A5 5A framing, CRC-16/CCITT-FALSE.
-- Supported frame types: `0x01 SET_ALL`, `0x02 GET_TEMPERATURE`, `0x82 TEMPERATURE_DATA`.
-- SET_ALL payload: 4 FAN + 4 chamber PTC (each duplicated to 2 physical PTC PWM) + Z/X/Y door bytes (11 bytes total).
-- Door byte `00`: no new jog; while busy, ignore (does not stop or override running motion). `01` open / `02` close.
+- Supported frame types: `0x01 SET_ALL`, `0x02 GET_TEMPERATURE`, `0x03 GET_MOTOR_STATUS`, `0x82 TEMPERATURE_DATA`, `0x83 MOTOR_STATUS_DATA`.
+- SET_ALL payload: 4 FAN + 4 chamber PTC (each duplicated to 2 physical PTC PWM) + Z/X/Y door **percent** bytes (11 bytes total).
+- Door byte `0..100`: close-percent target (`0`=full open, `100`=full close). Values `101..255` reject the whole frame.
+- After `startup_complete`: each valid SET_ALL commits thermal + three axis requested percents atomically and feeds the watchdog (including identical repeats). Different percent → latest-wins replan.
 - PTC active high; FAN active low at FPGA output.
 - PWM ~20 Hz.
-- Watchdog 10 s -> PTC 0, FAN 20.
-- Ordinary motor move: 450 steps at 1000 steps/s. X, Y, and Z may overlap.
+- Watchdog 30 s -> PTC 0, FAN 10 (enabled only after `startup_complete`).
+- Motion: open-loop percent positioning from startup-measured `travel_steps`; mid targets use half-up clamp to `1..travel-1`; endpoints 0/100 complete only on real open/close limits. X, Y, and Z may overlap.
 - Motor EN: CON120.2 / C11, NPN invert at board; FPGA constant 1 (`permanent_high`).
-- No ACK, BUSY, ERROR, command queue, preemption, legacy protocol compatibility, background temperature scan, or solenoid actuator.
+- No ACK, BUSY, ERROR, command queue, legacy jog compatibility, background temperature scan, or solenoid actuator.
 
 ## Limit and startup contract
 
@@ -58,11 +63,11 @@ Current authority is limited to the above contract files, this `AGENTS.md`, and
   - Y: LS CON12.3 C8, HS CON12.4 A8
   - Z: LS CON129.1 K16, HS CON129.2 J15
 - Motors: X STEP/DIR CON104.2/3 C12/B12; Y CON105.2/3 L12/J11; Z CON106.2/3 L14/K14.
-- Runtime: direction-select limit hard-stop each clock; truncate current STEP high pulse immediately after synchronized limit (`truncate_current_high_pulse_immediately_after_synchronized_limit`); busy ignores new start.
-- Startup (once per power-on/reset/reconfig): PTC 0%, FAN 10%, all axes DIR=1 close; up to 5000 steps @ 1000 steps/s per axis; if limit not hit, 500-step backoff and mark missed; X/Y/Z may move concurrently and stop independently.
-- `startup_done` is sticky until next FPGA power-on, global hardware reset, or reconfiguration.
-- After `startup_done`: startup motor controls idle; ordinary host jog and runtime limit policy apply; limit FSM does not restart.
-- During `startup_done == 0`: SET_ALL and GET_TEMPERATURE are dropped; no caching, no response, watchdog is not fed; frame parser stays reset/flushed.
+- Runtime: direction-select limit hard-stop each clock; truncate current STEP high pulse immediately after synchronized limit (`truncate_current_high_pulse_immediately_after_synchronized_limit`). Ordinary command / watchdog / endpoint-guard stops do **not** truncate a high pulse; they forbid the next rise.
+- Startup calibration (once per power-on/reset/reconfig): PTC 0%, FAN 10%; each axis independently seek-close (≤5000 gated STEP) then measure-open (≤5000); `travel_steps` latched on success; **no** 500-step backoff. Failed axes FAULT-lock until reset; partial success allowed. X/Y/Z may move concurrently and stop independently.
+- `startup_complete` is sticky until next FPGA power-on, global hardware reset, or reconfiguration.
+- During calibration: valid SET_ALL may update FAN/PTC but **ignores** door percents (no cache); GET_MOTOR_STATUS allowed; GET_TEMPERATURE dropped (no response); watchdog not enabled/fed.
+- After `startup_complete`: host must re-send desired percents; ordinary percent motion and runtime limit policy apply; calibration FSM does not restart.
 
 ## Tooling preference
 
@@ -79,7 +84,7 @@ Current authority is limited to the above contract files, this `AGENTS.md`, and
 ## Necessary tests
 
 - Product, protocol, generator, packaging, and Git protection Python tests.
-- Icarus testbenches for the active Prod2U top, including startup close/seek and runtime limit hard-stop behavior.
+- Icarus testbenches for the active Prod2U top, including startup seek-close/measure-open calibration and runtime limit hard-stop / latest-wins behavior.
 - Verilator lint, cocotb UART tests, and formal checks when the environment is available and cost is reasonable.
 
 ## Evidence boundaries

Разница между файлами не показана из-за своего большого размера
+ 16 - 47
FINAL_DELIVERY_REPORT.md


+ 10 - 11
OPEN_QUESTIONS.md

@@ -1,25 +1,24 @@
 # Open Questions and Accepted Uncertainty
 
-No user product-contract decision currently blocks the **11-byte SET_ALL + three-axis X/Y/Z** software path.
+活动合同正在迁移到 **三轴风门百分比定位**(`preview/door-percent-positioning`)。下列不确定项不阻塞协议模型与活动文档切换。
 
 ## Accepted uncertainty / explicit status
 
 - **Hardware validation: `NOT RUN`** — COM/JTAG/programming not authorized.
-- **FINAL_COMMIT / tip TD / bitstream SHA-256**: bound — ARTIFACT-SOURCE-COMMIT `f23d6d4c57959071cd3886ea5503fbe903aee547`(极性配置 tip / TD);Bitstream SHA-256 `eb275921a3c25dcd9440c02677ea9b910e2bf5e57517bbad4ee063afa93e760a`; td2026 Release_2026.1_SP2 Build `6.2.2.200067`; RUN_ID `20260806T112210Z-3f2f5f2f`。相对旧 tip `0de9f939…` / 旧 bit `3143b87c…`:**SOURCE-CLOSURE-UNCHANGED=false**(生产输入已变)。
-- **DELIVERY-COMMIT**: 见 firmware 包 `FINAL-DEV-COMMIT.txt` / review-compact `meta/git/HEAD.txt`(活动文档不硬编码未产生的 tip)。Hardware **`NOT RUN`**.
-- Prior bypass firmware bitstream `45f548ab…` was built at `bb515af`, **not** tip — not active closure evidence.
-- Contract/source baseline for lanes merge start: `cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7`.
-- Active contract: X/Y/Z, six limits, 450/5000/500, EN `permanent_high`, hard truncate `truncate_current_high_pulse_immediately_after_synchronized_limit`. Runtime limits are **not** inert.
+- **新合同 RTL / 生成器 / 全量验证 / TD tip / bitstream**:重构进行中;旧 jog 闭包 tip/bitstream **不是**新合同 pass 证据。
+- **协议参考模型与活动文档**:已按新合同更新(门百分比、30 s WD FAN10、`0x03/0x83` 31B、标定 seek-close→measure-open、latest-wins)。
+- Active IO: CON104/105/106/120/12/129。Runtime limits are **not** inert.
+- 中间百分比为开环步数估计(无编码器);丢步/齿隙可使中间位置偏移;两端限位可在到端时纠正坐标。不引入运行期重标定或编码器。
 - PWM ~20 Hz is a protocol/debug target; it does not guarantee a specific fan mechanical speed or torque.
 
 ## Physical / evidence remaining uncertainties
 
 - Board bring-up and real fan/PTC/motor load behavior remain unverified until hardware is authorized.
 - Active IO probes: CON104/105/106 (STEP/DIR), CON120.2 (EN), CON12 + CON129 (six limits). Solenoid / CON68 / CON34 / CON138–141 are **not** active product IO (see `docs/historical/`).
-- Full KiCad `generate` of SVG layers was **not** re-run (cached PCB reannotate for CON12 board-data); geometry SVGs retained.
 
-## Non-goals
+## Non-goals / migration notes
 
-- Do not treat archived 2-axis/solenoid closure (`da7b05a`, TD `8f28660`, bitstream `ce3157c5…`) as current tip truth.
-- Do not present `45f548ab…` as tip bitstream.
-- Do not revive Windows packages (`d99f354` / `4ddfbec`, `C:\Users\...`) as current pass evidence.
+- Do not treat archived jog (`00/01/02` · 450 steps · WD 10s FAN20 · 500 backoff) as current tip truth.
+- Do not present historical bypass / old tip bitstreams as door-percent tip evidence.
+- Do not revive Windows packages as current pass evidence.
+- Do not invent Hardware pass.

+ 18 - 20
PLAN.md

@@ -1,29 +1,27 @@
-# Prod2U active plan pointer(三轴闭包)
+# Prod2U active plan pointer(door-percent 百分比定位重构)
 
-- Contract truth: X/Y/Z, six limits, 450/5000/500, EN `permanent_high`, hard truncate `truncate_current_high_pulse_immediately_after_synchronized_limit`
-- ARTIFACT-SOURCE-COMMIT / tip TD: `f23d6d4c57959071cd3886ea5503fbe903aee547`
-- DELIVERY-COMMIT: 见 firmware 包 `FINAL-DEV-COMMIT.txt` / review-compact `meta/git/HEAD.txt`
-- Bitstream SHA-256: `eb275921a3c25dcd9440c02677ea9b910e2bf5e57517bbad4ee063afa93e760a`
-- SOURCE-CLOSURE-UNCHANGED=false vs prior tip `0de9f939…` / prior bit `3143b87c…`
-- td2026: Release_2026.1_SP2 Build `6.2.2.200067` (RUN_ID `20260806T112210Z-3f2f5f2f`)
-- Historical bypass bit `45f548ab…` @ `bb515af` — **not** tip
-- Contract/source baseline tip: `cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7` (docs/contract lane start)
-- Hardware validation: **`not_run`**
-- Active IO: CON104/105/106/120/12/129 — **not** solenoid / CON68 / CON34 / CON138–141; runtime limit **not** inert
-- Package / replay: review-compact live Git provenance + firmware/release-set closure;raw reference reused(不进默认 compact);ARTIFACT/bitstream 复用 `f23d6d4` / `eb275921`(生产输入未变,不重跑 TD)
-- 三种状态:默认生产离线固件闭包 PASS;逐轴编译期配置能力 PASS;Hardware NOT RUN
+> **破坏性迁移**:旧 `00/01/02` jog · busy 忽略 · WD 10s FAN20 · startup+500 backoff →  
+> 新 `0..100` 闭合百分比 · latest-wins · WD **30s FAN10** · seek-close→measure-open · `0x03/0x83` 31B。
+
+- Contract truth(目标):X/Y/Z 百分比定位;六限位硬截断;标定双端测量 travel;EN `permanent_high`;`truncate_current_high_pulse_immediately_after_synchronized_limit`;无 ACK/队列
+- Preview branch:`preview/door-percent-positioning`
+- 协议参考模型 / 活动文档:本轮已切换到新合同
+- `project.json` / RTL / 生成器 / 测试:由并行 agent 按同一合同落地(本 PLAN 不宣称已全部合入)
+- Hardware validation:**`not_run`**
+- Active IO: CON104/105/106/120/12/129 — **not** solenoid / CON68 / CON34 / CON138–141
+- 旧 jog 闭包 tip/bitstream(如 `f23d6d4` / `eb275921…`)仅为迁移前历史证据,**不是**新合同 tip pass
 
 ## Closure sequence
 
-1. ~~Merge parallel lanes~~ done on `closure/integrate-3axis`.
-2. ~~Exclusive `td2026` on clean tip; bind full bitstream SHA-256~~ done.
-3. Full matrix + three-volume package; activity docs identity filled.
-4. Independent read-only review session (parent launches).
-5. Git provenance / detached replay / stable reference fingerprint / release-set upload closure(本轮).
+1. Five pre-audits PASS(`.chatgpt-handoff/round-8/pre-audits/`)。
+2. 并行落地:合同/生成器、RTL motion stack、协议模型+活动文档。
+3. 重写验证矩阵(Python / Icarus / cocotb / formal / Verilator)。
+4. 独占 `td2026` 新 source closure + 新 bitstream(禁止复用旧 jog bit)。
+5. Package / review-compact;Hardware 保持 NOT RUN;合入干净 `dev`。
 
 ## Authority
 
 - Linux `td2026` + OSS CAD / Python verification
 - Contract: `projects/prod2u-door-temp/project.json`, requirements, protocol, `AGENTS.md`
-- Active status docs: `README.zh-CN.md`, `ACCEPTANCE_MATRIX.md`, `FINAL_DELIVERY_REPORT.md`, `OPEN_QUESTIONS.md`
-- Superseded 2-axis/solenoid plans: [`docs/historical/`](docs/historical/)
+- Active status docs: `README.zh-CN.md`, `ACCEPTANCE_MATRIX.md`, `OPEN_QUESTIONS.md`, 本文件
+- Superseded jog / 2-axis/solenoid plans: [`docs/historical/`](docs/historical/)

+ 24 - 22
README.zh-CN.md

@@ -1,30 +1,35 @@
 # Prod2U 门控温度 CPLD
 
-本仓库实现 `prod2u-door-temp`:**四腔热控 + 腔体 1 三轴步进风门(X/Y/Z)**。25 MHz 主时钟、UART `115200 8N1`、无流控。统一帧为 `A5 5A type length payload CRC16_LE`。CRC-16/CCITT-FALSE 覆盖 type、length 与 payload,线路低字节在前。
+本仓库实现 `prod2u-door-temp`:**四腔热控 + 腔体 1 三轴风门百分比定位(X/Y/Z)**。25 MHz 主时钟、UART `115200 8N1`、无流控。统一帧为 `A5 5A type length payload CRC16_LE`。CRC-16/CCITT-FALSE 覆盖 type、length 与 payload,线路低字节在前。
 
 **权威执行环境:Linux 容器**(`td2026`、Python/Icarus/Verilator/formal/cocotb)。Windows 路径与旧收据仅作历史参考,见 [`docs/historical/`](docs/historical/)。
 
+> **破坏性协议迁移**:旧门字节 `00/01/02` jog(`00` 心跳不动作、`01/02` 各 450 步)、busy 忽略、watchdog 10 s→FAN20、startup+500 backoff **已废弃**。  
+> **新合同**:`00`=全开 … `100`=全关;latest-wins;标定 seek-close→measure-open;watchdog **30 s→FAN10**;`GET_MOTOR_STATUS 0x03` / `0x83`(31B)。旧上位机继续发三门 `00` 会驱动到全开限位——须改为重发真实期望百分比。详见 [`docs/prod2u-door-temp-protocol.zh-CN.md`](docs/prod2u-door-temp-protocol.zh-CN.md)。
+
 ## 正式帧类型
 
 | 类型 | 说明 |
 |---|---|
-| `0x01 SET_ALL` | **11 字节** payload:4 FAN + 4 chamber PTC(各复制到 2 路物理 PTC PWM)+ Z/X/Y 门字节;成功无回复。旧 14 字节 length `0x0E` 静默丢弃。 |
-| `0x02 GET_TEMPERATURE` | 空 payload;读完 27 项 CT7428 后只回一帧温度。 |
+| `0x01 SET_ALL` | **11 字节** payload:4 FAN + 4 chamber PTC(各复制到 2 路物理 PTC PWM)+ Z/X/Y **闭合百分比**;成功无回复。旧 14 字节 length `0x0E` 静默丢弃。 |
+| `0x02 GET_TEMPERATURE` | 空 payload;读完 27 项 CT7428 后只回一帧温度(标定期间丢弃)。 |
+| `0x03 GET_MOTOR_STATUS` | 空 payload;golden `A5 5A 03 00 5C 48`;标定期间也允许。 |
 | `0x82 TEMPERATURE_DATA` | 27 字节 payload,总帧长 33 字节。 |
+| `0x83 MOTOR_STATUS_DATA` | 31 字节 payload,总帧长 37 字节(全局 1B + X/Y/Z 各 10B)。 |
 
-PTC/FAN 占空为十进制 0..100。PWM ≈20 Hz。PTC active-high;FAN 在 FPGA 输出为 active-low。启动目标 PTC=0、FAN=10;看门狗 10 s → PTC=0、FAN=20。
+PTC/FAN 占空为十进制 0..100。PWM ≈20 Hz。PTC active-high;FAN 在 FPGA 输出为 active-low。启动目标 PTC=0、FAN=10;看门狗 **30 s → PTC=0、FAN=10**。
 
-### 门字节语义(三轴步进,无电磁铁)
+### 门字节语义(闭合百分比,无电磁铁)
 
-| 字节 | 轴 | `00` | `01` | `02` |
+| 字节 | 轴 | `0` | `1..99` | `100` |
 |---|---|---|---|---|
-| 偏移 8 | Z | 不启动新 jog(busy 忽略,不停止/不覆盖当前动作) | open DIR=0 | close DIR=1 |
-| 偏移 9 | X | 不启动新 jog(busy 忽略,不停止/不覆盖当前动作) | open DIR=0 | close DIR=1 |
-| 偏移 10 | Y | 不启动新 jog(busy 忽略,不停止/不覆盖当前动作) | open DIR=0 | close DIR=1 |
+| 偏移 8 | Z | 全开(认 open_limit) | 中间开环目标 | 全关(认 close_limit) |
+| 偏移 9 | X | 全开(认 open_limit) | 中间开环目标 | 全关(认 close_limit) |
+| 偏移 10 | Y | 全开(认 open_limit) | 中间开环目标 | 全关(认 close_limit) |
 
-普通 jog:**450** 步 @ 1000 step/s;X/Y/Z 可并行。电机 EN:CON120.2 / C11,FPGA `permanent_high`(板级 NPN 反相后座端永久使能)。详细合同见 [`docs/prod2u-door-temp-protocol.zh-CN.md`](docs/prod2u-door-temp-protocol.zh-CN.md) 与 `projects/prod2u-door-temp/project.json`。
+`startup_complete` 后合法 SET_ALL latest-wins;心跳=重发当前期望百分比。电机 EN:CON120.2 / C11,FPGA `permanent_high`。协议模型:`tools/prod2u_simple_protocol.py`。
 
-## 六限位与启动 / 运行期硬截断
+## 六限位与启动标定 / 运行期硬截断
 
 六路限位(FPGA active-high,`runtime_use=true`):
 
@@ -36,25 +41,21 @@ PTC/FAN 占空为十进制 0..100。PWM ≈20 Hz。PTC active-high;FAN 在 FPG
 
 马达:X CON104.2/3 C12/B12;Y CON105.2/3 L12/J11;Z CON106.2/3 L14/K14。
 
-- **Startup(上电一拍)**:PTC=0、FAN=10;三轴 DIR=1 关门寻限,每轴最多 **5000** 步 @ 1000 step/s;未命中则 **500** 步 backoff;`startup_done` 前主机帧丢弃。
-- **硬截断**:`stop_semantics=truncate_current_high_pulse_immediately_after_synchronized_limit`(同步限位后立即截断当前 STEP 高脉冲)。Startup 与运行期均硬停;runtime limits are **not** inert。
+- **Startup 标定**:PTC=0、FAN=10;每轴独立 **seek-close → measure-open**(各 ≤5000 gated STEP @ 1000 step/s);**无** 500 步 backoff;失败轴 FAULT;`startup_complete` 前门百分比忽略,GET_MOTOR_STATUS 可见。
+- **硬截断**:`stop_semantics=truncate_current_high_pulse_immediately_after_synchronized_limit`。限位硬停;命令/watchdog 优雅停。runtime limits are **not** inert。
 
 活动 IO **不是** 电磁铁 / CON68 / CON34 / CON138–141;旧二轴+电磁铁叙述见 [`docs/historical/`](docs/historical/)。
 
-## 当前基线与验证真相(三轴闭包)
+## 当前基线与验证真相(door-percent 重构进行中)
 
 | 项 | 值 |
 |---|---|
-| 合同 / 源码基线 tip | `cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7`(Lane 合并起点) |
-| ARTIFACT-SOURCE-COMMIT / FINAL_COMMIT(TD 源闭包) | `f23d6d4c57959071cd3886ea5503fbe903aee547` |
-| DELIVERY-COMMIT | 见 firmware 包 `FINAL-DEV-COMMIT.txt` / review-compact `meta/git/HEAD.txt`(不在活动文档硬编码未产生的 tip) |
-| Bitstream SHA-256 | `eb275921a3c25dcd9440c02677ea9b910e2bf5e57517bbad4ee063afa93e760a` |
-| SOURCE-CLOSURE-UNCHANGED | **SOURCE-CLOSURE-UNCHANGED=false** vs 旧 tip `0de9f939…` / 旧 bit `3143b87c…`;本轮以 `meta/td/td-source-closure-binding.json` 为准 |
-| td2026 | Release_2026.1_SP2 Build `6.2.2.200067`;RUN_ID `20260806T112210Z-3f2f5f2f` |
-| 历史旁路 firmware bit | `45f548ab…` 构建于 `bb515af`,**不是** tip / 当前闭包证据 |
+| 预览分支 | `preview/door-percent-positioning` |
+| 合同迁移 | 百分比定位 + 30 s WD + GET_MOTOR_STATUS(活动文档/协议模型已切换) |
+| 旧三轴 jog 闭包 tip / bitstream | 历史证据,**不得**当作新合同 tip pass |
 | Hardware / JTAG / 烧录 | **`not_run`**(未授权) |
 
-陈旧二轴/电磁铁“final closure”(`da7b05a` / `ce3157c5…` / `8f28660…`)及 Windows 叙述已归档,**不是**当前活动真相。
+新合同的完整 offline/TD/package 证据由本轮重构闭环产生后写入;在此之前不得把旧 jog 收据或 Hardware 叙述成 pass。
 
 ## 离线验证入口(Linux)
 
@@ -70,6 +71,7 @@ TD:仅用 `td2026`(Anlogic TD 2026.1 SP2 Linux)。勿把 TD 的 `LD_LIBRAR
 ## 合同与工具
 
 - 合同:`projects/prod2u-door-temp/project.json`、`requirements.zh-CN.md`、协议文档、`AGENTS.md`
+- 协议参考:`tools/prod2u_simple_protocol.py`、`tools/door_percent_planner_ref.py`
 - 源码审计包:`package_for_agent_analysis.py`
 - 固件包:`tools/build_firmware_package.py`(需绑定 `--td-root`)
 - IO / 硬件期望:[`docs/IO_EVIDENCE_MATRIX.zh-CN.md`](docs/IO_EVIDENCE_MATRIX.zh-CN.md)、[`docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md`](docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md)

+ 18 - 47
config/prod2u_p4_verification_targets_v1.json

@@ -14,11 +14,13 @@
       "tests.unit.test_phase3_formal_contract",
       "tests.unit.test_product_contract_coverage",
       "tests.unit.test_negative_tool_fixtures",
-      "tests.unit.test_startup_close_seek",
+      "tests.unit.test_door_percent_calibration_contract",
       "tests.unit.test_three_axis_door_contract",
+      "tests.unit.test_door_percent_planner_exhaustive",
       "tests.unit.test_motor_polarity_config",
       "tests.unit.test_alt_config_rtl_matrix",
       "tests.unit.test_release_set_provenance",
+      "tests.unit.test_activity_docs_truth",
       "tests.test_project_structure"
     ],
     "icarus": [
@@ -29,10 +31,8 @@
       "frame_tx_tb",
       "project_adapter_tb",
       "pwm_scheduler_tb",
-      "door_motor_engine_tb",
-      "door_motor_engine_stop_tb",
-      "door_action_dispatcher_tb",
-      "startup_close_seek_tb",
+      "door_percent_planner_tb",
+      "door_motion_controller_tb",
       "temperature_reader_tb",
       "frame_tx_uart_tx_tb",
       "temperature_reader_config_tb",
@@ -44,7 +44,6 @@
       "output_target_ram_tb",
       "host_watchdog_tb",
       "shared_500us_tick_tb",
-      "startup_motor_stop_tb",
       "prod2u_por_tb"
     ],
     "verilator": [
@@ -56,75 +55,47 @@
     "formal": [
       {
         "name": "frame_command_contract",
-        "tasks": [
-          "bmc"
-        ]
+        "tasks": ["bmc"]
       },
       {
         "name": "frame_tx_contract",
-        "tasks": [
-          "bmc"
-        ]
+        "tasks": ["bmc"]
       },
       {
         "name": "output_target_ram_contract",
-        "tasks": [
-          "prove"
-        ]
+        "tasks": ["prove"]
       },
       {
         "name": "simple_frame_contract",
-        "tasks": [
-          "bmc",
-          "cover"
-        ]
+        "tasks": ["bmc", "cover"]
       },
       {
         "name": "simple_motor_temperature_contract",
-        "tasks": [
-          "prove",
-          "cover"
-        ]
+        "tasks": ["bmc", "cover"]
       },
       {
         "name": "pwm_scheduler_contract",
-        "tasks": [
-          "prove"
-        ]
+        "tasks": ["prove"]
       },
       {
         "name": "host_watchdog_contract",
-        "tasks": [
-          "prove"
-        ]
+        "tasks": ["prove"]
       },
       {
-        "name": "startup_close_seek",
-        "tasks": [
-          "bmc",
-          "cover"
-        ]
+        "name": "door_axis_cal",
+        "tasks": ["bmc", "cover"]
       },
       {
         "name": "runtime_limit_hard_stop",
-        "tasks": [
-          "bmc",
-          "cover"
-        ]
+        "tasks": ["bmc", "cover"]
       },
       {
         "name": "alt_config_limit_normalize",
-        "tasks": [
-          "bmc",
-          "cover"
-        ]
+        "tasks": ["bmc", "cover"]
       },
       {
-        "name": "door_action_dispatcher_axis3",
-        "tasks": [
-          "bmc",
-          "cover"
-        ]
+        "name": "door_percent_planner",
+        "tasks": ["bmc", "cover"]
       }
     ]
   }

+ 3 - 3
config/source_closure.json

@@ -14,9 +14,9 @@
     "src/modules/pwm_scheduler.v",
     "src/modules/shared_500us_tick.v",
     "src/modules/host_watchdog.v",
-    "src/modules/startup_close_seek.v",
-    "src/modules/door_motor_engine.v",
-    "src/modules/door_action_dispatcher.v",
+    "src/modules/door_percent_planner.v",
+    "src/modules/door_axis_controller.v",
+    "src/modules/door_motion_controller.v",
     "src/modules/i2c_word_reader.v",
     "src/modules/temperature_reader.v",
     "src/modules/temperature_ram.v",

+ 26 - 22
docs/HARDWARE_BRINGUP_NOTES.zh-CN.md

@@ -1,10 +1,12 @@
-# Prod2U V1.2 硬件 Bring-up 笔记(三轴六限位)
+# Prod2U V1.2 硬件 Bring-up 笔记(三轴百分比定位)
 
-run_id: `3axis-20260805T171312Z`  
 本文件 **不是** 已执行硬件回执。物理 COM/JTAG 未授权;**Hardware validation = NOT RUN**。
 
 引脚权威见 [`IO_EVIDENCE_MATRIX.zh-CN.md`](IO_EVIDENCE_MATRIX.zh-CN.md)。  
-活动合同:`projects/prod2u-door-temp/`;无 solenoid / motor-compat。
+活动合同:`projects/prod2u-door-temp/` + [`prod2u-door-temp-protocol.zh-CN.md`](prod2u-door-temp-protocol.zh-CN.md);无 solenoid / 旧 jog。
+
+> **破坏性迁移**:勿再按 `00/01/02` jog、450 步、busy 忽略、WD 10s→FAN20、startup+500 backoff 验收。  
+> 新合同:门字节 `0..100` 闭合百分比;latest-wins;标定 seek-close→measure-open;WD **30s→FAN10**;`GET_MOTOR_STATUS 0x03`。
 
 ## 0. 安全与探点
 
@@ -19,34 +21,36 @@ run_id: `3axis-20260805T171312Z`
 | 步 | 项目 | 操作摘要 | 通过判据(期望) |
 |---:|------|----------|------------------|
 | 1 | 上电静态 | 上电,不发 UART | PTC≈0;FAN≈10% @~20 Hz;`motor_en_n`=1;STEP 无边沿 |
-| 2 | Startup 关门 | 观察 X/Y/Z STEP + LS | 见 §2.1;`startup_done` 前主机帧丢弃(无 TEMP 响应) |
-| 3 | UART 冒烟 | startup 后 GET_TEMPERATURE | `0x82` 27 字节载荷 + CRC |
-| 4 | FAN/PTC PWM | SET_ALL 单腔 0/50/100 | ~20 Hz;同腔两路 PTC 一致 |
-| 5 | 普通 jog | byte8/9/10 = Z/X/Y;`01`/`02` | 450 STEP 上升沿 @ 1000 step/s |
-| 6 | 运行期限位硬停 | jog 中拨对应方向限位 | 当前高脉冲结束后无新上升沿 |
-| 7 | `00` 不启动新 jog | busy 时或空闲发 `00` | busy 忽略;不停止/不覆盖当前动作 |
-| 8 | 看门狗 | 停发 SET_ALL ≥10 s | PTC→0,FAN→20 |
+| 2 | Startup 标定 | 观察 X/Y/Z STEP + 限位 | §2.1;可用 `GET_MOTOR_STATUS`;`GET_TEMPERATURE` 无响应 |
+| 3 | UART 冒烟 | `startup_complete` 后 GET_TEMPERATURE | `0x82` 27 字节 + CRC |
+| 4 | 马达状态 | GET_MOTOR_STATUS | `0x83` 31 字节;golden 请求 `A5 5A 03 00 5C 48` |
+| 5 | FAN/PTC PWM | SET_ALL 单腔 0/50/100 | ~20 Hz;同腔两路 PTC 一致 |
+| 6 | 端点定位 | 门字段 0 / 100 | 认 open/close limit;非仅靠步数 |
+| 7 | 中间百分比 | 门字段 1..99 | 开环靠近 mid_target;latest-wins 可打断 |
+| 8 | 运行期限位硬停 | 运动中拨目标限位 | 当前高脉冲立即截断;无新上升沿 |
+| 9 | 心跳百分比 | 重发当前期望 percent | 喂狗;同目标不无故重启 |
+| 10 | 看门狗 | 停发 SET_ALL ≥30 s | PTC→0,FAN→10 |
 
 ## 2. 期望行为摘要
 
-### 2.1 Startup(一次性)
+### 2.1 Startup 标定(一次性)
 
-- DIR=1(关);三轴可并发。
-- 每轴最多 **5000** STEP @ 1000 step/s,停于对应 **LS**(关方向)。
-- 未触限位:该轴 **500** STEP backoff(DIR=0,HS 门控),标记 missed;不重试、无故障帧。
-- 限位命中:完成当前 STEP 高半周后不再产生新上升沿。
-- 无旧 10×450 burst / 50 ms 间隔合同。
+- 每轴独立:seek-close(≤5000 gated STEP)→ measure-open(≤5000);成功停在全开并锁存 `travel_steps`。
+- **无** 500 步 backoff。失败轴 FAULT 锁到复位;其它轴可成功。
+- 标定期间:SET_ALL 可改 FAN/PTC,门百分比忽略不缓存;GET_MOTOR_STATUS 可见;GET_TEMPERATURE 无响应;watchdog 不计时。
+- 限位硬截断语义仍适用。
 
-### 2.2 普通 jog(startup_done 后)
+### 2.2 运行期百分比(startup_complete 后)
 
-- SET_ALL:`door_z`@8、`door_x`@9、`door_y`@10;`01` 开 / `02` 关 / `00` 不启动新 jog(busy 时不停止、不覆盖)。
-- 固定 **450** STEP @ 1000 step/s。
-- 运行期:开方向看 HS、关方向看 LS;每时钟硬停。
+- SET_ALL:`z`@8、`x`@9、`y`@10 = 闭合百分比 0..100。
+- `0`/`100` 端点认真实限位;`1..99` 开环 mid 目标。
+- 新百分比 latest-wins;心跳=重发真实期望百分比(勿再发三门 `00` 当“不动作”)。
+- 步频 1000 step/s;只计 gated STEP 上升沿。
 
 ### 2.3 UART
 
 - 25 MHz,115200 8N1,217 clk/bit;`A5 5A`;CRC-16/CCITT-FALSE。
-- SET_ALL 无应答;GET_TEMPERATURE → `0x82`。
+- SET_ALL 无应答;GET_TEMPERATURE → `0x82`;GET_MOTOR_STATUS → `0x83`。
 
 ## 3. 探点速查(活动 ADC)
 
@@ -61,5 +65,5 @@ run_id: `3axis-20260805T171312Z`
 
 ## 4. 状态
 
-- Linux / sim / formal / TD:见本轮 verification-matrix 与 TD receipt。
+- Linux / sim / formal / TD:以 door-percent 重构闭环收据为准(旧 jog tip 不复用)。
 - **Hardware validation: NOT RUN**

+ 32 - 27
docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md

@@ -1,10 +1,10 @@
-# Prod2U V1.2 硬件测试顺序与期望波形(三轴活动版)
+# Prod2U V1.2 硬件测试顺序与期望波形(door-percent 活动版)
 
-前提:比特流与 active ADC 绑定 ARTIFACT-SOURCE-COMMIT `f23d6d4c57959071cd3886ea5503fbe903aee547`;  
-Bitstream SHA-256 `eb275921a3c25dcd9440c02677ea9b910e2bf5e57517bbad4ee063afa93e760a`(td2026 Release_2026.1_SP2 Build `6.2.2.200067`;RUN `20260806T112210Z-3f2f5f2f`)。  
-DELIVERY-COMMIT 见 firmware 包 / `meta/git/HEAD.txt`。相对旧 tip `0de9f939…` / 旧 bit `3143b87c…`:**SOURCE-CLOSURE-UNCHANGED=false**。  
-历史旁路 bit `45f548ab…` @ `bb515af` **不是** tip。 Hardware **`NOT RUN`**。  
-本文件 **不是** 已执行硬件回执;物理 COM/JTAG 未授权前状态为 `not_run`。
+前提:door-percent 重构完成后,比特流须绑定**新合同 tip**(禁止复用旧 jog tip `f23d6d4…` / bit `eb275921…` 作为新合同 pass)。  
+Hardware **`NOT RUN`**。本文件 **不是** 已执行硬件回执;物理 COM/JTAG 未授权前状态为 `not_run`。
+
+> **破坏性迁移**:旧 `00/01/02` jog · 450 步 · WD 10s FAN20 · startup+500 backoff **已废弃**。  
+> 新:门 `0..100` 闭合百分比 · latest-wins · WD **30s FAN10** · seek-close→measure-open · `0x03/0x83`。
 
 旧二轴+电磁铁探点(CON68/CON34/CON138–141、solenoid)已归档:  
 [`historical/HARDWARE_TEST_ORDER_WAVEFORMS-2axis-solenoid-pre-3axis.zh-CN.md`](historical/HARDWARE_TEST_ORDER_WAVEFORMS-2axis-solenoid-pre-3axis.zh-CN.md)。
@@ -29,30 +29,33 @@ DELIVERY-COMMIT 见 firmware 包 / `meta/git/HEAD.txt`。相对旧 tip `0de9f939
 
 | 步 | 项目 | 操作摘要 | 通过判据(期望) |
 |---:|------|----------|------------------|
-| 1 | 上电静态 | 上电,不发 UART | PTC 球≈0;FAN 球对应默认 duty≈10%(~20 Hz);FPGA EN=1;STEP 无边沿 |
-| 2 | Startup 关门寻限位 | 观察 X/Y/Z STEP + 六限位 | 见 §2.1;`startup_done` 前主机帧丢弃 |
-| 3 | UART 冒烟 | startup 完成后发 GET_TEMPERATURE | 收到 `0x82` 27 字节温度载荷 + CRC |
-| 4 | FAN PWM | SET_ALL 单腔风扇 0/50/100 | §2.2 |
-| 5 | PTC PWM | SET_ALL 单腔 PTC 0/50/100 | §2.3;同腔两路物理 PTC 一致 |
-| 6 | 三轴 jog | SET_ALL Z/X/Y = 01 或 02 | §2.4;每轴最多 450 个 STEP 上升沿 @ 1000 step/s |
-| 7 | 运行期硬截断 | startup 后 jog 时拨动目标限位 | STEP 高脉冲立即截断;无新上升沿(非惰性) |
-| 8 | 看门狗 | 停发 SET_ALL ≥10 s | PTC→0,FAN→20;STEP 停;EN 仍永久使能 |
+| 1 | 上电静态 | 上电,不发 UART | PTC 球≈0;FAN≈10%(~20 Hz);FPGA EN=1;STEP 无边沿 |
+| 2 | Startup 标定 | 观察 X/Y/Z STEP + 六限位;可发 GET_MOTOR_STATUS | §2.1;GET_TEMP 无响应 |
+| 3 | UART 冒烟 | startup 完成后 GET_TEMPERATURE | `0x82` 27 字节 + CRC |
+| 4 | 马达状态 | GET_MOTOR_STATUS | `0x83` 31 字节;请求 golden `A5 5A 03 00 5C 48` |
+| 5 | FAN PWM | SET_ALL 单腔风扇 0/50/100 | §2.2 |
+| 6 | PTC PWM | SET_ALL 单腔 PTC 0/50/100 | §2.3;同腔两路一致 |
+| 7 | 端点 0/100 | SET_ALL 门字段 0 或 100 | §2.4;认真实限位 |
+| 8 | 中间百分比 | 门字段 50 等 | 开环靠近 mid_target;可 latest-wins |
+| 9 | 运行期硬截断 | 运动中拨目标限位 | STEP 高脉冲立即截断;无新上升沿 |
+| 10 | 看门狗 | 停发 SET_ALL ≥30 s | PTC→0,FAN→10;STEP 停;EN 仍永久使能 |
 
 ## 2. 期望波形
 
 时钟 25 MHz;时间按合同标称。
 
-### 2.1 Startup 关门寻限位
+### 2.1 Startup 标定(seek-close → measure-open)
 
-- DIR = 1(关);FPGA EN = 1(`permanent_high`)。
-- 每轴最多 **5000** 个 STEP 上升沿 @ 1000 step/s;未命中 LS 则 DIR=0 回退最多 **500**(HS 可提前停)。
-- 限位同步变高:该轴 **立即截断** 当前 STEP 高脉冲(`truncate_current_high_pulse_immediately_after_synchronized_limit`),不再产生新上升沿。
-- 限位上电已为高:该轴不运动。
-- X/Y/Z 可重叠,独立停止。
+- FPGA EN = 1(`permanent_high`)。
+- 每轴:向 close ≤**5000** gated STEP,再向 open 测量 ≤**5000**;成功则 `travel_steps` 有效并停在全开。
+- **无** 500 步 backoff。
+- 限位同步变高:该轴 **立即截断** 当前 STEP 高脉冲,不再产生新上升沿。
+- X/Y/Z 可重叠,独立停止/失败。
 
 ```text
-STEP  (axis seeking):  ‾|_|‾|_| … (≤5000 rises) …
-LIMIT (active-high):   ____________/‾‾‾‾‾‾  → truncate high immediately
+STEP  (seek close):   ‾|_|‾|_| … (≤5000 rises) …
+STEP  (measure open): ‾|_|‾|_| … (travel rises) …
+LIMIT (active-high):  ____________/‾‾‾‾‾‾  → truncate high immediately
 ```
 
 ### 2.2 FAN PWM(~20 Hz)
@@ -65,15 +68,17 @@ LIMIT (active-high):   ____________/‾‾‾‾‾‾  → truncate high immedi
 - 同 ~20 Hz 时基;球侧 **高有效**。
 - 同腔两路占空应一致。
 
-### 2.4 普通 jog(startup_done 后)
+### 2.4 运行期百分比(startup_complete 后)
 
-- `01` DIR=0 开门;`02` DIR=1 关门;`00` = 不启动新 jog(busy 时不停止、不覆盖当前动作)。
-- 非零命令:最多 **450** 个 STEP 上升沿 @ 1000 step/s。
+- 门字节 = 闭合百分比 0..100(不是 jog 枚举)。
+- `0`/`100`:向对应限位运行;正常完成只认真实限位。
+- `1..99`:开环目标 `clamp((travel*percent+50)//100, 1, travel-1)` @ 1000 step/s。
+- 新百分比 latest-wins;心跳=重发期望百分比。
 - 运行期目标限位有效:**硬截断**(非 inert)。
 
 ```text
 DIR   ____/‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
-STEP  ....|‾|_|‾|_| … ≤450 rising edges … |_
+STEP  ....|‾|_|‾|_| … gated rises to target … |_
 EN    1(FPGA permanent_high)
 ```
 
@@ -81,7 +86,7 @@ EN    1(FPGA permanent_high)
 
 - bit 宽 = 217 clk @25 MHz ≈ 8.68 µs。
 - 帧:`A5 5A | type | length | payload | CRCL | CRCH`。
-- GET_TEMPERATURE → `0x82`,payload 27;SET_ALL **无** 应答。
+- GET_TEMPERATURE → `0x82`,payload 27;GET_MOTOR_STATUS → `0x83`,payload 31;SET_ALL **无** 应答。
 
 ## 3. 探点速查(V1.2 活动)
 

+ 7 - 11
docs/TD_USAGE.zh-CN.md

@@ -2,23 +2,19 @@
 
 **活动权威环境是 Linux 容器**,命令入口为 `td2026`(Anlogic TD 2026.1 SP2)。最终验收收据必须以当前 Linux 运行产生;Windows GUI/批处理路径仅作可选参考,不是活动闭环权威。
 
-## 活动 TD / bitstream 身份(三轴)
+## 活动 TD / bitstream 身份(door-percent)
 
 | 项 | 状态 |
 |---|---|
-| ARTIFACT-SOURCE-COMMIT / FINAL_COMMIT / tip TD | `f23d6d4c57959071cd3886ea5503fbe903aee547` |
-| DELIVERY-COMMIT | 见 firmware 包 `FINAL-DEV-COMMIT.txt` / review-compact `meta/git/HEAD.txt` |
-| Bitstream SHA-256 | `eb275921a3c25dcd9440c02677ea9b910e2bf5e57517bbad4ee063afa93e760a` |
-| SOURCE-CLOSURE vs 旧 tip | **SOURCE-CLOSURE-UNCHANGED=false** vs `0de9f939…` / 旧 bit `3143b87c…` |
-| td2026 | Release_2026.1_SP2 Build `6.2.2.200067` |
-| TD RUN_ID | `20260806T112210Z-3f2f5f2f` |
-| 历史旁路 firmware bit | `45f548ab…` built @ `bb515af` — **不是** tip / 当前闭包证据 |
-| 合同基线 tip(Lane 起点) | `cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7` |
+| 活动合同 | 三轴 **百分比定位**(非旧 450 jog);标定 seek-close→measure-open;WD 30s FAN10;`0x03/0x83` |
+| 新 tip TD / bitstream | **待 door-percent 重构闭环后重跑绑定**(当前 not_run) |
+| 旧 jog tip / bit(历史) | `f23d6d4c…` / `eb275921…` — **不得**复用为新合同 tip pass |
+| td2026 | Release_2026.1_SP2 Build `6.2.2.200067`(工具版本) |
 | Hardware 烧录 | **`not_run`** |
 
-生产 RTL/约束/ADC 变更后必须在 **最终 clean tip** 上独占重跑 `td2026`。勿用更旧历史位流(含二轴时代 `ce3157c5…` / `8f28660…`,或 `45f548ab…` @ `bb515af`)冒充当前 tip 证据。
+生产 RTL/约束/ADC 变更后必须在 **最终 clean tip** 上独占重跑 `td2026`。勿用更旧历史位流(含 jog 时代 `eb275921…` / `f23d6d4…`,二轴时代 `ce3157c5…`,或 `45f548ab…` @ `bb515af`)冒充当前 tip 证据。
 
-活动合同:X/Y/Z、六限位、450/5000/500、EN `permanent_high`、硬截断 `truncate_current_high_pulse_immediately_after_synchronized_limit`。活动 IO **不是** solenoid / CON68 / CON34 / CON138–141;runtime limit **不是** inert。
+活动合同:X/Y/Z 百分比、六限位、标定 ≤5000/≤5000(无 500 backoff)、EN `permanent_high`、硬截断 `truncate_current_high_pulse_immediately_after_synchronized_limit`。活动 IO **不是** solenoid / CON68 / CON34 / CON138–141;runtime limit **不是** inert。
 
 ## 1. 工具链版本
 

+ 95 - 22
docs/prod2u-door-temp-protocol.zh-CN.md

@@ -1,15 +1,33 @@
 # Prod2U 门与温度协议(活动合同)
 
-**四腔热控 + 腔体 1 三风门**:payload 含 4 路风扇、4 路 chamber PTC(各复制到 2 路物理 PTC PWM)、腔体 1 的 Z(进风)+ X/Y(出风)步进门动作。温度 GET 仍返回 **27** 个值。
-
-权威源:`projects/prod2u-door-temp/project.json`、`projects/prod2u-door-temp/requirements.zh-CN.md`、本文件、`AGENTS.md`。
+**四腔热控 + 腔体 1 三风门百分比定位**:payload 含 4 路风扇、4 路 chamber PTC(各复制到 2 路物理 PTC PWM)、腔体 1 的 Z(进风)+ X/Y(出风)**闭合百分比**。温度 GET 仍返回 **27** 个值。马达可观测性:`GET_MOTOR_STATUS` / `MOTOR_STATUS_DATA`。
+
+权威源:`projects/prod2u-door-temp/project.json`、`projects/prod2u-door-temp/requirements.zh-CN.md`、本文件、`AGENTS.md`。参考模型:`tools/prod2u_simple_protocol.py`、`tools/door_percent_planner_ref.py`。
+
+> ## 破坏性协议迁移警告
+>
+> **旧合同(已废弃,勿再按此发帧)**
+> - 门字节 `00` = 不启动新 jog / 可当心跳;`01` = 打开最多 450 步;`02` = 关闭最多 450 步
+> - busy 期间新门命令忽略(无 latest-wins)
+> - 看门狗 10 s → PTC=0、FAN=20
+> - 上电:关门寻限 + 未命中则打开回退 500 步
+>
+> **新合同(当前唯一权威)**
+> - 门字节 `00` = 全开(0% 闭合)… `64` = 全关(100% 闭合);`01..63` = 1%..99% 闭合
+> - 合法 SET_ALL 原子提交;运动中新百分比 **latest-wins**(最多完成已开始的一步)
+> - 看门狗 **30 s** → PTC=0、**FAN=10**(仅 `startup_complete` 后计时/喂狗)
+> - 上电标定:每轴独立 **seek-close → measure-open**;无 500 步 backoff
+> - 新增 `0x03 GET_MOTOR_STATUS` / `0x83 MOTOR_STATUS_DATA`(31 字节 payload)
+> - 无 ACK / BUSY / ERROR / 命令队列
+>
+> 旧上位机若继续把三个门字段填 `00` 当心跳,会让三轴持续核对并运行到**全开限位**。新的心跳方式:周期性重发当前真实期望的三个百分比。
 
 ## UART
 
 - 25 MHz 系统时钟,115200 8N1,217 clocks/bit
 - 帧头 `A5 5A`,CRC-16/CCITT-FALSE(覆盖 type+length+payload,小端)
-- 支持:`0x01 SET_ALL`、`0x02 GET_TEMPERATURE`、`0x82 TEMPERATURE_DATA`
-- 无 ACK / BUSY / ERROR / 命令队列 / 抢占
+- 支持:`0x01 SET_ALL`、`0x02 GET_TEMPERATURE`、`0x03 GET_MOTOR_STATUS`、`0x82 TEMPERATURE_DATA`、`0x83 MOTOR_STATUS_DATA`
+- 无 ACK / BUSY / ERROR / 命令队列
 
 ## SET_ALL(11 字节)
 
@@ -17,19 +35,65 @@
 |--------|------|------|
 | 0..3 | FAN1..4 占空比 | 0..100 |
 | 4..7 | Chamber PTC1..4 占空比 | 0..100(各复制到 2 路物理 PTC) |
-| 8 | Z 门(进风步进) | 00/01/02 |
-| 9 | X 门(出风步进) | 00/01/02 |
-| 10 | Y 门(出风步进) | 00/01/02 |
+| 8 | Z 门闭合百分比 | 0..100 |
+| 9 | X 门闭合百分比 | 0..100 |
+| 10 | Y 门闭合百分比 | 0..100 |
+
+任何 FAN/PTC/门越界、长度错误或 CRC 错误:整帧拒绝(不改热控、不改马达目标、不喂狗)。旧 14 字节 SET_ALL 继续拒绝。
 
-### 门动作字节语义(三轴步进)
+### 门百分比语义
 
 | 值 | 含义 |
 |----|------|
-| 00 | 不启动新 jog(已在运动则忽略;不改变 EN) |
-| 01 | 逻辑打开(向 open_limit),最多 450 STEP 上升沿 |
-| 02 | 逻辑关闭(向 close_limit),最多 450 STEP 上升沿 |
+| 0 (`0x00`) | 全开;正常完成只认真实 open_limit |
+| 1..99 | 中间闭合百分比;开环步数估计,目标夹到 `1..travel-1` |
+| 100 (`0x64`) | 全关;正常完成只认真实 close_limit |
+| 101..255 | 非法 |
+
+内部坐标:`current_position=0` 为全开端,`=travel_steps` 为全关端。中间位置为开环估计,不能宣称为机械闭环绝对位置。
+
+`startup_complete` 后:合法 SET_ALL 原子提交 FAN/PTC + 三轴 requested percent,并喂 30 s watchdog(含相同百分比重复帧)。不同百分比 → latest-wins。
+
+## GET_TEMPERATURE / TEMPERATURE_DATA
+
+- 请求 `0x02`,payload 长度 0
+- 响应 `0x82`,27 字节温度,总帧长 33
+- GET 不喂狗
+- 标定期间(`startup_complete==0`):GET_TEMPERATURE 静默丢弃、无响应
+
+## GET_MOTOR_STATUS / MOTOR_STATUS_DATA
+
+- 请求 `0x03`,payload 长度 0;golden:`A5 5A 03 00 5C 48`
+- 响应 `0x83`,payload **31** 字节,总帧长 37
+- 标定期间允许查询;GET 不喂狗
+- 响应对原子快照编码,发送期间字段不撕裂
 
-busy 期间新的门命令全部忽略(无 latest-wins)。看门狗超时:停止 STEP,PTC=0、FAN=20;EN 仍永久有效。
+### byte 0:全局状态
+
+| bit | 含义 |
+|-----|------|
+| 0..2 | X/Y/Z calibrated mask(bit0=X) |
+| 3..5 | X/Y/Z fault mask |
+| 6 | startup_complete |
+| 7 | watchdog_tripped |
+
+### byte 1..30:轴状态 ×3(顺序 X、Y、Z;每轴 10 字节)
+
+| 轴内偏移 | 字段 |
+|---------|------|
+| 0 | state |
+| 1 | flags |
+| 2 | requested_percent |
+| 3..4 | current_position LE16 |
+| 5..6 | target_position LE16 |
+| 7..8 | travel_steps LE16 |
+| 9 | fault_code |
+
+**state**:`0 CAL_SEEK_CLOSE` · `1 CAL_MEASURE_OPEN` · `2 IDLE` · `3 MOVE_OPEN` · `4 MOVE_CLOSE` · `5 WAIT_REPLAN` · `6 FAULT`
+
+**flags**:bit0 open_limit · bit1 close_limit · bit2 calibrated · bit3 moving · bit4 endpoint_mode · bit5 target_valid · bit6 replan_pending · bit7 reserved=0
+
+**fault_code**:`0 NONE` · `1 BOTH_LIMITS_ACTIVE` · `2 CAL_CLOSE_TIMEOUT` · `3 CAL_OPEN_TIMEOUT` · `4 INVALID_ZERO_OR_TINY_TRAVEL` · `5 ENDPOINT_TIMEOUT`
 
 ## 编译期每轴极性 / 端点角色(唯一权威入口)
 
@@ -42,7 +106,7 @@ busy 期间新的门命令全部忽略(无 latest-wins)。看门狗超时:
 | `limits.close_limit_is_ls[i]` | true:LS=逻辑关闭端、HS=打开端;false:角色对调 |
 
 生成参数:`P4_DIR_CLOSE_LEVEL_MASK` / `P4_LIMIT_ACTIVE_HIGH_MASK` / `P4_CLOSE_LIMIT_IS_LS_MASK`(bit0=X)。  
-`limits.active_level` 为 **legacy summary / deprecated / non-authoritative**,不控制 RTL mask,也不强制与 `all(limit_active_high)` 一致;保留仅为旧配置兼容。
+`limits.active_level` 为 **legacy summary / deprecated / non-authoritative**,不控制 RTL mask。
 
 ## 物理映射(V1.2 BRD)
 
@@ -56,17 +120,26 @@ busy 期间新的门命令全部忽略(无 latest-wins)。看门狗超时:
 | LS3/HS3 | CON129.1/2 | K16/J15 |
 | LS4/HS4 | CON129.3/4 | H15/H16(仅 inventory) |
 
-默认生产配置下限位高有效、LS=关闭端。运行期与 startup 均对**规范化后的逻辑端点**硬停。  
-`stop_semantics`:`truncate_current_high_pulse_immediately_after_synchronized_limit`(同步限位后立即截断当前 STEP 高脉冲,不再产生新上升沿)。
+默认生产配置下限位高有效、LS=关闭端。运行期与标定均对**规范化后的逻辑端点**硬停。  
+`stop_semantics`:`truncate_current_high_pulse_immediately_after_synchronized_limit`(同步限位后立即截断当前 STEP 高脉冲)。普通命令 / watchdog / endpoint-guard 优雅停:**不**截断高脉冲,只禁止下一上升沿。
+
+## Startup 标定(上电一拍)
+
+1. 六路限位 2FF 同步后,X/Y/Z 独立并行:
+2. **CAL_SEEK_CLOSE**:向 close 最多 **5000** 个 gated STEP;已在 close_limit 则 0 步进入测量。
+3. **CAL_MEASURE_OPEN**:向 open 测量行程;成功则 `travel_steps` 有效、停在全开、`requested_percent=0`。
+4. 失败轴 FAULT 锁定至复位;其它轴可继续成功。无 500 步 backoff。
+5. 三轴均进入 IDLE(成功)或 FAULT 后,`startup_complete` 粘性置位。
+6. 标定期间:SET_ALL 可更新 FAN/PTC,门百分比忽略且不缓存;GET_MOTOR_STATUS 可见;GET_TEMPERATURE 无响应;watchdog 不计时。
 
-## Startup(上电一拍)
+步频 1000 step/s。中间目标参考:`mid_target = clamp((travel*percent+50)//100, 1, travel-1)`。无电磁铁、无旧 jog 双 profile。
 
-1. 六路限位 2FF 同步后:已在逻辑 close_limit 的轴不运动。
-2. 其余轴按逻辑关闭方向搜索,最多 **5000** 个 STEP 上升沿;命中 configured close endpoint 的轴立即停且不回退(`found_close` 锁存)。
-3. 仅对始终未命中 close_limit 的轴按逻辑打开方向回退最多 **500** 步(途中 open_limit 可提前停)。
-4. `startup_done` 粘性置位后才接受主机命令;运行期仍按逻辑方向选择限位硬截断(非惰性)。
+## Watchdog
 
-普通命令 jog = **450** 步 @ 1000 step/s。无电磁铁、无 motor-compat 双 profile。
+- 30 s(500 µs tick × 60000),`enable=startup_complete`
+- 仅合法 SET_ALL commit 喂狗;任何 GET / 非法帧不喂
+- 超时:PTC=0、FAN=10、禁止新 STEP 上升沿;保留 travel/current/requested;`watchdog_tripped=1`
+- 下一帧合法 SET_ALL 清除 tripped 并按该帧百分比重新核对运动
 
 ## Hardware validation
 

+ 44 - 15
projects/prod2u-door-temp/project.json

@@ -69,17 +69,30 @@
     "count": 3,
     "order": ["x", "y", "z"],
     "role": "door",
-    "fixed_steps": 450,
     "execution": "overlap",
-    "busy_wait_ms": 600,
     "step_rate_hz": 1000,
     "step_half_cycles": 12500,
     "dir_setup_cycles": 25000,
-    "command_values": [0, 1, 2],
-    "heartbeat_value": 0,
     "open_dir_value": 0,
     "close_dir_value": 1,
     "dir_close_level": [1, 1, 1],
+    "positioning": {
+      "mode": "percent_close",
+      "percent_min": 0,
+      "percent_max": 100,
+      "open_endpoint_percent": 0,
+      "close_endpoint_percent": 100,
+      "mid_percent_min": 1,
+      "mid_percent_max": 99,
+      "rounding": "half_up",
+      "mid_clamp": "1_to_travel_minus_1",
+      "latest_wins": true,
+      "idempotent_same_target": true,
+      "command_interrupt": "finish_current_high_pulse_then_replan",
+      "shared_percent_planner": true,
+      "planner_count": 1,
+      "endpoint_guard_extra_steps": 500
+    },
     "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},
       "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},
@@ -103,16 +116,18 @@
     "runtime_use": true,
     "startup": {
       "enabled": true,
-      "direction_value": 1,
-      "direction_meaning": "close",
-      "close_step_count": 5000,
-      "backoff_step_count": 500,
+      "mode": "seek_close_then_measure_open",
+      "max_steps": 5000,
+      "min_travel_steps": 2,
       "step_rate_hz": 1000,
       "axis_order": ["x", "y", "z"],
+      "final_position": "open",
       "limit_stop_during_move": true,
       "stop_semantics": "truncate_current_high_pulse_immediately_after_synchronized_limit",
       "additional_rising_edges_after_synchronized_limit": 0,
-      "runtime_limit_use": true
+      "runtime_limit_use": true,
+      "partial_axis_failure_allowed": true,
+      "fault_lock_until_reset": true
     },
     "channels": [
       {"name": "x_limit_ls", "ball": "A5", "connector": "CON12", "connector_pin": 1, "side": "low"},
@@ -167,7 +182,7 @@
     "temperature_ram": "optional",
     "dsp": 0,
     "shared_pwm_comparators": 1,
-    "shared_motor_executors": 1,
+    "shared_percent_planner": 1,
     "shared_i2c_readers": 1
   },
   "protocol": {
@@ -185,7 +200,9 @@
     "commands": {
       "set_all": 1,
       "get_temperature": 2,
-      "temperature_data": 130
+      "get_motor_status": 3,
+      "temperature_data": 130,
+      "motor_status_data": 131
     },
     "set_all": {
       "payload_length": 11,
@@ -198,12 +215,23 @@
       "legacy_payload_length_rejected": 14,
       "duty_min": 0,
       "duty_max": 100,
-      "door_values": [0, 1, 2],
+      "door_percent_min": 0,
+      "door_percent_max": 100,
+      "door_percent_rejected_example": 101,
       "response": "none"
     },
+    "get_motor_status": {
+      "payload_length": 0,
+      "response": "motor_status_data"
+    },
     "temperature_data": {
       "payload_length": 27,
       "frame_length": 33
+    },
+    "motor_status_data": {
+      "payload_length": 31,
+      "frame_length": 37,
+      "layout": "host-contract"
     }
   },
   "timeouts": {
@@ -211,10 +239,11 @@
     "host_get_response_ms": 5000
   },
   "watchdog": {
-    "timeout_seconds": 10,
+    "timeout_seconds": 30,
     "tick_us": 500,
     "tick_clks": 12500,
-    "timeout_ticks": 20000,
-    "target": {"ptc": 0, "fan": 20}
+    "timeout_ticks": 60000,
+    "enable_after_startup_complete": true,
+    "target": {"ptc": 0, "fan": 10}
   }
 }

+ 26 - 14
projects/prod2u-door-temp/requirements.zh-CN.md

@@ -1,5 +1,11 @@
 # Prod2U 门控与温度项目需求
 
+## 破坏性协议迁移警告
+
+**旧合同已废弃**:门字节 `00/01/02` jog(`00` 不启动/心跳、`01` 开 450、`02` 关 450);busy 忽略新门命令;watchdog 10 s → FAN 20;startup 关门寻限 + 500 步 backoff。
+
+**新合同**:门字节为闭合百分比 `0..100`(`0`=全开,`100`=全关);合法 SET_ALL latest-wins;标定 seek-close → measure-open;watchdog **30 s → FAN 10**;`GET_MOTOR_STATUS 0x03` / `MOTOR_STATUS_DATA 0x83`(31 字节)。无 ACK/队列。旧上位机继续发三门 `00` 当心跳会驱动到全开限位——必须改为重发真实期望百分比。
+
 ## 系统与协议
 
 项目使用 EF2L45BG256B、25 MHz 时钟和 115200 8N1 UART。帧格式:
@@ -8,15 +14,16 @@
 A5 5A type payload_length payload crc16_low crc16_high
 ```
 
-CRC 为 CRC-16/CCITT-FALSE。正式类型只有 `0x01`、`0x02` 和 `0x82`。
+CRC 为 CRC-16/CCITT-FALSE。正式类型:`0x01 SET_ALL`、`0x02 GET_TEMPERATURE`、`0x03 GET_MOTOR_STATUS`、`0x82 TEMPERATURE_DATA`、`0x83 MOTOR_STATUS_DATA`。
 
-## 产品范围:四腔热控 + 腔体 1 三轴风门
+## 产品范围:四腔热控 + 腔体 1 三轴风门百分比定位
 
 - 4 路风扇 duty(0..100),各对应一腔。
 - 4 路 chamber PTC duty,各复制到 2 路物理 PTC PWM(8 路输出严格相等)。
-- 腔体 1:三轴步进风门 X/Y/Z(各 450 步 jog @ 1000 step/s,可并行)。
+- 腔体 1:三轴步进风门 X/Y/Z,按闭合百分比开环定位(可并行;latest-wins)。
 - 温度:27 值 GET/响应不变。
-- 无电磁铁进风门;字节 8 为 Z 轴步进命令。
+- 马达状态:31 字节 `MOTOR_STATUS_DATA` 可观测标定/运动/故障。
+- 无电磁铁进风门;字节 8 为 Z 轴闭合百分比。
 
 ## SET_ALL(11 字节)
 
@@ -24,16 +31,17 @@ CRC 为 CRC-16/CCITT-FALSE。正式类型只有 `0x01`、`0x02` 和 `0x82`。
 | ---: | --- |
 | 0–3 | 腔体 1–4 风扇 |
 | 4–7 | 腔体 1–4 PTC |
-| 8 | 风门 Z 00/01/02 |
-| 9 | 风门 X 00/01/02 |
-| 10 | 风门 Y 00/01/02 |
+| 8 | 风门 Z 闭合百分比 0..100 |
+| 9 | 风门 X 闭合百分比 0..100 |
+| 10 | 风门 Y 闭合百分比 0..100 |
 
-旧 14 字节格式拒绝。SET_ALL 无回复。
+旧 14 字节格式拒绝。SET_ALL 无回复。任一字段越界则整帧拒绝。
 
 ## 风门与马达
 
-- 三轴编码均为 `00/01/02`:`00` = 不启动新 jog(轴已 busy 时忽略该字节,不停止、不覆盖当前动作);`01` 逻辑打开(向 open_limit);`02` 逻辑关闭(向 close_limit)。
-- 普通 jog:450 步、1000 step/s,X/Y/Z 可并行。
+- 三轴编码均为闭合百分比:`0`=全开(认 open_limit),`100`=全关(认 close_limit),`1..99`=中间开环目标。
+- 中间目标:`clamp((travel*percent+50)//100, 1, travel-1)`;步频 1000 step/s;只计最终 gated STEP 上升沿。
+- 运动中新百分比 latest-wins;最多完成已开始的一步;无命令队列。
 - 电机 EN:CON120.2 → C11,板级 NPN 反相;FPGA 恒 1(`permanent_high`),座端 EN 永久有效。
 - 步进/方向球位:X CON104.2/3 → C12/B12;Y CON105.2/3 → L12/J11;Z CON106.2/3 → L14/K14。
 - **编译期唯一权威配置**(下标 X/Y/Z):`motors.dir_close_level`、`limits.limit_active_high`、`limits.close_limit_is_ls`。默认全 1/true。经正式 `generate_project` 生成 `P4_*_MASK`;`limits.active_level` 为 legacy/deprecated/non-authoritative,不控制 mask。
@@ -48,10 +56,14 @@ CRC 为 CRC-16/CCITT-FALSE。正式类型只有 `0x01`、`0x02` 和 `0x82`。
 | Y | CON12.3 C8 | CON12.4 A8 |
 | Z | CON129.1 K16 | CON129.2 J15 |
 
-- **Startup**:PTC=0、FAN=10;三轴逻辑关闭寻限;每轴最多 5000 步 @ 1000 step/s;曾命中 close_limit 则锁存且不回退;始终未命中则逻辑打开回退最多 500 步;`startup_done` 粘滞。
-- **运行期**:按逻辑运动方向选择对应逻辑限位;限位有效时该轴硬停(同步限位后立即截断当前 STEP 高脉冲,`stop_semantics=truncate_current_high_pulse_immediately_after_synchronized_limit`);busy 期间忽略新 start。
-- Startup 完成前:SET_ALL / GET_TEMPERATURE 丢弃,看门狗不喂,帧解析器保持 flush。
+- **Startup 标定**:PTC=0、FAN=10;每轴独立 seek-close(≤5000)再 measure-open(≤5000);成功锁存 `travel_steps` 并停在全开;失败 FAULT 锁到复位;**无** 500 步 backoff;`startup_complete` 粘滞。
+- **运行期**:按逻辑运动方向选择对应逻辑限位;限位有效时该轴硬停(同步限位后立即截断当前 STEP 高脉冲);命令/watchdog/guard 优雅停不截断高脉冲。
+- 标定完成前:SET_ALL 可更新 FAN/PTC,门百分比忽略不缓存;GET_MOTOR_STATUS 允许;GET_TEMPERATURE 丢弃;看门狗不启用。
 
 ## 输出与看门狗
 
-PTC/FAN 球位见 `project.json`。启动 PTC=0、FAN=10。看门狗 10 s → PTC=0、FAN=20。
+PTC/FAN 球位见 `project.json`。启动 PTC=0、FAN=10。看门狗 **30 s** → PTC=0、FAN=10(仅 `startup_complete` 后由合法 SET_ALL 喂狗)。
+
+## Hardware
+
+硬件验证:**NOT RUN**(未授权 COM/JTAG/烧录)。

src/modules/door_action_dispatcher.v → reference/historical/legacy-old-contract/door_action_dispatcher.v


src/modules/door_motor_engine.v → reference/historical/legacy-old-contract/door_motor_engine.v


src/modules/startup_close_seek.v → reference/historical/legacy-old-contract/startup_close_seek.v


tests/formal/door_action_dispatcher_axis3.sby → reference/historical/legacy-old-contract/tests/door_action_dispatcher_axis3.sby


tests/formal/door_action_dispatcher_axis3_formal.v → reference/historical/legacy-old-contract/tests/door_action_dispatcher_axis3_formal.v


tests/sim/door_action_dispatcher_tb.v → reference/historical/legacy-old-contract/tests/door_action_dispatcher_tb.v


tests/sim/door_motor_engine_stop_tb.v → reference/historical/legacy-old-contract/tests/door_motor_engine_stop_tb.v


tests/sim/door_motor_engine_tb.v → reference/historical/legacy-old-contract/tests/door_motor_engine_tb.v


tests/formal/startup_close_seek.sby → reference/historical/legacy-old-contract/tests/startup_close_seek.sby


tests/formal/startup_close_seek_formal.v → reference/historical/legacy-old-contract/tests/startup_close_seek_formal.v


tests/sim/startup_close_seek_tb.v → reference/historical/legacy-old-contract/tests/startup_close_seek_tb.v


tests/sim/startup_motor_stop_tb.v → reference/historical/legacy-old-contract/tests/startup_motor_stop_tb.v


+ 168 - 45
schemas/project.schema.json

@@ -268,17 +268,14 @@
                                                        "count",
                                                        "order",
                                                        "role",
-                                                       "fixed_steps",
                                                        "execution",
-                                                       "busy_wait_ms",
                                                        "step_rate_hz",
                                                        "step_half_cycles",
                                                        "dir_setup_cycles",
-                                                       "command_values",
-                                                       "heartbeat_value",
                                                        "open_dir_value",
                                                        "close_dir_value",
                                                        "dir_close_level",
+                                                       "positioning",
                                                        "mapping",
                                                        "enable_n"
                                                    ],
@@ -292,16 +289,9 @@
                                                          "role":  {
                                                                       "type":  "string"
                                                                   },
-                                                         "fixed_steps":  {
-                                                                             "type":  "integer"
-                                                                         },
                                                          "execution":  {
                                                                            "type":  "string"
                                                                        },
-                                                         "busy_wait_ms":  {
-                                                                              "type":  "integer",
-                                                                              "minimum":  600
-                                                                          },
                                                          "step_rate_hz":  {
                                                                               "type":  "integer"
                                                                           },
@@ -311,12 +301,6 @@
                                                          "dir_setup_cycles":  {
                                                                                   "type":  "integer"
                                                                               },
-                                                         "command_values":  {
-                                                                                "type":  "array"
-                                                                            },
-                                                         "heartbeat_value":  {
-                                                                                 "type":  "integer"
-                                                                             },
                                                          "open_dir_value":  {
                                                                                 "type":  "integer"
                                                                             },
@@ -333,6 +317,78 @@
                                                                                            },
                                                                                  "description":  "AUTHORITATIVE per-axis physical DIR level for logical close (1 or 0); index0=X,1=Y,2=Z (bit0=X). Must be integer 0/1, not boolean."
                                                                              },
+                                                         "positioning":  {
+                                                                             "type":  "object",
+                                                                             "required":  [
+                                                                                              "mode",
+                                                                                              "percent_min",
+                                                                                              "percent_max",
+                                                                                              "open_endpoint_percent",
+                                                                                              "close_endpoint_percent",
+                                                                                              "mid_percent_min",
+                                                                                              "mid_percent_max",
+                                                                                              "rounding",
+                                                                                              "mid_clamp",
+                                                                                              "latest_wins",
+                                                                                              "idempotent_same_target",
+                                                                                              "command_interrupt",
+                                                                                              "shared_percent_planner",
+                                                                                              "planner_count",
+                                                                                              "endpoint_guard_extra_steps"
+                                                                                          ],
+                                                                             "properties":  {
+                                                                                                "mode":  {
+                                                                                                             "type":  "string",
+                                                                                                             "enum":  ["percent_close"]
+                                                                                                         },
+                                                                                                "percent_min":  {
+                                                                                                                    "type":  "integer"
+                                                                                                                },
+                                                                                                "percent_max":  {
+                                                                                                                    "type":  "integer"
+                                                                                                                },
+                                                                                                "open_endpoint_percent":  {
+                                                                                                                              "type":  "integer"
+                                                                                                                          },
+                                                                                                "close_endpoint_percent":  {
+                                                                                                                               "type":  "integer"
+                                                                                                                           },
+                                                                                                "mid_percent_min":  {
+                                                                                                                        "type":  "integer"
+                                                                                                                    },
+                                                                                                "mid_percent_max":  {
+                                                                                                                        "type":  "integer"
+                                                                                                                    },
+                                                                                                "rounding":  {
+                                                                                                                 "type":  "string",
+                                                                                                                 "enum":  ["half_up"]
+                                                                                                             },
+                                                                                                "mid_clamp":  {
+                                                                                                                  "type":  "string",
+                                                                                                                  "enum":  ["1_to_travel_minus_1"]
+                                                                                                              },
+                                                                                                "latest_wins":  {
+                                                                                                                    "type":  "boolean"
+                                                                                                                },
+                                                                                                "idempotent_same_target":  {
+                                                                                                                               "type":  "boolean"
+                                                                                                                           },
+                                                                                                "command_interrupt":  {
+                                                                                                                          "type":  "string",
+                                                                                                                          "enum":  ["finish_current_high_pulse_then_replan"]
+                                                                                                                      },
+                                                                                                "shared_percent_planner":  {
+                                                                                                                               "type":  "boolean"
+                                                                                                                           },
+                                                                                                "planner_count":  {
+                                                                                                                      "type":  "integer"
+                                                                                                                  },
+                                                                                                "endpoint_guard_extra_steps":  {
+                                                                                                                                   "type":  "integer"
+                                                                                                                               }
+                                                                                            },
+                                                                             "additionalProperties":  false
+                                                                         },
                                                          "mapping":  {
                                                                          "type":  "object",
                                                                          "required":  [
@@ -438,33 +494,33 @@
                                                                          "type":  "object",
                                                                          "required":  [
                                                                                           "enabled",
-                                                                                          "direction_value",
-                                                                                          "direction_meaning",
-                                                                                          "close_step_count",
-                                                                                          "backoff_step_count",
+                                                                                          "mode",
+                                                                                          "max_steps",
+                                                                                          "min_travel_steps",
                                                                                           "step_rate_hz",
                                                                                           "axis_order",
+                                                                                          "final_position",
                                                                                           "limit_stop_during_move",
                                                                                           "stop_semantics",
                                                                                           "additional_rising_edges_after_synchronized_limit",
-                                                                                          "runtime_limit_use"
+                                                                                          "runtime_limit_use",
+                                                                                          "partial_axis_failure_allowed",
+                                                                                          "fault_lock_until_reset"
                                                                                       ],
                                                                          "properties":  {
                                                                                             "enabled":  {
                                                                                                             "type":  "boolean"
                                                                                                         },
-                                                                                            "direction_value":  {
-                                                                                                                  "type":  "integer"
-                                                                                                              },
-                                                                                            "direction_meaning":  {
-                                                                                                                    "type":  "string"
-                                                                                                                },
-                                                                                            "close_step_count":  {
-                                                                                                                   "type":  "integer"
-                                                                                                               },
-                                                                                            "backoff_step_count":  {
-                                                                                                                   "type":  "integer"
-                                                                                                               },
+                                                                                            "mode":  {
+                                                                                                         "type":  "string",
+                                                                                                         "enum":  ["seek_close_then_measure_open"]
+                                                                                                     },
+                                                                                            "max_steps":  {
+                                                                                                              "type":  "integer"
+                                                                                                          },
+                                                                                            "min_travel_steps":  {
+                                                                                                                     "type":  "integer"
+                                                                                                                 },
                                                                                             "step_rate_hz":  {
                                                                                                                  "type":  "integer"
                                                                                                              },
@@ -474,6 +530,10 @@
                                                                                                                           "type":  "string"
                                                                                                                       }
                                                                                                          },
+                                                                                            "final_position":  {
+                                                                                                                   "type":  "string",
+                                                                                                                   "enum":  ["open"]
+                                                                                                               },
                                                                                             "limit_stop_during_move":  {
                                                                                                                            "type":  "boolean"
                                                                                                                        },
@@ -489,7 +549,13 @@
                                                                                                                                                 },
                                                                                             "runtime_limit_use":  {
                                                                                                                     "type":  "boolean"
-                                                                                                                }
+                                                                                                                },
+                                                                                            "partial_axis_failure_allowed":  {
+                                                                                                                                 "type":  "boolean"
+                                                                                                                             },
+                                                                                            "fault_lock_until_reset":  {
+                                                                                                                           "type":  "boolean"
+                                                                                                                       }
                                                                                         },
                                                                          "additionalProperties":  false
                                                                      },
@@ -669,7 +735,7 @@
                                                           "temperature_ram",
                                                           "dsp",
                                                           "shared_pwm_comparators",
-                                                          "shared_motor_executors",
+                                                          "shared_percent_planner",
                                                           "shared_i2c_readers"
                                                       ],
                                          "properties":  {
@@ -691,7 +757,7 @@
                                                             "shared_pwm_comparators":  {
                                                                                            "type":  "integer"
                                                                                        },
-                                                            "shared_motor_executors":  {
+                                                            "shared_percent_planner":  {
                                                                                            "type":  "integer"
                                                                                        },
                                                             "shared_i2c_readers":  {
@@ -707,7 +773,9 @@
                                                          "crc",
                                                          "commands",
                                                          "set_all",
-                                                         "temperature_data"
+                                                         "get_motor_status",
+                                                         "temperature_data",
+                                                         "motor_status_data"
                                                      ],
                                         "properties":  {
                                                            "header_hex":  {
@@ -758,7 +826,9 @@
                                                                             "required":  [
                                                                                              "set_all",
                                                                                              "get_temperature",
-                                                                                             "temperature_data"
+                                                                                             "get_motor_status",
+                                                                                             "temperature_data",
+                                                                                             "motor_status_data"
                                                                                          ],
                                                                             "properties":  {
                                                                                                "set_all":  {
@@ -767,9 +837,15 @@
                                                                                                "get_temperature":  {
                                                                                                                        "type":  "integer"
                                                                                                                    },
+                                                                                               "get_motor_status":  {
+                                                                                                                        "type":  "integer"
+                                                                                                                    },
                                                                                                "temperature_data":  {
                                                                                                                         "type":  "integer"
-                                                                                                                    }
+                                                                                                                    },
+                                                                                               "motor_status_data":  {
+                                                                                                                         "type":  "integer"
+                                                                                                                     }
                                                                                            },
                                                                             "additionalProperties":  false
                                                                         },
@@ -786,7 +862,8 @@
                                                                                             "legacy_payload_length_rejected",
                                                                                             "duty_min",
                                                                                             "duty_max",
-                                                                                            "door_values",
+                                                                                            "door_percent_min",
+                                                                                            "door_percent_max",
                                                                                             "response"
                                                                                         ],
                                                                            "properties":  {
@@ -820,15 +897,37 @@
                                                                                               "duty_max":  {
                                                                                                                "type":  "integer"
                                                                                                            },
-                                                                                              "door_values":  {
-                                                                                                                  "type":  "array"
-                                                                                                              },
+                                                                                              "door_percent_min":  {
+                                                                                                                       "type":  "integer"
+                                                                                                                   },
+                                                                                              "door_percent_max":  {
+                                                                                                                       "type":  "integer"
+                                                                                                                   },
+                                                                                              "door_percent_rejected_example":  {
+                                                                                                                                    "type":  "integer"
+                                                                                                                                },
                                                                                               "response":  {
                                                                                                                "type":  "string"
                                                                                                            }
                                                                                           },
                                                                            "additionalProperties":  false
                                                                        },
+                                                           "get_motor_status":  {
+                                                                                    "type":  "object",
+                                                                                    "required":  [
+                                                                                                     "payload_length",
+                                                                                                     "response"
+                                                                                                 ],
+                                                                                    "properties":  {
+                                                                                                       "payload_length":  {
+                                                                                                                              "type":  "integer"
+                                                                                                                          },
+                                                                                                       "response":  {
+                                                                                                                        "type":  "string"
+                                                                                                                    }
+                                                                                                   },
+                                                                                    "additionalProperties":  false
+                                                                                },
                                                            "temperature_data":  {
                                                                                     "type":  "object",
                                                                                     "required":  [
@@ -844,7 +943,27 @@
                                                                                                                         }
                                                                                                    },
                                                                                     "additionalProperties":  false
-                                                                                }
+                                                                                },
+                                                           "motor_status_data":  {
+                                                                                     "type":  "object",
+                                                                                     "required":  [
+                                                                                                      "payload_length",
+                                                                                                      "frame_length",
+                                                                                                      "layout"
+                                                                                                  ],
+                                                                                     "properties":  {
+                                                                                                        "payload_length":  {
+                                                                                                                               "type":  "integer"
+                                                                                                                           },
+                                                                                                        "frame_length":  {
+                                                                                                                             "type":  "integer"
+                                                                                                                         },
+                                                                                                        "layout":  {
+                                                                                                                       "type":  "string"
+                                                                                                                   }
+                                                                                                    },
+                                                                                     "additionalProperties":  false
+                                                                                 }
                                                        },
                                         "additionalProperties":  false
                                     },
@@ -871,6 +990,7 @@
                                                          "tick_us",
                                                          "tick_clks",
                                                          "timeout_ticks",
+                                                         "enable_after_startup_complete",
                                                          "target"
                                                      ],
                                         "properties":  {
@@ -886,6 +1006,9 @@
                                                            "timeout_ticks":  {
                                                                                  "type":  "integer"
                                                                              },
+                                                           "enable_after_startup_complete":  {
+                                                                                                 "type":  "boolean"
+                                                                                             },
                                                            "target":  {
                                                                           "type":  "object",
                                                                           "required":  [

+ 6 - 4
src/common/frame_tx.v

@@ -1,6 +1,9 @@
 `timescale 1ns/1ps
 
-module frame_tx (
+module frame_tx #(
+    // Width of payload byte index; 5 bits covers 0..31 (length 31 / temp 27).
+    parameter integer PAYLOAD_IDX_BITS = 5
+) (
     input  wire       clk,
     input  wire       rst_n,
     input  wire       start,
@@ -25,7 +28,6 @@ module frame_tx (
     localparam [3:0] ST_PAYLOAD_CRC_WAIT = 4'd8;
     localparam [3:0] ST_CRC_LOW = 4'd9;
     localparam [3:0] ST_CRC_HIGH = 4'd10;
-    localparam integer PAYLOAD_IDX_BITS = 5;
 
     reg [3:0] state;
     reg [7:0] type_reg;
@@ -45,7 +47,7 @@ module frame_tx (
         .busy(crc_busy), .data_done(crc_data_done), .crc(crc_value)
     );
 
-    assign payload_addr = payload_index;
+    assign payload_addr = {{(8-PAYLOAD_IDX_BITS){1'b0}}, payload_index};
 
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
@@ -66,7 +68,7 @@ module frame_tx (
                 if (start) begin
                     type_reg <= frame_type;
                     length_reg <= payload_length;
-                    payload_index <= 8'd0;
+                    payload_index <= {PAYLOAD_IDX_BITS{1'b0}};
                     busy <= 1'b1;
                     crc_start_reg <= 1'b1;
                     state <= ST_A5;

+ 13 - 3
src/generated/golden-vectors.json

@@ -1,7 +1,17 @@
 {
   "all_invalid_temperature": "A55A821BFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA745",
+  "get_motor_status": "A55A03005C48",
   "get_temperature": "A55A02006D7B",
-  "set_all_all_zero": "A55A010B00000000000000000000005873",
-  "set_all_legacy_14_rejected": "0E",
-  "set_all_mixed": "A55A010B0A141E280019326401020087D5"
+  "motor_status_data_example": "A55A831F4702250000000000E8030002250000000000E8030002250000000000E803005226",
+  "notes": {
+    "get_motor_status": "Exact request frame A55A03005C48.",
+    "set_all_all_zero_full_open": "Legal SET_ALL: FAN/PTC 0 and doors 0/0/0 = full open; not a jog heartbeat no-op.",
+    "set_all_door_0x65_rejected": "Door percent 0x65 (101) is out of 0..100 and must be rejected."
+  },
+  "set_all_all_zero_full_open": "A55A010B00000000000000000000005873",
+  "set_all_door_0x65_rejected": "65",
+  "set_all_doors_0_percent": "A55A010B0A141E2800193264000000D584",
+  "set_all_doors_100_percent": "A55A010B0A141E2800193264646464B228",
+  "set_all_doors_50_percent": "A55A010B0A141E2800193264323232F65A",
+  "set_all_legacy_14_rejected": "0E"
 }

+ 113 - 26
src/generated/host-contract.json

@@ -1,17 +1,83 @@
 {
   "axis_count": 3,
   "commands": {
+    "get_motor_status": {
+      "payload_length": 0,
+      "response": "MOTOR_STATUS_DATA",
+      "type": "0x03"
+    },
     "get_temperature": {
       "payload_length": 0,
       "response": "TEMPERATURE_DATA",
       "type": "0x02"
     },
+    "motor_status_data": {
+      "frame_length": 37,
+      "layout": {
+        "axis_fields": [
+          "state",
+          "flags",
+          "requested_percent",
+          "current_position_le16",
+          "target_position_le16",
+          "travel_steps_le16",
+          "fault_code"
+        ],
+        "axis_order": [
+          "x",
+          "y",
+          "z"
+        ],
+        "byte0_global": {
+          "bit0_2": "calibrated_mask_xyz",
+          "bit3_5": "fault_mask_xyz",
+          "bit6": "startup_complete",
+          "bit7": "watchdog_tripped"
+        },
+        "fault_codes": {
+          "BOTH_LIMITS_ACTIVE": 1,
+          "CAL_CLOSE_TIMEOUT": 2,
+          "CAL_OPEN_TIMEOUT": 3,
+          "ENDPOINT_TIMEOUT": 5,
+          "INVALID_ZERO_OR_TINY_TRAVEL": 4,
+          "NONE": 0
+        },
+        "flags": {
+          "calibrated": 2,
+          "close_limit": 1,
+          "endpoint_mode": 4,
+          "moving": 3,
+          "open_limit": 0,
+          "replan_pending": 6,
+          "reserved": 7,
+          "target_valid": 5
+        },
+        "per_axis_bytes": 10,
+        "states": {
+          "CAL_MEASURE_OPEN": 1,
+          "CAL_SEEK_CLOSE": 0,
+          "FAULT": 6,
+          "IDLE": 2,
+          "MOVE_CLOSE": 4,
+          "MOVE_OPEN": 3,
+          "WAIT_REPLAN": 5
+        }
+      },
+      "payload_length": 31,
+      "type": "0x83"
+    },
     "set_all": {
-      "door_values": [
+      "door_percent_range": [
         0,
-        1,
-        2
+        100
       ],
+      "door_percent_semantics": {
+        "0": "full_open_endpoint",
+        "0x65": "rejected_out_of_range",
+        "100": "full_close_endpoint",
+        "1_to_99": "mid_percent_close",
+        "all_zero_frame": "fan_ptc_zero_and_all_doors_full_open_not_heartbeat"
+      },
       "duty_range": [
         0,
         100
@@ -25,9 +91,9 @@
         "ptc_chamber_2",
         "ptc_chamber_3",
         "ptc_chamber_4",
-        "door_z",
-        "door_x",
-        "door_y"
+        "door_z_percent",
+        "door_x_percent",
+        "door_y_percent"
       ],
       "payload_length": 11,
       "response": "none",
@@ -106,25 +172,21 @@
         "y",
         "z"
       ],
-      "backoff_step_count": 500,
-      "close_step_count": 5000,
-      "direction_meaning": "close",
-      "direction_value": 1,
       "enabled": true,
+      "fault_lock_until_reset": true,
+      "final_position": "open",
       "limit_stop_during_move": true,
+      "max_steps": 5000,
+      "min_travel_steps": 2,
+      "mode": "seek_close_then_measure_open",
+      "partial_axis_failure_allowed": true,
       "runtime_limit_use": true,
       "step_rate_hz": 1000,
       "stop_semantics": "truncate_current_high_pulse_immediately_after_synchronized_limit"
     }
   },
   "motors": {
-    "busy_wait_ms": 600,
     "close_dir_value": 1,
-    "command_values": [
-      0,
-      1,
-      2
-    ],
     "count": 3,
     "dir_close_level": [
       1,
@@ -141,8 +203,6 @@
       "policy": "permanent_high"
     },
     "execution": "overlap",
-    "fixed_steps": 450,
-    "heartbeat_value": 0,
     "mapping": {
       "x": {
         "axis": "x",
@@ -181,6 +241,23 @@
       "y",
       "z"
     ],
+    "positioning": {
+      "close_endpoint_percent": 100,
+      "command_interrupt": "finish_current_high_pulse_then_replan",
+      "endpoint_guard_extra_steps": 500,
+      "idempotent_same_target": true,
+      "latest_wins": true,
+      "mid_clamp": "1_to_travel_minus_1",
+      "mid_percent_max": 99,
+      "mid_percent_min": 1,
+      "mode": "percent_close",
+      "open_endpoint_percent": 0,
+      "percent_max": 100,
+      "percent_min": 0,
+      "planner_count": 1,
+      "rounding": "half_up",
+      "shared_percent_planner": true
+    },
     "role": "door",
     "step_half_cycles": 12500,
     "step_rate_hz": 1000
@@ -365,7 +442,9 @@
   "project_id": "prod2u-door-temp",
   "protocol": {
     "commands": {
+      "get_motor_status": 3,
       "get_temperature": 2,
+      "motor_status_data": 131,
       "set_all": 1,
       "temperature_data": 130
     },
@@ -379,15 +458,22 @@
       "wire_order": "little",
       "xor_output": 0
     },
+    "get_motor_status": {
+      "payload_length": 0,
+      "response": "motor_status_data"
+    },
     "header_hex": "A55A",
+    "motor_status_data": {
+      "frame_length": 37,
+      "layout": "host-contract",
+      "payload_length": 31
+    },
     "set_all": {
       "chamber_ptc_count": 4,
       "chamber_ptc_offset": 4,
-      "door_values": [
-        0,
-        1,
-        2
-      ],
+      "door_percent_max": 100,
+      "door_percent_min": 0,
+      "door_percent_rejected_example": 101,
       "duty_max": 100,
       "duty_min": 0,
       "exhaust_x_offset": 9,
@@ -448,13 +534,14 @@
     "tx_ball": "M10"
   },
   "watchdog": {
+    "enable_after_startup_complete": true,
     "target": {
-      "fan": 20,
+      "fan": 10,
       "ptc": 0
     },
     "tick_clks": 12500,
     "tick_us": 500,
-    "timeout_seconds": 10,
-    "timeout_ticks": 20000
+    "timeout_seconds": 30,
+    "timeout_ticks": 60000
   }
 }

+ 36 - 7
src/generated/prod2u_door_temp_params.vh

@@ -17,6 +17,13 @@
 `define P4_PWM_PHASE_COUNT 100
 `define P4_PWM_FREQUENCY_HZ 20
 `define P4_PWM_SLOT_CLKS 1042
+`define P4_CMD_SET_ALL 8'h01
+`define P4_CMD_GET_TEMPERATURE 8'h02
+`define P4_CMD_GET_MOTOR_STATUS 8'h03
+`define P4_CMD_TEMPERATURE_DATA 8'h82
+`define P4_CMD_MOTOR_STATUS_DATA 8'h83
+`define P4_RSP_TEMPERATURE 8'h82
+`define P4_RSP_MOTOR_STATUS 8'h83
 `define P4_SET_ALL_PAYLOAD_LENGTH 11
 `define P4_CHAMBER_PTC_COUNT 4
 `define P4_SET_ALL_FAN_OFFSET 0
@@ -24,15 +31,21 @@
 `define P4_SET_ALL_Z_DOOR_OFFSET 8
 `define P4_SET_ALL_EXHAUST_X_OFFSET 9
 `define P4_SET_ALL_EXHAUST_Y_OFFSET 10
+`define P4_DOOR_PERCENT_MIN 0
+`define P4_DOOR_PERCENT_MAX 100
+`define P4_OPEN_ENDPOINT_PERCENT 0
+`define P4_CLOSE_ENDPOINT_PERCENT 100
+`define P4_MID_PERCENT_MIN 1
+`define P4_MID_PERCENT_MAX 99
+`define P4_MOTOR_STATUS_PAYLOAD_LENGTH 31
+`define P4_MOTOR_STATUS_FRAME_LENGTH 37
 `define P4_MOTOR_OPEN_DIR 1'b0
 `define P4_MOTOR_CLOSE_DIR 1'b1
 `define P4_FRAME_INTER_BYTE_TIMEOUT_CYCLES 250000
-`define P4_FIXED_MOTOR_STEPS 450
 `define P4_MOTOR_STEP_RATE_HZ 1000
 `define P4_MOTOR_STEP_HALF_CYCLES 12500
 `define P4_MOTOR_DIR_SETUP_CYCLES 25000
 `define P4_MOTOR_DIR_SETUP_TICKS 2
-`define P4_MOTOR_HEARTBEAT_COMMAND 2'd0
 `define P4_TEMPERATURE_COUNT 27
 `define P4_TEMPERATURE_COUNT_BYTE 8'h1B
 `define P4_TEMPERATURE_FRAME_LENGTH 33
@@ -41,18 +54,34 @@
 `define P4_FAN_ACTIVE_HIGH 0
 `define P4_PTC_DEFAULT_TARGET 8'h00
 `define P4_FAN_DEFAULT_TARGET 8'h0A
-`define P4_WATCHDOG_TIMEOUT_SECONDS 10
+`define P4_WATCHDOG_TIMEOUT_SECONDS 30
 `define P4_WATCHDOG_TICK_US 500
 `define P4_WATCHDOG_TICK_CLKS 12500
-`define P4_WATCHDOG_TIMEOUT_TICKS 20000
+`define P4_WATCHDOG_TIMEOUT_TICKS 60000
+`define P4_WATCHDOG_ENABLE_AFTER_STARTUP 1
 `define P4_WATCHDOG_PTC_TARGET 8'h00
-`define P4_WATCHDOG_FAN_TARGET 8'h14
+`define P4_WATCHDOG_FAN_TARGET 8'h0A
 `define P4_STARTUP_ENABLED 1
 `define P4_STARTUP_DIR_MASK 3'b111
-`define P4_STARTUP_CLOSE_STEPS 5000
-`define P4_STARTUP_BACKOFF_STEPS 500
+`define P4_CAL_MAX_STEPS 5000
+`define P4_CAL_MIN_TRAVEL 2
+`define P4_ENDPOINT_GUARD_EXTRA 500
+`define P4_ENDPOINT_GUARD_MAX 5500
 `define P4_STARTUP_STEP_RATE_HZ 1000
 `define P4_MOTOR_ENABLE_POLICY_PERMANENT_HIGH 1
+`define P4_STATE_CAL_SEEK_CLOSE 8'd0
+`define P4_STATE_CAL_MEASURE_OPEN 8'd1
+`define P4_STATE_IDLE 8'd2
+`define P4_STATE_MOVE_OPEN 8'd3
+`define P4_STATE_MOVE_CLOSE 8'd4
+`define P4_STATE_WAIT_REPLAN 8'd5
+`define P4_STATE_FAULT 8'd6
+`define P4_FAULT_NONE 8'd0
+`define P4_FAULT_BOTH_LIMITS_ACTIVE 8'd1
+`define P4_FAULT_CAL_CLOSE_TIMEOUT 8'd2
+`define P4_FAULT_CAL_OPEN_TIMEOUT 8'd3
+`define P4_FAULT_INVALID_ZERO_OR_TINY_TRAVEL 8'd4
+`define P4_FAULT_ENDPOINT_TIMEOUT 8'd5
 `define P4_TEMP_DEVICE_ADDR_0 7'h49
 `define P4_TEMP_DEVICE_ADDR_1 7'h48
 `define P4_TEMP_DEVICE_ADDR_2 7'h4B

+ 3 - 3
src/generated/project-summary.json

@@ -32,10 +32,10 @@
   "temperature_payload_len": 27,
   "uart_clks_per_bit": 217,
   "watchdog_target": {
-    "fan": 20,
+    "fan": 10,
     "ptc": 0
   },
   "watchdog_tick_clks": 12500,
-  "watchdog_timeout_seconds": 10,
-  "watchdog_timeout_ticks": 20000
+  "watchdog_timeout_seconds": 30,
+  "watchdog_timeout_ticks": 60000
 }

+ 17 - 8
src/generated/td-source-manifest.json

@@ -126,7 +126,9 @@
     "limit_count": 6,
     "protocol": {
       "commands": {
+        "get_motor_status": 3,
         "get_temperature": 2,
+        "motor_status_data": 131,
         "set_all": 1,
         "temperature_data": 130
       },
@@ -140,15 +142,22 @@
         "wire_order": "little",
         "xor_output": 0
       },
+      "get_motor_status": {
+        "payload_length": 0,
+        "response": "motor_status_data"
+      },
       "header_hex": "A55A",
+      "motor_status_data": {
+        "frame_length": 37,
+        "layout": "host-contract",
+        "payload_length": 31
+      },
       "set_all": {
         "chamber_ptc_count": 4,
         "chamber_ptc_offset": 4,
-        "door_values": [
-          0,
-          1,
-          2
-        ],
+        "door_percent_max": 100,
+        "door_percent_min": 0,
+        "door_percent_rejected_example": 101,
         "duty_max": 100,
         "duty_min": 0,
         "exhaust_x_offset": 9,
@@ -194,9 +203,9 @@
     "src/modules/pwm_scheduler.v",
     "src/modules/shared_500us_tick.v",
     "src/modules/host_watchdog.v",
-    "src/modules/startup_close_seek.v",
-    "src/modules/door_motor_engine.v",
-    "src/modules/door_action_dispatcher.v",
+    "src/modules/door_percent_planner.v",
+    "src/modules/door_axis_controller.v",
+    "src/modules/door_motion_controller.v",
     "src/modules/i2c_word_reader.v",
     "src/modules/temperature_reader.v",
     "src/modules/temperature_ram.v",

+ 644 - 0
src/modules/door_axis_controller.v

@@ -0,0 +1,644 @@
+`timescale 1ns/1ps
+
+// Per-axis door percent FSM: cal seek-close → measure-open, then runtime
+// mid/endpoint motion with latest-wins replan. Position only on gated_step_rise.
+module door_axis_controller #(
+    parameter integer AXIS_ID = 0,
+    parameter integer MAX_CAL_STEPS = 5000,
+    parameter integer MIN_TRAVEL = 2,
+    parameter integer ENDPOINT_GUARD_EXTRA = 500,
+    parameter integer DIR_SETUP_TICKS = 2,
+    parameter integer PERCENT_MAX = 100
+) (
+    input  wire        clk,
+    input  wire        rst_n,
+    input  wire        open_limit,
+    input  wire        close_limit,
+    input  wire        limit_sync_valid,
+    input  wire        gated_step,
+    input  wire        gated_step_rise,
+    input  wire        tick_500us,
+    input  wire        request_valid,
+    input  wire [7:0]  requested_percent_in,
+    input  wire        watchdog_stop,
+    output reg         planner_req,
+    output wire [7:0]  planner_percent,
+    output wire [12:0] planner_travel,
+    input  wire        planner_done,
+    input  wire [1:0]  planner_done_axis,
+    input  wire [7:0]  planner_done_percent,
+    input  wire [12:0] planner_result,
+    output reg         step,
+    output reg         dir_close,
+    output reg  [2:0]  status_state,
+    output reg  [7:0]  status_flags,
+    output reg  [7:0]  status_requested_percent,
+    output reg  [12:0] status_current,
+    output reg  [12:0] status_target,
+    output reg  [12:0] status_travel,
+    output reg  [7:0]  status_fault_code,
+    output wire        calibrated,
+    output wire        faulted,
+    output wire        terminal
+);
+    localparam [2:0] ST_CAL_SEEK_CLOSE   = 3'd0;
+    localparam [2:0] ST_CAL_MEASURE_OPEN = 3'd1;
+    localparam [2:0] ST_IDLE             = 3'd2;
+    localparam [2:0] ST_MOVE_OPEN        = 3'd3;
+    localparam [2:0] ST_MOVE_CLOSE       = 3'd4;
+    localparam [2:0] ST_WAIT_REPLAN      = 3'd5;
+    localparam [2:0] ST_FAULT            = 3'd6;
+
+    localparam [2:0] FC_NONE              = 3'd0;
+    localparam [2:0] FC_BOTH_LIMITS       = 3'd1;
+    localparam [2:0] FC_CAL_CLOSE_TIMEOUT = 3'd2;
+    localparam [2:0] FC_CAL_OPEN_TIMEOUT  = 3'd3;
+    localparam [2:0] FC_TINY_TRAVEL       = 3'd4;
+    localparam [2:0] FC_ENDPOINT_TIMEOUT  = 3'd5;
+
+    localparam [2:0] PH_NONE       = 3'd0;
+    localparam [2:0] PH_DIR_SETUP  = 3'd1;
+    localparam [2:0] PH_RUN        = 3'd2;
+    localparam [2:0] PH_DRAIN_HIGH = 3'd3;
+
+    localparam integer CNT_W = 13;
+    localparam [CNT_W-1:0] MAX_STEPS_W = MAX_CAL_STEPS[CNT_W-1:0];
+    localparam [CNT_W-1:0] MIN_TRAVEL_W = MIN_TRAVEL[CNT_W-1:0];
+
+    reg        calibrated_r;
+    reg [2:0]  fault_code;
+    reg [CNT_W-1:0] travel_steps;
+    reg [CNT_W-1:0] current_position;
+    reg [CNT_W-1:0] target_position;
+    reg [7:0]  requested_percent;
+    reg        replan_pending;
+    reg        endpoint_mode;
+    reg        target_valid;
+    reg        moving;
+    reg [2:0]  phase;
+    reg [3:0]  setup_count;
+    reg [CNT_W-1:0] motion_count;
+    reg        allow_rise;
+    reg        stop_after_budget;
+    reg        cal_started;
+    reg        need_planner;
+    reg        wd_stopped;
+
+    assign calibrated = calibrated_r;
+    assign faulted = (status_state == ST_FAULT);
+    assign terminal = ((status_state == ST_IDLE) && calibrated_r) || (status_state == ST_FAULT);
+    assign planner_percent = requested_percent;
+    assign planner_travel = travel_steps;
+
+    wire both_limits = open_limit && close_limit;
+    wire mid_request = (requested_percent > 8'd0) && (requested_percent < PERCENT_MAX[7:0]);
+    wire is_open_endpoint = (requested_percent == 8'd0);
+    wire is_close_endpoint = (requested_percent == PERCENT_MAX[7:0]);
+    wire planner_accept = planner_done && (planner_done_axis == AXIS_ID[1:0]) &&
+        (planner_done_percent == requested_percent) && calibrated_r &&
+        (status_state != ST_FAULT) && mid_request && need_planner;
+    wire [CNT_W-1:0] guard_limit = travel_steps + ENDPOINT_GUARD_EXTRA[CNT_W-1:0];
+    wire in_calibration = (status_state == ST_CAL_SEEK_CLOSE) ||
+                          (status_state == ST_CAL_MEASURE_OPEN);
+
+    always @* begin
+        status_requested_percent = requested_percent;
+        status_current = current_position;
+        status_target = target_position;
+        status_travel = travel_steps;
+        status_fault_code = {5'd0, fault_code};
+        status_flags = {
+            1'b0,
+            replan_pending,
+            target_valid,
+            endpoint_mode,
+            moving,
+            calibrated_r,
+            close_limit,
+            open_limit
+        };
+    end
+
+    // Shared STEP half-period helper: returns next step level
+    function automatic step_toggle;
+        input cur_step;
+        input do_allow_rise;
+        begin
+            if (cur_step)
+                step_toggle = 1'b0;
+            else if (do_allow_rise)
+                step_toggle = 1'b1;
+            else
+                step_toggle = 1'b0;
+        end
+    endfunction
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            status_state <= ST_CAL_SEEK_CLOSE;
+            calibrated_r <= 1'b0;
+            fault_code <= FC_NONE;
+            travel_steps <= {CNT_W{1'b0}};
+            current_position <= {CNT_W{1'b0}};
+            target_position <= {CNT_W{1'b0}};
+            requested_percent <= 8'd0;
+            replan_pending <= 1'b0;
+            endpoint_mode <= 1'b0;
+            target_valid <= 1'b0;
+            moving <= 1'b0;
+            phase <= PH_NONE;
+            setup_count <= 4'd0;
+            motion_count <= {CNT_W{1'b0}};
+            allow_rise <= 1'b0;
+            stop_after_budget <= 1'b0;
+            cal_started <= 1'b0;
+            need_planner <= 1'b0;
+            planner_req <= 1'b0;
+            step <= 1'b0;
+            dir_close <= 1'b1;
+            wd_stopped <= 1'b0;
+        end else if (both_limits) begin
+            status_state <= ST_FAULT;
+            fault_code <= FC_BOTH_LIMITS;
+            step <= 1'b0;
+            phase <= PH_NONE;
+            moving <= 1'b0;
+            allow_rise <= 1'b0;
+            stop_after_budget <= 1'b0;
+            planner_req <= 1'b0;
+            need_planner <= 1'b0;
+            replan_pending <= 1'b0;
+            if (request_valid)
+                requested_percent <= requested_percent_in;
+        end else if (status_state == ST_FAULT) begin
+            step <= 1'b0;
+            moving <= 1'b0;
+            planner_req <= 1'b0;
+            if (request_valid)
+                requested_percent <= requested_percent_in;
+        end else begin
+            // ----------------------------------------------------------
+            // 1) Position / cal / guard counts on gated rise (always)
+            // ----------------------------------------------------------
+            if (gated_step_rise) begin
+                if (status_state == ST_CAL_SEEK_CLOSE ||
+                    status_state == ST_CAL_MEASURE_OPEN) begin
+                    motion_count <= motion_count + 1'b1;
+                end else if (calibrated_r) begin
+                    if (endpoint_mode)
+                        motion_count <= motion_count + 1'b1;
+                    if (dir_close) begin
+                        if (current_position < travel_steps)
+                            current_position <= current_position + 1'b1;
+                    end else begin
+                        if (current_position != {CNT_W{1'b0}})
+                            current_position <= current_position - 1'b1;
+                    end
+                end
+            end
+
+            // ----------------------------------------------------------
+            // 2) Host request (latest-wins). Preempts tick progression.
+            // ----------------------------------------------------------
+            if (request_valid && calibrated_r) begin
+                // Resume only if new percent, after watchdog, or idle-not-satisfied.
+                if ((requested_percent_in != requested_percent) ||
+                    wd_stopped ||
+                    ((status_state == ST_IDLE) && (
+                        ((requested_percent_in == 8'd0) && !open_limit) ||
+                        ((requested_percent_in == PERCENT_MAX[7:0]) && !close_limit) ||
+                        ((requested_percent_in > 8'd0) &&
+                         (requested_percent_in < PERCENT_MAX[7:0]) &&
+                         (current_position != target_position))
+                    ))) begin
+                    requested_percent <= requested_percent_in;
+                    wd_stopped <= 1'b0;
+                    replan_pending <= 1'b1;
+                    planner_req <= 1'b0;
+                    need_planner <= 1'b0;
+                    allow_rise <= 1'b0;
+                    // Same endpoint already in motion: do not reset guard/phase
+                    if ((requested_percent_in == requested_percent) &&
+                        endpoint_mode && moving &&
+                        ((status_state == ST_MOVE_OPEN) || (status_state == ST_MOVE_CLOSE)) &&
+                        !wd_stopped) begin
+                        // Idempotent heartbeat while correctly moving: keep going
+                        replan_pending <= 1'b0;
+                    end else if (gated_step || step) begin
+                        phase <= PH_DRAIN_HIGH;
+                        status_state <= ST_WAIT_REPLAN;
+                    end else begin
+                        step <= 1'b0;
+                        phase <= PH_NONE;
+                        moving <= 1'b0;
+                        status_state <= ST_WAIT_REPLAN;
+                    end
+                end else begin
+                    // Same target while already moving/planning/satisfied: no-op
+                    requested_percent <= requested_percent_in;
+                    wd_stopped <= 1'b0;
+                end
+
+            // ----------------------------------------------------------
+            // 3) Watchdog graceful stop (request same cycle already handled)
+            // ----------------------------------------------------------
+            end else if (watchdog_stop && calibrated_r && !in_calibration) begin
+                allow_rise <= 1'b0;
+                planner_req <= 1'b0;
+                need_planner <= 1'b0;
+                if (gated_step || step) begin
+                    phase <= PH_DRAIN_HIGH;
+                    status_state <= ST_WAIT_REPLAN;
+                    replan_pending <= 1'b0;
+                end else begin
+                    step <= 1'b0;
+                    phase <= PH_NONE;
+                    moving <= 1'b0;
+                    status_state <= ST_IDLE;
+                    wd_stopped <= 1'b1;
+                    replan_pending <= 1'b0;
+                end
+
+            // ----------------------------------------------------------
+            // 4) Planner result
+            // ----------------------------------------------------------
+            end else if (planner_accept) begin
+                planner_req <= 1'b0;
+                need_planner <= 1'b0;
+                replan_pending <= 1'b0;
+                target_position <= planner_result;
+                target_valid <= 1'b1;
+                endpoint_mode <= 1'b0;
+                motion_count <= {CNT_W{1'b0}};
+                step <= 1'b0;
+                setup_count <= 4'd0;
+                allow_rise <= 1'b0;
+                stop_after_budget <= 1'b0;
+                if (planner_result == current_position) begin
+                    status_state <= ST_IDLE;
+                    moving <= 1'b0;
+                    phase <= PH_NONE;
+                end else if (planner_result > current_position) begin
+                    dir_close <= 1'b1;
+                    phase <= PH_DIR_SETUP;
+                    moving <= 1'b1;
+                    status_state <= ST_MOVE_CLOSE;
+                end else begin
+                    dir_close <= 1'b0;
+                    phase <= PH_DIR_SETUP;
+                    moving <= 1'b1;
+                    status_state <= ST_MOVE_OPEN;
+                end
+
+            // ----------------------------------------------------------
+            // 5) Calibration start
+            // ----------------------------------------------------------
+            end else if (!cal_started) begin
+                if (limit_sync_valid) begin
+                    cal_started <= 1'b1;
+                    motion_count <= {CNT_W{1'b0}};
+                    setup_count <= 4'd0;
+                    allow_rise <= 1'b0;
+                    stop_after_budget <= 1'b0;
+                    step <= 1'b0;
+                    phase <= PH_DIR_SETUP;
+                    moving <= 1'b1;
+                    if (close_limit) begin
+                        dir_close <= 1'b0;
+                        status_state <= ST_CAL_MEASURE_OPEN;
+                    end else begin
+                        dir_close <= 1'b1;
+                        status_state <= ST_CAL_SEEK_CLOSE;
+                    end
+                end
+
+            // ----------------------------------------------------------
+            // 6) CAL_SEEK_CLOSE
+            // ----------------------------------------------------------
+            end else if (status_state == ST_CAL_SEEK_CLOSE) begin
+                if (close_limit) begin
+                    step <= 1'b0;
+                    allow_rise <= 1'b0;
+                    stop_after_budget <= 1'b0;
+                    motion_count <= {CNT_W{1'b0}};
+                    setup_count <= 4'd0;
+                    dir_close <= 1'b0;
+                    phase <= PH_DIR_SETUP;
+                    moving <= 1'b1;
+                    status_state <= ST_CAL_MEASURE_OPEN;
+                end else if (stop_after_budget && !gated_step && !step) begin
+                    status_state <= ST_FAULT;
+                    fault_code <= FC_CAL_CLOSE_TIMEOUT;
+                    moving <= 1'b0;
+                    phase <= PH_NONE;
+                end else begin
+                    // Use post-rise count: if count already at max, stop new rises
+                    if ((motion_count >= MAX_STEPS_W) ||
+                        (gated_step_rise && (motion_count + 1'b1 >= MAX_STEPS_W))) begin
+                        allow_rise <= 1'b0;
+                        stop_after_budget <= 1'b1;
+                    end
+                    if (phase == PH_DIR_SETUP) begin
+                        step <= 1'b0;
+                        if (tick_500us) begin
+                            if (setup_count + 1'b1 >= DIR_SETUP_TICKS[3:0]) begin
+                                phase <= PH_RUN;
+                                setup_count <= 4'd0;
+                                allow_rise <= !stop_after_budget && (motion_count < MAX_STEPS_W);
+                            end else begin
+                                setup_count <= setup_count + 1'b1;
+                            end
+                        end
+                    end else if (tick_500us) begin
+                        step <= step_toggle(step, allow_rise && !stop_after_budget &&
+                                            (motion_count < MAX_STEPS_W));
+                    end
+                end
+
+            // ----------------------------------------------------------
+            // 7) CAL_MEASURE_OPEN
+            // ----------------------------------------------------------
+            end else if (status_state == ST_CAL_MEASURE_OPEN) begin
+                if (open_limit) begin
+                    // motion_count already includes this cycle's rise (NBA: see old+1)
+                    // Use effective count: if rise this cycle, +1 on current
+                    if (gated_step_rise) begin
+                        // effective = motion_count+1 (scheduled); compare with that
+                        if (((motion_count + 1'b1) >= MIN_TRAVEL_W) &&
+                            ((motion_count + 1'b1) <= MAX_STEPS_W)) begin
+                            travel_steps <= motion_count + 1'b1;
+                            current_position <= {CNT_W{1'b0}};
+                            target_position <= {CNT_W{1'b0}};
+                            requested_percent <= 8'd0;
+                            calibrated_r <= 1'b1;
+                            fault_code <= FC_NONE;
+                            target_valid <= 1'b1;
+                            endpoint_mode <= 1'b1;
+                            step <= 1'b0;
+                            phase <= PH_NONE;
+                            moving <= 1'b0;
+                            allow_rise <= 1'b0;
+                            stop_after_budget <= 1'b0;
+                            status_state <= ST_IDLE;
+                        end else begin
+                            status_state <= ST_FAULT;
+                            fault_code <= FC_TINY_TRAVEL;
+                            step <= 1'b0;
+                            moving <= 1'b0;
+                            phase <= PH_NONE;
+                        end
+                    end else begin
+                        if ((motion_count >= MIN_TRAVEL_W) &&
+                            (motion_count <= MAX_STEPS_W)) begin
+                            travel_steps <= motion_count;
+                            current_position <= {CNT_W{1'b0}};
+                            target_position <= {CNT_W{1'b0}};
+                            requested_percent <= 8'd0;
+                            calibrated_r <= 1'b1;
+                            fault_code <= FC_NONE;
+                            target_valid <= 1'b1;
+                            endpoint_mode <= 1'b1;
+                            step <= 1'b0;
+                            phase <= PH_NONE;
+                            moving <= 1'b0;
+                            allow_rise <= 1'b0;
+                            stop_after_budget <= 1'b0;
+                            status_state <= ST_IDLE;
+                        end else begin
+                            status_state <= ST_FAULT;
+                            fault_code <= FC_TINY_TRAVEL;
+                            step <= 1'b0;
+                            moving <= 1'b0;
+                            phase <= PH_NONE;
+                        end
+                    end
+                end else if (stop_after_budget && !gated_step && !step) begin
+                    status_state <= ST_FAULT;
+                    fault_code <= FC_CAL_OPEN_TIMEOUT;
+                    moving <= 1'b0;
+                    phase <= PH_NONE;
+                end else begin
+                    if ((motion_count >= MAX_STEPS_W) ||
+                        (gated_step_rise && (motion_count + 1'b1 >= MAX_STEPS_W))) begin
+                        allow_rise <= 1'b0;
+                        stop_after_budget <= 1'b1;
+                    end
+                    if (phase == PH_DIR_SETUP) begin
+                        step <= 1'b0;
+                        if (tick_500us) begin
+                            if (setup_count + 1'b1 >= DIR_SETUP_TICKS[3:0]) begin
+                                phase <= PH_RUN;
+                                allow_rise <= !stop_after_budget && (motion_count < MAX_STEPS_W);
+                            end else begin
+                                setup_count <= setup_count + 1'b1;
+                            end
+                        end
+                    end else if (tick_500us) begin
+                        step <= step_toggle(step, allow_rise && !stop_after_budget &&
+                                            (motion_count < MAX_STEPS_W));
+                    end
+                end
+
+            // ----------------------------------------------------------
+            // 8) WAIT_REPLAN / drain / decide
+            // ----------------------------------------------------------
+            end else if (status_state == ST_WAIT_REPLAN) begin
+                if (phase == PH_DRAIN_HIGH) begin
+                    if (tick_500us)
+                        step <= 1'b0;
+                    if (!gated_step && (!step || tick_500us)) begin
+                        step <= 1'b0;
+                        phase <= PH_NONE;
+                        moving <= 1'b0;
+                        if (watchdog_stop) begin
+                            status_state <= ST_IDLE;
+                            wd_stopped <= 1'b1;
+                            replan_pending <= 1'b0;
+                        end else begin
+                            replan_pending <= 1'b1;
+                        end
+                    end
+                end else if (replan_pending) begin
+                    replan_pending <= 1'b0;
+                    if (is_open_endpoint) begin
+                        endpoint_mode <= 1'b1;
+                        target_position <= {CNT_W{1'b0}};
+                        target_valid <= 1'b1;
+                        need_planner <= 1'b0;
+                        planner_req <= 1'b0;
+                        if (open_limit) begin
+                            current_position <= {CNT_W{1'b0}};
+                            status_state <= ST_IDLE;
+                            moving <= 1'b0;
+                            step <= 1'b0;
+                            phase <= PH_NONE;
+                        end else begin
+                            motion_count <= {CNT_W{1'b0}};
+                            dir_close <= 1'b0;
+                            step <= 1'b0;
+                            setup_count <= 4'd0;
+                            allow_rise <= 1'b0;
+                            stop_after_budget <= 1'b0;
+                            phase <= PH_DIR_SETUP;
+                            moving <= 1'b1;
+                            status_state <= ST_MOVE_OPEN;
+                        end
+                    end else if (is_close_endpoint) begin
+                        endpoint_mode <= 1'b1;
+                        target_position <= travel_steps;
+                        target_valid <= 1'b1;
+                        need_planner <= 1'b0;
+                        planner_req <= 1'b0;
+                        if (close_limit) begin
+                            current_position <= travel_steps;
+                            status_state <= ST_IDLE;
+                            moving <= 1'b0;
+                            step <= 1'b0;
+                            phase <= PH_NONE;
+                        end else begin
+                            motion_count <= {CNT_W{1'b0}};
+                            dir_close <= 1'b1;
+                            step <= 1'b0;
+                            setup_count <= 4'd0;
+                            allow_rise <= 1'b0;
+                            stop_after_budget <= 1'b0;
+                            phase <= PH_DIR_SETUP;
+                            moving <= 1'b1;
+                            status_state <= ST_MOVE_CLOSE;
+                        end
+                    end else begin
+                        endpoint_mode <= 1'b0;
+                        need_planner <= 1'b1;
+                        planner_req <= 1'b1;
+                        moving <= 1'b0;
+                        step <= 1'b0;
+                        phase <= PH_NONE;
+                    end
+                end
+
+            // ----------------------------------------------------------
+            // 9) MOVE_OPEN / MOVE_CLOSE
+            // ----------------------------------------------------------
+            end else if ((status_state == ST_MOVE_OPEN) ||
+                         (status_state == ST_MOVE_CLOSE)) begin
+                if (endpoint_mode) begin
+                    if ((dir_close && close_limit) || (!dir_close && open_limit)) begin
+                        step <= 1'b0;
+                        allow_rise <= 1'b0;
+                        stop_after_budget <= 1'b0;
+                        phase <= PH_NONE;
+                        moving <= 1'b0;
+                        if (dir_close) begin
+                            current_position <= travel_steps;
+                            target_position <= travel_steps;
+                        end else begin
+                            current_position <= {CNT_W{1'b0}};
+                            target_position <= {CNT_W{1'b0}};
+                        end
+                        status_state <= ST_IDLE;
+                    end else if (stop_after_budget && !gated_step && !step) begin
+                        status_state <= ST_FAULT;
+                        fault_code <= FC_ENDPOINT_TIMEOUT;
+                        moving <= 1'b0;
+                        phase <= PH_NONE;
+                        step <= 1'b0;
+                    end else begin
+                        if ((motion_count >= guard_limit) ||
+                            (gated_step_rise && (motion_count + 1'b1 >= guard_limit))) begin
+                            allow_rise <= 1'b0;
+                            stop_after_budget <= 1'b1;
+                        end
+                        if (phase == PH_DIR_SETUP) begin
+                            step <= 1'b0;
+                            if (tick_500us) begin
+                                if (setup_count + 1'b1 >= DIR_SETUP_TICKS[3:0]) begin
+                                    phase <= PH_RUN;
+                                    allow_rise <= 1'b1;
+                                end else begin
+                                    setup_count <= setup_count + 1'b1;
+                                end
+                            end
+                        end else if (phase == PH_DRAIN_HIGH) begin
+                            if (tick_500us)
+                                step <= 1'b0;
+                        end else if (tick_500us) begin
+                            step <= step_toggle(step, allow_rise && !stop_after_budget &&
+                                                (motion_count < guard_limit));
+                        end
+                    end
+                end else begin
+                    // Mid-percent motion
+                    if ((dir_close && close_limit) || (!dir_close && open_limit)) begin
+                        step <= 1'b0;
+                        allow_rise <= 1'b0;
+                        if (dir_close)
+                            current_position <= travel_steps;
+                        else
+                            current_position <= {CNT_W{1'b0}};
+                        replan_pending <= 1'b1;
+                        need_planner <= 1'b0;
+                        planner_req <= 1'b0;
+                        phase <= PH_NONE;
+                        moving <= 1'b0;
+                        status_state <= ST_WAIT_REPLAN;
+                    end else begin
+                        // Effective current after this cycle's rise
+                        // Completion: compare using updated position intent
+                        if ((current_position == target_position) ||
+                            (gated_step_rise && dir_close &&
+                             (current_position + 1'b1 == target_position)) ||
+                            (gated_step_rise && !dir_close &&
+                             (current_position - 1'b1 == target_position))) begin
+                            allow_rise <= 1'b0;
+                            if (step || gated_step) begin
+                                phase <= PH_DRAIN_HIGH;
+                                if (tick_500us)
+                                    step <= 1'b0;
+                            end else begin
+                                step <= 1'b0;
+                                phase <= PH_NONE;
+                                moving <= 1'b0;
+                                status_state <= ST_IDLE;
+                            end
+                        end else if (phase == PH_DIR_SETUP) begin
+                            step <= 1'b0;
+                            if (tick_500us) begin
+                                if (setup_count + 1'b1 >= DIR_SETUP_TICKS[3:0]) begin
+                                    phase <= PH_RUN;
+                                    allow_rise <= 1'b1;
+                                end else begin
+                                    setup_count <= setup_count + 1'b1;
+                                end
+                            end
+                        end else if (phase == PH_DRAIN_HIGH) begin
+                            if (tick_500us)
+                                step <= 1'b0;
+                            if (!step && !gated_step) begin
+                                moving <= 1'b0;
+                                status_state <= ST_IDLE;
+                                phase <= PH_NONE;
+                            end else if (tick_500us && step) begin
+                                // falling this tick; next cycle check idle
+                            end
+                        end else if (tick_500us) begin
+                            step <= step_toggle(step, allow_rise);
+                        end
+                    end
+                end
+
+            // ----------------------------------------------------------
+            // 10) IDLE
+            // ----------------------------------------------------------
+            end else if (status_state == ST_IDLE) begin
+                step <= 1'b0;
+                moving <= 1'b0;
+                if (calibrated_r && is_open_endpoint && open_limit)
+                    current_position <= {CNT_W{1'b0}};
+                if (calibrated_r && is_close_endpoint && close_limit)
+                    current_position <= travel_steps;
+                if (replan_pending)
+                    status_state <= ST_WAIT_REPLAN;
+            end
+        end
+    end
+endmodule

+ 269 - 0
src/modules/door_motion_controller.v

@@ -0,0 +1,269 @@
+`timescale 1ns/1ps
+
+// Three-axis door motion: shared percent planner, startup_complete, status snapshot.
+module door_motion_controller #(
+    parameter integer MAX_CAL_STEPS = 5000,
+    parameter integer MIN_TRAVEL = 2,
+    parameter integer ENDPOINT_GUARD_EXTRA = 500,
+    parameter integer DIR_SETUP_TICKS = 2,
+    parameter integer PERCENT_MAX = 100,
+    parameter integer STATUS_PAYLOAD_LENGTH = 31
+) (
+    input  wire        clk,
+    input  wire        rst_n,
+    input  wire        tick_500us,
+    input  wire        limit_sync_valid,
+    input  wire [2:0]  open_limit,
+    input  wire [2:0]  close_limit,
+    input  wire [2:0]  gated_step,
+    input  wire [2:0]  gated_step_rise,
+    input  wire        motor_request_valid,
+    input  wire [7:0]  percent_x,
+    input  wire [7:0]  percent_y,
+    input  wire [7:0]  percent_z,
+    input  wire        watchdog_stop,
+    input  wire        watchdog_tripped,
+    output wire [2:0]  step,
+    output wire [2:0]  dir_close,
+    output reg         startup_complete,
+    output wire [2:0]  calibrated_mask,
+    output wire [2:0]  fault_mask,
+    // Snapshot capture / read (31-byte MOTOR_STATUS_DATA)
+    input  wire        status_capture,
+    input  wire [7:0]  status_rd_addr,
+    output reg  [7:0]  status_rd_data
+);
+    wire        planner_start;
+    wire [1:0]  planner_axis_id;
+    wire [7:0]  planner_percent_i;
+    wire [12:0] planner_travel_i;
+    wire        planner_busy;
+    wire        planner_done;
+    wire [12:0] planner_result;
+    wire [1:0]  planner_done_axis;
+    wire [7:0]  planner_done_percent;
+
+    wire        req_x, req_y, req_z;
+    wire [7:0]  pct_req_x, pct_req_y, pct_req_z;
+    wire [12:0] trav_req_x, trav_req_y, trav_req_z;
+
+    wire [2:0]  st_state_x, st_state_y, st_state_z;
+    wire [7:0]  st_flags_x, st_flags_y, st_flags_z;
+    wire [7:0]  st_pct_x, st_pct_y, st_pct_z;
+    wire [12:0] st_cur_x, st_cur_y, st_cur_z;
+    wire [12:0] st_tgt_x, st_tgt_y, st_tgt_z;
+    wire [12:0] st_trav_x, st_trav_y, st_trav_z;
+    wire [7:0]  st_fault_x, st_fault_y, st_fault_z;
+    wire        cal_x, cal_y, cal_z;
+    wire        fault_x, fault_y, fault_z;
+    wire        term_x, term_y, term_z;
+
+    assign calibrated_mask = {cal_z, cal_y, cal_x};
+    assign fault_mask = {fault_z, fault_y, fault_x};
+
+    door_percent_planner u_planner (
+        .clk(clk), .rst_n(rst_n),
+        .start(planner_start),
+        .axis_id(planner_axis_id),
+        .percent(planner_percent_i),
+        .travel(planner_travel_i),
+        .busy(planner_busy),
+        .done(planner_done),
+        .result(planner_result),
+        .done_axis_id(planner_done_axis),
+        .done_percent(planner_done_percent)
+    );
+
+    // X→Y→Z arbiter: level req while planner idle
+    reg        grant_start;
+    reg [1:0]  grant_axis;
+    reg [7:0]  grant_percent;
+    reg [12:0] grant_travel;
+
+    assign planner_start = grant_start;
+    assign planner_axis_id = grant_axis;
+    assign planner_percent_i = grant_percent;
+    assign planner_travel_i = grant_travel;
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            grant_start <= 1'b0;
+            grant_axis <= 2'd0;
+            grant_percent <= 8'd0;
+            grant_travel <= 13'd0;
+        end else begin
+            grant_start <= 1'b0;
+            if (!planner_busy && !grant_start) begin
+                if (req_x) begin
+                    grant_start <= 1'b1;
+                    grant_axis <= 2'd0;
+                    grant_percent <= pct_req_x;
+                    grant_travel <= trav_req_x;
+                end else if (req_y) begin
+                    grant_start <= 1'b1;
+                    grant_axis <= 2'd1;
+                    grant_percent <= pct_req_y;
+                    grant_travel <= trav_req_y;
+                end else if (req_z) begin
+                    grant_start <= 1'b1;
+                    grant_axis <= 2'd2;
+                    grant_percent <= pct_req_z;
+                    grant_travel <= trav_req_z;
+                end
+            end
+        end
+    end
+
+    door_axis_controller #(
+        .AXIS_ID(0),
+        .MAX_CAL_STEPS(MAX_CAL_STEPS),
+        .MIN_TRAVEL(MIN_TRAVEL),
+        .ENDPOINT_GUARD_EXTRA(ENDPOINT_GUARD_EXTRA),
+        .DIR_SETUP_TICKS(DIR_SETUP_TICKS),
+        .PERCENT_MAX(PERCENT_MAX)
+    ) u_axis_x (
+        .clk(clk), .rst_n(rst_n),
+        .open_limit(open_limit[0]), .close_limit(close_limit[0]),
+        .limit_sync_valid(limit_sync_valid),
+        .gated_step(gated_step[0]), .gated_step_rise(gated_step_rise[0]),
+        .tick_500us(tick_500us),
+        .request_valid(motor_request_valid),
+        .requested_percent_in(percent_x),
+        .watchdog_stop(watchdog_stop),
+        .planner_req(req_x),
+        .planner_percent(pct_req_x),
+        .planner_travel(trav_req_x),
+        .planner_done(planner_done),
+        .planner_done_axis(planner_done_axis),
+        .planner_done_percent(planner_done_percent),
+        .planner_result(planner_result),
+        .step(step[0]), .dir_close(dir_close[0]),
+        .status_state(st_state_x), .status_flags(st_flags_x),
+        .status_requested_percent(st_pct_x),
+        .status_current(st_cur_x), .status_target(st_tgt_x),
+        .status_travel(st_trav_x), .status_fault_code(st_fault_x),
+        .calibrated(cal_x), .faulted(fault_x), .terminal(term_x)
+    );
+
+    door_axis_controller #(
+        .AXIS_ID(1),
+        .MAX_CAL_STEPS(MAX_CAL_STEPS),
+        .MIN_TRAVEL(MIN_TRAVEL),
+        .ENDPOINT_GUARD_EXTRA(ENDPOINT_GUARD_EXTRA),
+        .DIR_SETUP_TICKS(DIR_SETUP_TICKS),
+        .PERCENT_MAX(PERCENT_MAX)
+    ) u_axis_y (
+        .clk(clk), .rst_n(rst_n),
+        .open_limit(open_limit[1]), .close_limit(close_limit[1]),
+        .limit_sync_valid(limit_sync_valid),
+        .gated_step(gated_step[1]), .gated_step_rise(gated_step_rise[1]),
+        .tick_500us(tick_500us),
+        .request_valid(motor_request_valid),
+        .requested_percent_in(percent_y),
+        .watchdog_stop(watchdog_stop),
+        .planner_req(req_y),
+        .planner_percent(pct_req_y),
+        .planner_travel(trav_req_y),
+        .planner_done(planner_done),
+        .planner_done_axis(planner_done_axis),
+        .planner_done_percent(planner_done_percent),
+        .planner_result(planner_result),
+        .step(step[1]), .dir_close(dir_close[1]),
+        .status_state(st_state_y), .status_flags(st_flags_y),
+        .status_requested_percent(st_pct_y),
+        .status_current(st_cur_y), .status_target(st_tgt_y),
+        .status_travel(st_trav_y), .status_fault_code(st_fault_y),
+        .calibrated(cal_y), .faulted(fault_y), .terminal(term_y)
+    );
+
+    door_axis_controller #(
+        .AXIS_ID(2),
+        .MAX_CAL_STEPS(MAX_CAL_STEPS),
+        .MIN_TRAVEL(MIN_TRAVEL),
+        .ENDPOINT_GUARD_EXTRA(ENDPOINT_GUARD_EXTRA),
+        .DIR_SETUP_TICKS(DIR_SETUP_TICKS),
+        .PERCENT_MAX(PERCENT_MAX)
+    ) u_axis_z (
+        .clk(clk), .rst_n(rst_n),
+        .open_limit(open_limit[2]), .close_limit(close_limit[2]),
+        .limit_sync_valid(limit_sync_valid),
+        .gated_step(gated_step[2]), .gated_step_rise(gated_step_rise[2]),
+        .tick_500us(tick_500us),
+        .request_valid(motor_request_valid),
+        .requested_percent_in(percent_z),
+        .watchdog_stop(watchdog_stop),
+        .planner_req(req_z),
+        .planner_percent(pct_req_z),
+        .planner_travel(trav_req_z),
+        .planner_done(planner_done),
+        .planner_done_axis(planner_done_axis),
+        .planner_done_percent(planner_done_percent),
+        .planner_result(planner_result),
+        .step(step[2]), .dir_close(dir_close[2]),
+        .status_state(st_state_z), .status_flags(st_flags_z),
+        .status_requested_percent(st_pct_z),
+        .status_current(st_cur_z), .status_target(st_tgt_z),
+        .status_travel(st_trav_z), .status_fault_code(st_fault_z),
+        .calibrated(cal_z), .faulted(fault_z), .terminal(term_z)
+    );
+
+    // Sticky startup_complete when all axes terminal
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n)
+            startup_complete <= 1'b0;
+        else if (!startup_complete && term_x && term_y && term_z)
+            startup_complete <= 1'b1;
+    end
+
+    // -------- 31-byte atomic snapshot --------
+    reg [7:0] snap [0:30];
+    integer si;
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            for (si = 0; si < STATUS_PAYLOAD_LENGTH; si = si + 1)
+                snap[si] <= 8'd0;
+            status_rd_data <= 8'd0;
+        end else begin
+            if (status_capture) begin
+                // byte0: cal[2:0], fault[2:0], startup, watchdog
+                snap[0] <= {watchdog_tripped, startup_complete, fault_mask, calibrated_mask};
+                // X @1, Y @11, Z @21
+                snap[1]  <= {5'd0, st_state_x};
+                snap[2]  <= st_flags_x;
+                snap[3]  <= st_pct_x;
+                snap[4]  <= st_cur_x[7:0];
+                snap[5]  <= {3'd0, st_cur_x[12:8]};
+                snap[6]  <= st_tgt_x[7:0];
+                snap[7]  <= {3'd0, st_tgt_x[12:8]};
+                snap[8]  <= st_trav_x[7:0];
+                snap[9]  <= {3'd0, st_trav_x[12:8]};
+                snap[10] <= st_fault_x;
+                snap[11] <= {5'd0, st_state_y};
+                snap[12] <= st_flags_y;
+                snap[13] <= st_pct_y;
+                snap[14] <= st_cur_y[7:0];
+                snap[15] <= {3'd0, st_cur_y[12:8]};
+                snap[16] <= st_tgt_y[7:0];
+                snap[17] <= {3'd0, st_tgt_y[12:8]};
+                snap[18] <= st_trav_y[7:0];
+                snap[19] <= {3'd0, st_trav_y[12:8]};
+                snap[20] <= st_fault_y;
+                snap[21] <= {5'd0, st_state_z};
+                snap[22] <= st_flags_z;
+                snap[23] <= st_pct_z;
+                snap[24] <= st_cur_z[7:0];
+                snap[25] <= {3'd0, st_cur_z[12:8]};
+                snap[26] <= st_tgt_z[7:0];
+                snap[27] <= {3'd0, st_tgt_z[12:8]};
+                snap[28] <= st_trav_z[7:0];
+                snap[29] <= {3'd0, st_trav_z[12:8]};
+                snap[30] <= st_fault_z;
+            end
+            if (status_rd_addr < STATUS_PAYLOAD_LENGTH[7:0])
+                status_rd_data <= snap[status_rd_addr];
+            else
+                status_rd_data <= 8'd0;
+        end
+    end
+endmodule

+ 84 - 0
src/modules/door_percent_planner.v

@@ -0,0 +1,84 @@
+`timescale 1ns/1ps
+
+// Shared iterative half-up percent → steps planner (no DSP).
+// result = clamp(round_half_up(travel * percent / 100), 1, travel-1)
+module door_percent_planner (
+    input  wire        clk,
+    input  wire        rst_n,
+    input  wire        start,
+    input  wire [1:0]  axis_id,
+    input  wire [7:0]  percent,
+    input  wire [12:0] travel,
+    output reg         busy,
+    output reg         done,
+    output reg  [12:0] result,
+    output reg  [1:0]  done_axis_id,
+    output reg  [7:0]  done_percent
+);
+    reg [7:0]  acc;
+    reg [12:0] remaining;
+    reg [12:0] accum_result;
+    reg [12:0] travel_latched;
+    reg [7:0]  percent_latched;
+    reg [1:0]  axis_latched;
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            busy <= 1'b0;
+            done <= 1'b0;
+            result <= 13'd0;
+            done_axis_id <= 2'd0;
+            done_percent <= 8'd0;
+            acc <= 8'd0;
+            remaining <= 13'd0;
+            accum_result <= 13'd0;
+            travel_latched <= 13'd0;
+            percent_latched <= 8'd0;
+            axis_latched <= 2'd0;
+        end else begin
+            done <= 1'b0;
+            if (start && !busy) begin
+                busy <= 1'b1;
+                accum_result <= 13'd0;
+                acc <= 8'd50;
+                remaining <= travel;
+                travel_latched <= travel;
+                percent_latched <= percent;
+                axis_latched <= axis_id;
+                // Degenerate travel: finish immediately with clamped mid (1 if travel>=2 else 0).
+                if (travel == 13'd0) begin
+                    busy <= 1'b0;
+                    done <= 1'b1;
+                    result <= 13'd0;
+                    done_axis_id <= axis_id;
+                    done_percent <= percent;
+                end
+            end else if (busy) begin
+                if (remaining != 13'd0) begin
+                    if ((acc + percent_latched) >= 8'd100) begin
+                        acc <= acc + percent_latched - 8'd100;
+                        accum_result <= accum_result + 13'd1;
+                    end else begin
+                        acc <= acc + percent_latched;
+                    end
+                    remaining <= remaining - 13'd1;
+                end else begin
+                    // Clamp mid targets to 1 .. travel-1
+                    if (travel_latched <= 13'd1) begin
+                        result <= 13'd0;
+                    end else if (accum_result < 13'd1) begin
+                        result <= 13'd1;
+                    end else if (accum_result >= travel_latched) begin
+                        result <= travel_latched - 13'd1;
+                    end else begin
+                        result <= accum_result;
+                    end
+                    done_axis_id <= axis_latched;
+                    done_percent <= percent_latched;
+                    busy <= 1'b0;
+                    done <= 1'b1;
+                end
+            end
+        end
+    end
+endmodule

+ 16 - 2
src/modules/host_watchdog.v

@@ -1,10 +1,11 @@
 `timescale 1ns/1ps
 
 module host_watchdog #(
-    parameter integer TIMEOUT_TICKS = 20_000
+    parameter integer TIMEOUT_TICKS = 60_000
 ) (
     input  wire clk,
     input  wire rst_n,
+    input  wire enable,
     input  wire tick_500us,
     input  wire valid_set_all_commit,
     output reg  watchdog_active,
@@ -12,15 +13,28 @@ module host_watchdog #(
 );
     localparam integer COUNTER_BITS = (TIMEOUT_TICKS <= 1) ? 1 : $clog2(TIMEOUT_TICKS + 1);
     reg [COUNTER_BITS-1:0] tick_count;
+    reg enable_d;
 
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
             tick_count <= {COUNTER_BITS{1'b0}};
             watchdog_active <= 1'b0;
             timeout_event <= 1'b0;
+            enable_d <= 1'b0;
         end else begin
             timeout_event <= 1'b0;
-            if (valid_set_all_commit) begin
+            enable_d <= enable;
+
+            if (!enable) begin
+                // Disabled: clear counter and active; do not trip
+                tick_count <= {COUNTER_BITS{1'b0}};
+                watchdog_active <= 1'b0;
+            end else if (valid_set_all_commit) begin
+                // Feed has priority over same-cycle timeout
+                tick_count <= {COUNTER_BITS{1'b0}};
+                watchdog_active <= 1'b0;
+            end else if (!enable_d && enable) begin
+                // 0→1: start full timeout from zero
                 tick_count <= {COUNTER_BITS{1'b0}};
                 watchdog_active <= 1'b0;
             end else if (tick_500us && !watchdog_active) begin

+ 77 - 25
src/project/command_controller.v

@@ -9,7 +9,14 @@ module command_controller #(
     parameter integer CHAMBER_PTC_OFFSET = 4,
     parameter integer Z_DOOR_OFFSET = 8,
     parameter integer EXHAUST_X_OFFSET = 9,
-    parameter integer EXHAUST_Y_OFFSET = 10
+    parameter integer EXHAUST_Y_OFFSET = 10,
+    parameter [7:0]   CMD_GET_TEMPERATURE = 8'h02,
+    parameter [7:0]   CMD_GET_MOTOR_STATUS = 8'h03,
+    parameter [7:0]   RSP_TEMPERATURE = 8'h82,
+    parameter [7:0]   RSP_MOTOR_STATUS = 8'h83,
+    parameter integer TEMP_PAYLOAD_LENGTH = 27,
+    parameter integer MOTOR_STATUS_PAYLOAD_LENGTH = 31,
+    parameter integer DOOR_PERCENT_MAX = 100
 ) (
     input  wire       clk,
     input  wire       rst_n,
@@ -24,13 +31,19 @@ module command_controller #(
     output reg  [3:0] target_wr_addr,
     output reg  [7:0] target_wr_data,
     output reg        valid_set_all_commit,
-    output reg  [1:0] z_door_cmd,
-    output reg  [1:0] exhaust_x_cmd,
-    output reg  [1:0] exhaust_y_cmd,
-    output reg        door_action_valid,
+    // Door percent (byte8=Z, byte9=X, byte10=Y)
+    output reg  [7:0] door_percent_z,
+    output reg  [7:0] door_percent_x,
+    output reg  [7:0] door_percent_y,
+    output reg        motor_request_valid,
+    input  wire       startup_complete,
     output reg        temperature_start,
     input  wire       temperature_done,
+    output reg        status_capture,
     output reg        tx_start,
+    output reg  [7:0] tx_frame_type,
+    output reg  [7:0] tx_payload_length,
+    output reg        tx_payload_is_status, // 0=temperature RAM, 1=motor status snap
     input  wire       tx_done,
     output wire       busy
 );
@@ -44,8 +57,9 @@ module command_controller #(
     localparam [3:0] ST_WRITE_PTC = 4'd7;
     localparam [3:0] ST_COMMIT = 4'd8;
     localparam [3:0] ST_TEMPERATURE = 4'd9;
-    localparam [3:0] ST_TX = 4'd10;
-    localparam [3:0] ST_DRAIN = 4'd11;
+    localparam [3:0] ST_STATUS_CAPTURE = 4'd10;
+    localparam [3:0] ST_TX = 4'd11;
+    localparam [3:0] ST_DRAIN = 4'd12;
 
     reg [3:0] state;
     reg [2:0] validate_index;
@@ -53,6 +67,10 @@ module command_controller #(
     reg [7:0] fan_values [0:3];
     reg [7:0] ptc_values [0:3];
     reg [1:0] ptc_write_phase;
+    // Registered previous-cycle startup for commit race:
+    // if startup_complete rises same cycle as commit, ignore motors.
+    reg       startup_complete_d;
+    reg       motor_submit_armed;
 
     assign frame_ready = (state == ST_IDLE) || (state == ST_DRAIN);
     assign frame_accept_enable = (state == ST_IDLE);
@@ -77,31 +95,57 @@ module command_controller #(
             validate_index <= 3'd0;
             write_index <= 3'd0;
             ptc_write_phase <= 2'd0;
-            z_door_cmd <= 2'd0;
-            exhaust_x_cmd <= 2'd0;
-            exhaust_y_cmd <= 2'd0;
+            door_percent_z <= 8'd0;
+            door_percent_x <= 8'd0;
+            door_percent_y <= 8'd0;
             valid_set_all_commit <= 1'b0;
-            door_action_valid <= 1'b0;
+            motor_request_valid <= 1'b0;
+            motor_submit_armed <= 1'b0;
+            startup_complete_d <= 1'b0;
             target_wr_en <= 1'b0;
             target_wr_addr <= 4'd0;
             target_wr_data <= 8'd0;
             temperature_start <= 1'b0;
+            status_capture <= 1'b0;
             tx_start <= 1'b0;
+            tx_frame_type <= RSP_TEMPERATURE;
+            tx_payload_length <= TEMP_PAYLOAD_LENGTH[7:0];
+            tx_payload_is_status <= 1'b0;
         end else begin
             valid_set_all_commit <= 1'b0;
-            door_action_valid <= 1'b0;
+            motor_request_valid <= 1'b0;
             target_wr_en <= 1'b0;
             temperature_start <= 1'b0;
+            status_capture <= 1'b0;
             tx_start <= 1'b0;
+            startup_complete_d <= startup_complete;
+
             case (state)
                 ST_IDLE: begin
                     if (frame_valid) begin
-                        if ((frame_type == 8'h01) && (frame_length == SET_ALL_PAYLOAD_LENGTH[7:0])) begin
+                        if ((frame_type == 8'h01) &&
+                            (frame_length == SET_ALL_PAYLOAD_LENGTH[7:0])) begin
                             validate_index <= 3'd0;
                             state <= ST_VALIDATE_FAN;
-                        end else if ((frame_type == 8'h02) && (frame_length == 8'd0)) begin
-                            temperature_start <= 1'b1;
-                            state <= ST_TEMPERATURE;
+                        end else if ((frame_type == CMD_GET_TEMPERATURE) &&
+                                     (frame_length == 8'd0)) begin
+                            if (startup_complete) begin
+                                temperature_start <= 1'b1;
+                                tx_frame_type <= RSP_TEMPERATURE;
+                                tx_payload_length <= TEMP_PAYLOAD_LENGTH[7:0];
+                                tx_payload_is_status <= 1'b0;
+                                state <= ST_TEMPERATURE;
+                            end else begin
+                                // Pre-startup GET_TEMP: silent drain
+                                state <= ST_DRAIN;
+                            end
+                        end else if ((frame_type == CMD_GET_MOTOR_STATUS) &&
+                                     (frame_length == 8'd0)) begin
+                            status_capture <= 1'b1;
+                            tx_frame_type <= RSP_MOTOR_STATUS;
+                            tx_payload_length <= MOTOR_STATUS_PAYLOAD_LENGTH[7:0];
+                            tx_payload_is_status <= 1'b1;
+                            state <= ST_STATUS_CAPTURE;
                         end else begin
                             state <= ST_DRAIN;
                         end
@@ -133,26 +177,26 @@ module command_controller #(
                     end
                 end
                 ST_VALIDATE_Z: begin
-                    if (payload_read_data > 8'd2) begin
+                    if (payload_read_data > DOOR_PERCENT_MAX[7:0]) begin
                         state <= ST_DRAIN;
                     end else begin
-                        z_door_cmd <= payload_read_data[1:0];
+                        door_percent_z <= payload_read_data;
                         state <= ST_VALIDATE_X;
                     end
                 end
                 ST_VALIDATE_X: begin
-                    if (payload_read_data > 8'd2) begin
+                    if (payload_read_data > DOOR_PERCENT_MAX[7:0]) begin
                         state <= ST_DRAIN;
                     end else begin
-                        exhaust_x_cmd <= payload_read_data[1:0];
+                        door_percent_x <= payload_read_data;
                         state <= ST_VALIDATE_Y;
                     end
                 end
                 ST_VALIDATE_Y: begin
-                    if (payload_read_data > 8'd2) begin
+                    if (payload_read_data > DOOR_PERCENT_MAX[7:0]) begin
                         state <= ST_DRAIN;
                     end else begin
-                        exhaust_y_cmd <= payload_read_data[1:0];
+                        door_percent_y <= payload_read_data;
                         write_index <= 3'd0;
                         ptc_write_phase <= 2'd0;
                         state <= ST_WRITE_FAN;
@@ -170,8 +214,6 @@ module command_controller #(
                     end
                 end
                 ST_WRITE_PTC: begin
-                    // Each chamber PTC duty is duplicated to a physical pair:
-                    // chamber i -> channels {2*i, 2*i+1}.
                     target_wr_en <= 1'b1;
                     target_wr_data <= ptc_values[write_index];
                     if (ptc_write_phase == 2'd0) begin
@@ -181,6 +223,8 @@ module command_controller #(
                         target_wr_addr <= {1'b0, write_index[1:0], 1'b1};
                         ptc_write_phase <= 2'd0;
                         if (write_index == CHAMBER_PTC_COUNT - 1) begin
+                            // Arm motor submit from registered (previous-cycle) startup
+                            motor_submit_armed <= startup_complete_d;
                             state <= ST_COMMIT;
                         end else begin
                             write_index <= write_index + 1'b1;
@@ -189,7 +233,10 @@ module command_controller #(
                 end
                 ST_COMMIT: begin
                     valid_set_all_commit <= 1'b1;
-                    door_action_valid <= 1'b1;
+                    if (motor_submit_armed) begin
+                        motor_request_valid <= 1'b1;
+                    end
+                    motor_submit_armed <= 1'b0;
                     state <= ST_DRAIN;
                 end
                 ST_TEMPERATURE: begin
@@ -198,6 +245,11 @@ module command_controller #(
                         state <= ST_TX;
                     end
                 end
+                ST_STATUS_CAPTURE: begin
+                    // One-cycle gap after capture before tx_start (frame_tx latency)
+                    tx_start <= 1'b1;
+                    state <= ST_TX;
+                end
                 ST_TX: begin
                     if (tx_done) state <= ST_DRAIN;
                 end

+ 35 - 36
src/project/project_adapter.v

@@ -10,9 +10,13 @@ module project_adapter #(
     parameter integer Z_DOOR_OFFSET = 8,
     parameter integer EXHAUST_X_OFFSET = 9,
     parameter integer EXHAUST_Y_OFFSET = 10,
-    parameter integer OPEN_DIR = 0,
-    parameter integer CLOSE_DIR = 1,
-    parameter integer AXIS_COUNT = 3
+    parameter [7:0]   CMD_GET_TEMPERATURE = 8'h02,
+    parameter [7:0]   CMD_GET_MOTOR_STATUS = 8'h03,
+    parameter [7:0]   RSP_TEMPERATURE = 8'h82,
+    parameter [7:0]   RSP_MOTOR_STATUS = 8'h83,
+    parameter integer TEMP_PAYLOAD_LENGTH = 27,
+    parameter integer MOTOR_STATUS_PAYLOAD_LENGTH = 31,
+    parameter integer DOOR_PERCENT_MAX = 100
 ) (
     input  wire       clk,
     input  wire       rst_n,
@@ -27,22 +31,21 @@ module project_adapter #(
     output wire [3:0] target_wr_addr,
     output wire [7:0] target_wr_data,
     output wire       valid_set_all_commit,
-    output wire       motor_start,
-    output wire [AXIS_COUNT-1:0] motor_active_mask,
-    output wire [AXIS_COUNT-1:0] motor_dir_mask,
-    input  wire       motor_busy,
-    input  wire       watchdog_abort,
+    output wire       motor_request_valid,
+    output wire [7:0] door_percent_x,
+    output wire [7:0] door_percent_y,
+    output wire [7:0] door_percent_z,
+    input  wire       startup_complete,
     output wire       temperature_start,
     input  wire       temperature_done,
+    output wire       status_capture,
     output wire       tx_start,
+    output wire [7:0] tx_frame_type,
+    output wire [7:0] tx_payload_length,
+    output wire       tx_payload_is_status,
     input  wire       tx_done,
     output wire       busy
 );
-    wire [1:0] z_door_cmd;
-    wire [1:0] exhaust_x_cmd;
-    wire [1:0] exhaust_y_cmd;
-    wire door_action_valid;
-
     command_controller #(
         .PTC_COUNT(PTC_COUNT),
         .FAN_COUNT(FAN_COUNT),
@@ -52,7 +55,14 @@ module project_adapter #(
         .CHAMBER_PTC_OFFSET(CHAMBER_PTC_OFFSET),
         .Z_DOOR_OFFSET(Z_DOOR_OFFSET),
         .EXHAUST_X_OFFSET(EXHAUST_X_OFFSET),
-        .EXHAUST_Y_OFFSET(EXHAUST_Y_OFFSET)
+        .EXHAUST_Y_OFFSET(EXHAUST_Y_OFFSET),
+        .CMD_GET_TEMPERATURE(CMD_GET_TEMPERATURE),
+        .CMD_GET_MOTOR_STATUS(CMD_GET_MOTOR_STATUS),
+        .RSP_TEMPERATURE(RSP_TEMPERATURE),
+        .RSP_MOTOR_STATUS(RSP_MOTOR_STATUS),
+        .TEMP_PAYLOAD_LENGTH(TEMP_PAYLOAD_LENGTH),
+        .MOTOR_STATUS_PAYLOAD_LENGTH(MOTOR_STATUS_PAYLOAD_LENGTH),
+        .DOOR_PERCENT_MAX(DOOR_PERCENT_MAX)
     ) controller (
         .clk(clk), .rst_n(rst_n),
         .frame_valid(frame_valid), .frame_ready(frame_ready),
@@ -62,28 +72,17 @@ module project_adapter #(
         .target_wr_en(target_wr_en), .target_wr_addr(target_wr_addr),
         .target_wr_data(target_wr_data),
         .valid_set_all_commit(valid_set_all_commit),
-        .z_door_cmd(z_door_cmd),
-        .exhaust_x_cmd(exhaust_x_cmd),
-        .exhaust_y_cmd(exhaust_y_cmd),
-        .door_action_valid(door_action_valid),
+        .door_percent_z(door_percent_z),
+        .door_percent_x(door_percent_x),
+        .door_percent_y(door_percent_y),
+        .motor_request_valid(motor_request_valid),
+        .startup_complete(startup_complete),
         .temperature_start(temperature_start), .temperature_done(temperature_done),
-        .tx_start(tx_start), .tx_done(tx_done), .busy(busy)
-    );
-
-    door_action_dispatcher #(
-        .OPEN_DIR(OPEN_DIR),
-        .CLOSE_DIR(CLOSE_DIR),
-        .AXIS_COUNT(AXIS_COUNT)
-    ) u_door_dispatch (
-        .clk(clk), .rst_n(rst_n),
-        .door_action_valid(door_action_valid),
-        .z_door_cmd(z_door_cmd),
-        .exhaust_x_cmd(exhaust_x_cmd),
-        .exhaust_y_cmd(exhaust_y_cmd),
-        .watchdog_abort(watchdog_abort),
-        .motor_start(motor_start),
-        .motor_active_mask(motor_active_mask),
-        .motor_dir_mask(motor_dir_mask),
-        .motor_busy(motor_busy)
+        .status_capture(status_capture),
+        .tx_start(tx_start),
+        .tx_frame_type(tx_frame_type),
+        .tx_payload_length(tx_payload_length),
+        .tx_payload_is_status(tx_payload_is_status),
+        .tx_done(tx_done), .busy(busy)
     );
 endmodule

+ 85 - 90
src/top/prod2u_p4_normal_v3_top.v

@@ -30,10 +30,6 @@ module prod2u_p4_normal_v3_top (
     endgenerate
 
     localparam integer AXIS_COUNT = `P4_AXIS_COUNT;
-    localparam integer MOTOR_STEP_WIDTH =
-        (`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;
-    // 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;
@@ -59,25 +55,11 @@ module prod2u_p4_normal_v3_top (
     wire [3:0] target_wr_addr;
     wire [7:0] target_wr_data;
     wire valid_set_all_commit;
-    wire host_motor_start;
-    wire [AXIS_COUNT-1:0] host_motor_active_mask;
-    wire [AXIS_COUNT-1:0] host_motor_dir_mask;
-    wire motor_start;
-    wire [AXIS_COUNT-1:0] motor_active_mask;
-    wire [AXIS_COUNT-1:0] motor_dir_mask;
-    wire [MOTOR_STEP_WIDTH-1:0] motor_step_count;
-    wire [MOTOR_STEP_WIDTH-1:0] host_motor_step_count;
-    wire [MOTOR_STEP_WIDTH-1:0] startup_motor_step_count;
-    wire motor_done;
-    wire motor_busy;
-    wire motor_abort_done;
-    wire startup_done;
-    wire startup_motor_start;
-    wire [AXIS_COUNT-1:0] startup_motor_active_mask;
-    wire [AXIS_COUNT-1:0] startup_motor_dir_mask;
-    wire [AXIS_COUNT-1:0] startup_motor_stop_mask;
-    wire [AXIS_COUNT-1:0] runtime_limit_stop_mask;
-    wire [AXIS_COUNT-1:0] motor_stop_mask;
+    wire motor_request_valid;
+    wire [7:0] door_percent_x;
+    wire [7:0] door_percent_y;
+    wire [7:0] door_percent_z;
+    wire startup_complete;
     wire [AXIS_COUNT-1:0] engine_step;
     wire [AXIS_COUNT-1:0] engine_dir;
 
@@ -94,6 +76,9 @@ module prod2u_p4_normal_v3_top (
     wire [AXIS_COUNT-1:0] close_limit;
     wire [AXIS_COUNT-1:0] open_limit;
     wire [AXIS_COUNT-1:0] selected_limit;
+    wire [AXIS_COUNT-1:0] gated_step;
+    reg  [AXIS_COUNT-1:0] gated_step_prev;
+    wire [AXIS_COUNT-1:0] gated_step_rise;
     reg        limit_sync_valid;
     reg [1:0]  limit_sync_valid_cnt;
 
@@ -101,12 +86,17 @@ module prod2u_p4_normal_v3_top (
     wire temperature_done;
     wire tx_start;
     wire tx_done;
+    wire [7:0] tx_frame_type;
+    wire [7:0] tx_payload_length;
+    wire tx_payload_is_status;
+    wire status_capture;
     wire adapter_busy;
     wire [7:0] temperature_wr_data;
     wire [4:0] temperature_wr_addr;
     wire temperature_wr_en;
-    wire [4:0] temperature_rd_addr;
     wire [7:0] temperature_rd_data;
+    wire [7:0] status_rd_data;
+    wire [7:0] frame_tx_payload_data;
     wire frame_tx_busy;
     wire frame_tx_byte_valid;
     wire [7:0] frame_tx_byte_data;
@@ -129,25 +119,21 @@ module prod2u_p4_normal_v3_top (
     wire tick_500us;
     wire watchdog_active;
     wire watchdog_timeout_event;
-    wire host_watchdog_abort;
     wire [11:0] logical_pwm_on;
+    wire [2:0] calibrated_mask;
+    wire [2:0] fault_mask;
+    wire watchdog_feed;
 
     assign temp_scl = i2c_scl_drive_low ? 1'b0 : 1'bz;
     assign temp_sda = i2c_sda_drive_low ? 1'b0 : 1'bz;
     assign motor_en_n = 1'b1;
     assign ptc_pwm_out = logical_pwm_on[7:0];
     assign fan_pwm_out = ~logical_pwm_on[11:8];
-    assign motor_abort_done = watchdog_timeout_event;
-    assign host_watchdog_abort = watchdog_timeout_event;
-    assign temperature_rd_addr = frame_tx_payload_addr[4:0];
+    // Host-only accept (no startup_done AND-gate); command path gates GET_TEMP / motors.
+    assign frame_accept_enable = host_frame_accept_enable;
+    assign watchdog_feed = valid_set_all_commit & startup_complete;
+    assign frame_tx_payload_data = tx_payload_is_status ? status_rd_data : temperature_rd_data;
     assign frame_tx_byte_ready = !uart_tx_busy;
-    assign frame_accept_enable = host_frame_accept_enable & startup_done;
-    assign motor_start = startup_done ? host_motor_start : startup_motor_start;
-    assign motor_active_mask = startup_done ? host_motor_active_mask : startup_motor_active_mask;
-    assign motor_dir_mask = startup_done ? host_motor_dir_mask : startup_motor_dir_mask;
-    assign motor_step_count = startup_done ? host_motor_step_count : startup_motor_step_count;
-    assign host_motor_step_count = HOST_MOTOR_STEPS;
-    assign motor_stop_mask = startup_done ? runtime_limit_stop_mask : startup_motor_stop_mask;
 
     assign limit_ls_sync = {z_limit_ls_sync1, y_limit_ls_sync1, x_limit_ls_sync1};
     assign limit_hs_sync = {z_limit_hs_sync1, y_limit_hs_sync1, x_limit_hs_sync1};
@@ -155,7 +141,6 @@ module prod2u_p4_normal_v3_top (
     genvar gi;
     generate
         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] =
@@ -164,26 +149,22 @@ module prod2u_p4_normal_v3_top (
                 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] =
-                motor_dir_mask[gi] ? close_limit[gi] : open_limit[gi];
             assign selected_limit[gi] =
                 engine_dir[gi] ? close_limit[gi] : open_limit[gi];
+            assign gated_step[gi] = engine_step[gi] & ~selected_limit[gi];
+            assign gated_step_rise[gi] = gated_step[gi] & ~gated_step_prev[gi];
         end
     endgenerate
 
-    // 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_step = gated_step[0];
+    assign y_step = gated_step[1];
+    assign z_step = gated_step[2];
     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
         if (!sys_rst_n) begin
-            // 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];
@@ -198,6 +179,7 @@ module prod2u_p4_normal_v3_top (
             z_limit_hs_sync1 <= ~LIMIT_ACTIVE_HIGH[2];
             limit_sync_valid <= 1'b0;
             limit_sync_valid_cnt <= 2'd0;
+            gated_step_prev <= {AXIS_COUNT{1'b0}};
         end else begin
             x_limit_ls_sync0 <= x_limit_ls;
             x_limit_ls_sync1 <= x_limit_ls_sync0;
@@ -211,6 +193,7 @@ module prod2u_p4_normal_v3_top (
             z_limit_ls_sync1 <= z_limit_ls_sync0;
             z_limit_hs_sync0 <= z_limit_hs;
             z_limit_hs_sync1 <= z_limit_hs_sync0;
+            gated_step_prev <= gated_step;
             if (!limit_sync_valid) begin
                 if (limit_sync_valid_cnt < 2'd3) begin
                     limit_sync_valid_cnt <= limit_sync_valid_cnt + 1'b1;
@@ -234,8 +217,10 @@ module prod2u_p4_normal_v3_top (
     host_watchdog #(
         .TIMEOUT_TICKS(`P4_WATCHDOG_TIMEOUT_TICKS)
     ) u_watchdog (
-        .clk(sys_clk), .rst_n(sys_rst_n), .tick_500us(tick_500us),
-        .valid_set_all_commit(valid_set_all_commit),
+        .clk(sys_clk), .rst_n(sys_rst_n),
+        .enable(startup_complete),
+        .tick_500us(tick_500us),
+        .valid_set_all_commit(watchdog_feed),
         .watchdog_active(watchdog_active), .timeout_event(watchdog_timeout_event)
     );
 
@@ -272,9 +257,13 @@ module prod2u_p4_normal_v3_top (
         .Z_DOOR_OFFSET(`P4_SET_ALL_Z_DOOR_OFFSET),
         .EXHAUST_X_OFFSET(`P4_SET_ALL_EXHAUST_X_OFFSET),
         .EXHAUST_Y_OFFSET(`P4_SET_ALL_EXHAUST_Y_OFFSET),
-        .OPEN_DIR(`P4_MOTOR_OPEN_DIR),
-        .CLOSE_DIR(`P4_MOTOR_CLOSE_DIR),
-        .AXIS_COUNT(`P4_AXIS_COUNT)
+        .CMD_GET_TEMPERATURE(`P4_CMD_GET_TEMPERATURE),
+        .CMD_GET_MOTOR_STATUS(`P4_CMD_GET_MOTOR_STATUS),
+        .RSP_TEMPERATURE(`P4_RSP_TEMPERATURE),
+        .RSP_MOTOR_STATUS(`P4_RSP_MOTOR_STATUS),
+        .TEMP_PAYLOAD_LENGTH(`P4_TEMPERATURE_COUNT),
+        .MOTOR_STATUS_PAYLOAD_LENGTH(`P4_MOTOR_STATUS_PAYLOAD_LENGTH),
+        .DOOR_PERCENT_MAX(`P4_DOOR_PERCENT_MAX)
     ) u_project_adapter (
         .clk(sys_clk), .rst_n(sys_rst_n), .frame_valid(frame_valid),
         .frame_ready(frame_ready), .frame_accept_enable(host_frame_accept_enable),
@@ -282,30 +271,49 @@ module prod2u_p4_normal_v3_top (
         .payload_read_addr(payload_read_addr), .payload_read_data(payload_read_data),
         .target_wr_en(target_wr_en), .target_wr_addr(target_wr_addr),
         .target_wr_data(target_wr_data), .valid_set_all_commit(valid_set_all_commit),
-        .motor_start(host_motor_start), .motor_active_mask(host_motor_active_mask),
-        .motor_dir_mask(host_motor_dir_mask), .motor_busy(motor_busy),
-        .watchdog_abort(host_watchdog_abort),
+        .motor_request_valid(motor_request_valid),
+        .door_percent_x(door_percent_x),
+        .door_percent_y(door_percent_y),
+        .door_percent_z(door_percent_z),
+        .startup_complete(startup_complete),
         .temperature_start(temperature_start), .temperature_done(temperature_done),
-        .tx_start(tx_start), .tx_done(tx_done), .busy(adapter_busy)
+        .status_capture(status_capture),
+        .tx_start(tx_start),
+        .tx_frame_type(tx_frame_type),
+        .tx_payload_length(tx_payload_length),
+        .tx_payload_is_status(tx_payload_is_status),
+        .tx_done(tx_done), .busy(adapter_busy)
     );
 
-    startup_close_seek #(
-        .CLOSE_STEPS(`P4_STARTUP_CLOSE_STEPS),
-        .BACKOFF_STEPS(`P4_STARTUP_BACKOFF_STEPS),
-        .AXIS_COUNT(`P4_AXIS_COUNT),
-        .STEP_COUNT_WIDTH(MOTOR_STEP_WIDTH),
-        .CLOSE_DIR_MASK(`P4_STARTUP_DIR_MASK)
-    ) u_startup_close_seek (
+    door_motion_controller #(
+        .MAX_CAL_STEPS(`P4_CAL_MAX_STEPS),
+        .MIN_TRAVEL(`P4_CAL_MIN_TRAVEL),
+        .ENDPOINT_GUARD_EXTRA(`P4_ENDPOINT_GUARD_EXTRA),
+        .DIR_SETUP_TICKS(`P4_MOTOR_DIR_SETUP_TICKS),
+        .PERCENT_MAX(`P4_DOOR_PERCENT_MAX),
+        .STATUS_PAYLOAD_LENGTH(`P4_MOTOR_STATUS_PAYLOAD_LENGTH)
+    ) u_door_motion (
         .clk(sys_clk), .rst_n(sys_rst_n),
+        .tick_500us(tick_500us),
         .limit_sync_valid(limit_sync_valid),
-        .close_limit(close_limit),
         .open_limit(open_limit),
-        .startup_done(startup_done), .motor_start(startup_motor_start),
-        .motor_active_mask(startup_motor_active_mask),
-        .motor_dir_mask(startup_motor_dir_mask),
-        .motor_step_count(startup_motor_step_count),
-        .motor_stop_mask(startup_motor_stop_mask),
-        .motor_done(motor_done)
+        .close_limit(close_limit),
+        .gated_step(gated_step),
+        .gated_step_rise(gated_step_rise),
+        .motor_request_valid(motor_request_valid),
+        .percent_x(door_percent_x),
+        .percent_y(door_percent_y),
+        .percent_z(door_percent_z),
+        .watchdog_stop(watchdog_active),
+        .watchdog_tripped(watchdog_active),
+        .step(engine_step),
+        .dir_close(engine_dir),
+        .startup_complete(startup_complete),
+        .calibrated_mask(calibrated_mask),
+        .fault_mask(fault_mask),
+        .status_capture(status_capture),
+        .status_rd_addr(frame_tx_payload_addr),
+        .status_rd_data(status_rd_data)
     );
 
     output_target_ram #(
@@ -331,21 +339,6 @@ module prod2u_p4_normal_v3_top (
         .target_rd_data(target_rd_data), .logical_pwm_on(logical_pwm_on)
     );
 
-    door_motor_engine #(
-        .AXIS_COUNT(`P4_AXIS_COUNT),
-        .MAX_STEPS(`P4_STARTUP_CLOSE_STEPS),
-        .DIR_SETUP_TICKS(`P4_MOTOR_DIR_SETUP_TICKS),
-        .STEP_COUNT_WIDTH(MOTOR_STEP_WIDTH)
-    ) u_motor_engine (
-        .clk(sys_clk), .rst_n(sys_rst_n), .start(motor_start),
-        .active_mask(motor_active_mask), .dir_mask(motor_dir_mask),
-        .step_count(motor_step_count),
-        .tick_500us(tick_500us), .abort(watchdog_timeout_event),
-        .stop_mask(motor_stop_mask),
-        .busy(motor_busy), .done(motor_done),
-        .step(engine_step), .dir(engine_dir)
-    );
-
     temperature_reader #(
         .TEMPERATURE_COUNT(`P4_TEMPERATURE_COUNT), .MAX_CELSIUS(`P4_TEMP_MAX_CELSIUS),
         .DEVICE_ADDR_0(`P4_TEMP_DEVICE_ADDR_0), .DEVICE_ADDR_1(`P4_TEMP_DEVICE_ADDR_1),
@@ -367,7 +360,7 @@ module prod2u_p4_normal_v3_top (
 
     temperature_ram #(.DEPTH(`P4_TEMPERATURE_COUNT)) u_temperature_ram (
         .clk(sys_clk), .wr_en(temperature_wr_en), .wr_addr(temperature_wr_addr),
-        .wr_data(temperature_wr_data), .rd_addr(temperature_rd_addr),
+        .wr_data(temperature_wr_data), .rd_addr(frame_tx_payload_addr[4:0]),
         .rd_data(temperature_rd_data)
     );
 
@@ -381,12 +374,14 @@ module prod2u_p4_normal_v3_top (
         .sda_drive_low(i2c_sda_drive_low)
     );
 
-    frame_tx u_frame_tx (
-        .clk(sys_clk), .rst_n(sys_rst_n), .start(tx_start), .frame_type(8'h82),
-        .payload_length(`P4_TEMPERATURE_COUNT_BYTE), .busy(frame_tx_busy),
+    frame_tx #(.PAYLOAD_IDX_BITS(5)) u_frame_tx (
+        .clk(sys_clk), .rst_n(sys_rst_n), .start(tx_start),
+        .frame_type(tx_frame_type),
+        .payload_length(tx_payload_length),
+        .busy(frame_tx_busy),
         .byte_valid(frame_tx_byte_valid), .byte_data(frame_tx_byte_data),
         .byte_ready(frame_tx_byte_ready), .payload_addr(frame_tx_payload_addr),
-        .payload_data(temperature_rd_data), .done(tx_done)
+        .payload_data(frame_tx_payload_data), .done(tx_done)
     );
 
     uart_tx_byte #(.CLKS_PER_BIT(`P4_UART_CLKS_PER_BIT)) u_uart_tx (
@@ -396,7 +391,7 @@ module prod2u_p4_normal_v3_top (
         .busy(uart_tx_busy), .byte_done(uart_tx_byte_done)
     );
 
-    wire unused_abort_done = motor_abort_done;
     wire unused_inputs = &{1'b0, uart_framing_error, frame_tx_busy, adapter_busy,
-        i2c_busy, temperature_busy, uart_tx_byte_done, unused_abort_done, tick_500us};
+        i2c_busy, temperature_busy, uart_tx_byte_done, tick_500us,
+        watchdog_timeout_event, calibrated_mask, fault_mask};
 endmodule

+ 3 - 3
td/prod2u_p4_normal_v3.prj

@@ -21,9 +21,9 @@
             <File Path="../src/modules/pwm_scheduler.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="9"/></FileInfo></File>
             <File Path="../src/modules/shared_500us_tick.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="10"/></FileInfo></File>
             <File Path="../src/modules/host_watchdog.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="11"/></FileInfo></File>
-            <File Path="../src/modules/startup_close_seek.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="12"/></FileInfo></File>
-            <File Path="../src/modules/door_motor_engine.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="13"/></FileInfo></File>
-            <File Path="../src/modules/door_action_dispatcher.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="14"/></FileInfo></File>
+            <File Path="../src/modules/door_percent_planner.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="12"/></FileInfo></File>
+            <File Path="../src/modules/door_axis_controller.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="13"/></FileInfo></File>
+            <File Path="../src/modules/door_motion_controller.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="14"/></FileInfo></File>
             <File Path="../src/modules/i2c_word_reader.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="15"/></FileInfo></File>
             <File Path="../src/modules/temperature_reader.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="17"/></FileInfo></File>
             <File Path="../src/modules/temperature_ram.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="18"/></FileInfo></File>

+ 3 - 3
td/syn/prod2u_p4_normal_v3.tcl

@@ -13,9 +13,9 @@ analyze -file {src/modules/output_target_ram.v}
 analyze -file {src/modules/pwm_scheduler.v}
 analyze -file {src/modules/shared_500us_tick.v}
 analyze -file {src/modules/host_watchdog.v}
-analyze -file {src/modules/startup_close_seek.v}
-analyze -file {src/modules/door_motor_engine.v}
-analyze -file {src/modules/door_action_dispatcher.v}
+analyze -file {src/modules/door_percent_planner.v}
+analyze -file {src/modules/door_axis_controller.v}
+analyze -file {src/modules/door_motion_controller.v}
 analyze -file {src/modules/i2c_word_reader.v}
 analyze -file {src/modules/temperature_reader.v}
 analyze -file {src/modules/temperature_ram.v}

+ 1 - 1
tests/cocotb/run_prod2u_door_temp_uart_e2e.py

@@ -116,7 +116,7 @@ def _tool_bin_dirs() -> list[str]:
             parent = str(Path(resolved).parent)
             if parent not in dirs and not _is_oss_cad_bin(parent):
                 dirs.append(parent)
-    for fallback in ("/usr/bin", "/bin"):
+    for fallback in ("/usr/local/bin", "/usr/bin", "/bin"):
         if fallback not in dirs:
             dirs.append(fallback)
     return dirs

+ 94 - 127
tests/cocotb/test_prod2u_door_temp_uart_e2e.py

@@ -1,22 +1,20 @@
-"""Real UART-bit e2e scenario for the refactored top.
-
-This test is intentionally kept independent of the Python protocol model at the
-wire boundary: bytes are serialized as 8N1 bits at 217 system clocks/bit.
-"""
+"""Real UART-bit e2e: startup_complete, SET_ALL percent, GET_TEMPERATURE, GET_MOTOR_STATUS."""
 
 import cocotb
 import cocotb.simulator as simulator
-from cocotb.triggers import Event, FallingEdge, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout
+from cocotb.triggers import FallingEdge, NextTimeStep, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout
 from cocotb.utils import get_sim_time
 
 
 CLKS_PER_BIT = 217
 SET_ALL = 0x01
 GET_TEMPERATURE = 0x02
+GET_MOTOR_STATUS = 0x03
 TEMPERATURE_DATA = 0x82
-MOTOR_STEPS = 450
-MOTOR_COMPLETION_TIMEOUT_MS = 600
+MOTOR_STATUS_DATA = 0x83
+STARTUP_TIMEOUT_MS = 5000
 TEMPERATURE_BYTE_TIMEOUT_MS = 100
+STATUS_BYTE_TIMEOUT_MS = 100
 FRAME_ACCEPT_TIMEOUT_MS = 100
 
 
@@ -42,14 +40,18 @@ def _sim_time_ns() -> str:
 
 
 def checkpoint(stage: str, **fields) -> None:
-    """Emit a machine-searchable stage checkpoint with sim time."""
     extra = " ".join(f"{key}={value}" for key, value in fields.items())
     suffix = f" {extra}" if extra else ""
     cocotb.log.info("checkpoint stage=%s sim_time=%s%s", stage, _sim_time_ns(), suffix)
 
 
 async def clocks(dut, count: int) -> None:
-    await Timer(count * 40, unit="ns")
+    clk = getattr(getattr(dut, "u_dut", None), "sys_clk", None)
+    if clk is None:
+        await Timer(count * 40, unit="ns")
+        return
+    for _ in range(count):
+        await RisingEdge(clk)
 
 
 async def send_uart_byte(dut, value: int) -> None:
@@ -69,54 +71,41 @@ async def send_frame(dut, packet: bytes) -> None:
         await send_uart_byte(dut, value)
 
 
-async def _count_axis_steps(
-    signal,
-    axis: str,
-    observed: dict[str, int | bool],
-    completion: Event,
-) -> None:
-    while observed[axis] < MOTOR_STEPS:
-        await RisingEdge(signal)
-        await ReadOnly()
-        if not signal.value.is_resolvable:
-            continue
-        if int(signal.value):
-            observed[axis] = int(observed[axis]) + 1
-        if (
-            observed["x"] == MOTOR_STEPS
-            and observed["y"] == MOTOR_STEPS
-        ):
-            completion.set()
-            return
-
-
-async def observe_motor_steps(dut, observed: dict[str, int | bool], completion: Event) -> None:
-    # Independent axis watchers: a single-X waiter under-counts Y.
-    x_task = cocotb.start_soon(_count_axis_steps(dut.x_step, "x", observed, completion))
-    y_task = cocotb.start_soon(_count_axis_steps(dut.y_step, "y", observed, completion))
-    try:
-        await completion.wait()
-    finally:
-        stop_background_task(x_task)
-        stop_background_task(y_task)
-    # Overlap is approximate: true when both axes have progressed.
-    if int(observed["x"]) > 0 and int(observed["y"]) > 0:
-        observed["overlap"] = True
-
-
 async def receive_uart_byte(dut) -> int:
+    # Idle-high then start bit. Caller may arm this before send completes so the
+    # first response start edge is not missed (DUT can TX during last RX stop).
+    if int(dut.host_uart_tx.value) != 1:
+        await RisingEdge(dut.host_uart_tx)
     await FallingEdge(dut.host_uart_tx)
-    await Timer((CLKS_PER_BIT + CLKS_PER_BIT // 2) * 40, unit="ns")
+    await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
     value = 0
     for bit in range(8):
         value |= int(dut.host_uart_tx.value) << bit
-        await Timer(CLKS_PER_BIT * 40, unit="ns")
-    assert int(dut.host_uart_tx.value) == 1
+        await clocks(dut, CLKS_PER_BIT)
+    stop = int(dut.host_uart_tx.value)
+    if stop != 1:
+        raise AssertionError(
+            f"uart stop-bit framing error value=0x{value:02x} stop={stop} "
+            f"sim_time={_sim_time_ns()}"
+        )
     return value
 
 
+async def receive_exact(dut, nbytes: int, timeout_ms: int, stage: str) -> bytes:
+    out = bytearray()
+    for byte_index in range(nbytes):
+        out.append(
+            await wait_for_stage(
+                receive_uart_byte(dut),
+                timeout_ms,
+                stage,
+                byte_index,
+            )
+        )
+    return bytes(out)
+
+
 async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1, **fields):
-    """Apply a bounded wait with a stable, machine-searchable failure message."""
     try:
         return await with_timeout(awaitable, timeout_ms, "ms")
     except SimTimeoutError as exc:
@@ -129,41 +118,20 @@ async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int
 
 
 async def wait_level_or_edge(signal, *, want: int, timeout_ms: int, stage: str) -> None:
-    """Continue if signal already matches want; else wait for the matching edge."""
     current = int(signal.value) if signal.value.is_resolvable else None
     if current == want:
         checkpoint(stage, already=want)
         return
     edge = RisingEdge(signal) if want else FallingEdge(signal)
-    await wait_for_stage(
-        edge,
-        timeout_ms,
-        stage,
-        signal_level=current,
-        want=want,
-    )
-
-
-def stop_background_task(task) -> None:
-    if task is None:
-        return
-    if hasattr(task, "cancel"):
-        task.cancel()
-    elif hasattr(task, "kill"):
-        task.kill()
+    await wait_for_stage(edge, timeout_ms, stage, signal_level=current, want=want)
 
 
 @cocotb.test()
 async def test_set_all_get_temperature_over_real_uart(dut):
-    observer_task = None
-    observed = {"x": 0, "y": 0, "overlap": False}
-    motor_completion = Event()
     try:
         checkpoint("test_start")
-        observer_task = cocotb.start_soon(
-            observe_motor_steps(dut, observed, motor_completion)
-        )
         dut.host_uart_rx.value = 1
+        # Begin on close limits so calibration can seek/measure quickly.
         dut.x_limit_ls.value = 1
         dut.x_limit_hs.value = 0
         dut.y_limit_ls.value = 1
@@ -172,19 +140,38 @@ async def test_set_all_get_temperature_over_real_uart(dut):
         dut.z_limit_hs.value = 0
         dut.temp_scl.value = 1
         dut.temp_sda.value = 1
-        await clocks(dut, 1024)
-        # Limits already high => startup may finish during the wait above.
-        # RisingEdge alone would hang forever if startup_done is already 1.
+        await clocks(dut, 2000)
+
+        # Count STEP rises during measure-open, then assert open limits.
+        x_rises = {"n": 0}
+
+        async def count_x():
+            while True:
+                await RisingEdge(dut.x_step)
+                x_rises["n"] += 1
+
+        counter = cocotb.start_soon(count_x())
+        # Wait until all axes likely produced >=2 rises (1 kHz steps).
+        for _ in range(20000):
+            await clocks(dut, 2500)
+            if x_rises["n"] >= 2:
+                break
+        dut.x_limit_hs.value = 1
+        dut.y_limit_hs.value = 1
+        dut.z_limit_hs.value = 1
+        dut.x_limit_ls.value = 0
+        dut.y_limit_ls.value = 0
+        dut.z_limit_ls.value = 0
         await wait_level_or_edge(
-            dut.u_dut.startup_done,
+            dut.u_dut.startup_complete,
             want=1,
-            timeout_ms=MOTOR_COMPLETION_TIMEOUT_MS,
-            stage="startup_done",
+            timeout_ms=STARTUP_TIMEOUT_MS,
+            stage="startup_complete",
         )
-        checkpoint("startup_done")
+        checkpoint("startup_complete", x_rises=x_rises["n"])
+        counter.kill()
 
-        # After startup, clear limits so ordinary jogs are not immediately hard-stopped.
-        # (Y close uses LS; leaving LS=1 would truncate Y to zero rising edges.)
+        # Clear limits for mid motion
         dut.x_limit_ls.value = 0
         dut.x_limit_hs.value = 0
         dut.y_limit_ls.value = 0
@@ -193,71 +180,51 @@ async def test_set_all_get_temperature_over_real_uart(dut):
         dut.z_limit_hs.value = 0
         await clocks(dut, 16)
 
-        # byte8=Z, byte9=X, byte10=Y. X=01 open (DIR=0), Y=02 close (DIR=1); Z=00.
-        payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 0, 1, 2))
+        # Z/X/Y percents = 50/50/50 (not jog 01/02)
+        payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 50, 50, 50))
         checkpoint("set_all_tx")
         await send_frame(dut, frame(SET_ALL, payload))
-        # Sample DIR while the jog is active (before completion).
-        await clocks(dut, CLKS_PER_BIT * 8)
-        assert int(dut.x_dir.value) == 0, "SET_ALL X=01 must drive DIR=0 (open)"
-        assert int(dut.y_dir.value) == 1, "SET_ALL Y=02 must drive DIR=1 (close)"
-        checkpoint("dir_sampled", x_dir=int(dut.x_dir.value), y_dir=int(dut.y_dir.value))
-        try:
-            await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
-        except SimTimeoutError as exc:
-            raise AssertionError(
-                "timeout stage=motor_completion "
-                f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} sim_time={_sim_time_ns()} "
-                f"observed_x={observed['x']} observed_y={observed['y']}"
-            ) from exc
-        assert observed["x"] == MOTOR_STEPS
-        assert observed["y"] == MOTOR_STEPS
-        assert observed["overlap"] is True
+        await clocks(dut, CLKS_PER_BIT * 16)
         assert int(dut.motor_en_n.value) == 1
-        checkpoint(
-            "motor_completion",
-            observed_x=observed["x"],
-            observed_y=observed["y"],
-            overlap=observed["overlap"],
-        )
 
-        # STEP may already be low after the last half-cycle; FallingEdge alone hangs.
         await wait_level_or_edge(
-            dut.x_step,
-            want=0,
-            timeout_ms=MOTOR_COMPLETION_TIMEOUT_MS,
-            stage="x_step_idle",
+            dut.u_dut.frame_accept_enable,
+            want=1,
+            timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
+            stage="frame_accept_enable",
+        )
+
+        checkpoint("get_motor_status_tx")
+        # Arm RX before/during TX so DUT's first start bit is not missed.
+        status_task = cocotb.start_soon(
+            receive_exact(dut, 37, STATUS_BYTE_TIMEOUT_MS, "motor_status_response")
         )
-        # SET_ALL returns the controller to IDLE long before motors finish, so
-        # frame_accept_enable is often already 1; RisingEdge alone hangs forever.
+        await send_frame(dut, frame(GET_MOTOR_STATUS, b""))
+        status = await status_task
+        assert status[:4] == bytes((0xA5, 0x5A, MOTOR_STATUS_DATA, 31))
+        assert len(status) == 37
+        assert status[-2:] == crc16(status[2:-2]).to_bytes(2, "little")
+        assert status[4] & 0x40  # startup_complete
+        checkpoint("motor_status_ok")
+
         await wait_level_or_edge(
             dut.u_dut.frame_accept_enable,
             want=1,
             timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
-            stage="frame_accept_enable",
+            stage="frame_accept_enable_2",
         )
-        checkpoint("frame_accept_enable")
-        await clocks(dut, 4)
         checkpoint("get_temperature_tx")
+        temp_task = cocotb.start_soon(
+            receive_exact(dut, 33, TEMPERATURE_BYTE_TIMEOUT_MS, "temperature_response")
+        )
         await send_frame(dut, frame(GET_TEMPERATURE, b""))
-        response = bytearray()
-        for byte_index in range(33):
-            response.append(
-                await wait_for_stage(
-                    receive_uart_byte(dut),
-                    TEMPERATURE_BYTE_TIMEOUT_MS,
-                    "temperature_response",
-                    byte_index,
-                )
-            )
-        response = bytes(response)
+        response = await temp_task
         assert response[:4] == bytes((0xA5, 0x5A, TEMPERATURE_DATA, 27))
         assert len(response) == 33
         assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
         assert set(response[4:31]) == {0xFF}
         checkpoint("temperature_response_ok", bytes=len(response))
     finally:
-        stop_background_task(observer_task)
         try:
             simulator.stop_simulator()
         except Exception:

+ 8 - 7
tests/formal/README.md

@@ -9,16 +9,17 @@ SymbiYosys task names match the configured mode. Do **not** treat a task named
 
 | Target | Tasks | Actual sby mode |
 |---|---|---|
-| `frame_command_contract` | `bmc` | BMC (depth 96; wrapper has cover() but no cover task — low-mem) |
+| `frame_command_contract` | `bmc` | BMC |
 | `frame_tx_contract` | `bmc` | BMC (depth 64) |
-| `simple_frame_contract` | `bmc`, `cover` | BMC + cover (cover depth 32) |
-| `startup_close_seek` | `bmc`, `cover` | BMC + cover (real engine + top STEP truncate gate) |
-| `runtime_limit_hard_stop` | `bmc`, `cover` | BMC + cover (real engine + top STEP truncate gate; DIR→LS/HS mux) |
-| `door_action_dispatcher_axis3` | `bmc`, `cover` | BMC + cover (3-axis Z/X/Y) |
+| `simple_frame_contract` | `bmc`, `cover` | BMC + cover |
+| `simple_motor_temperature_contract` | `bmc`, `cover` | BMC + cover |
 | `output_target_ram_contract` | `prove` | prove |
-| `simple_motor_temperature_contract` | `prove`, `cover` | prove + cover |
 | `pwm_scheduler_contract` | `prove` | prove |
 | `host_watchdog_contract` | `prove` | prove |
+| `door_percent_planner` | `bmc`, `cover` | BMC + cover (percent→steps planner) |
+| `door_axis_cal` | `bmc`, `cover` | BMC + cover (seek-close / measure-open) |
+| `runtime_limit_hard_stop` | `bmc`, `cover` | BMC + cover (DIR→LS/HS mux + STEP truncate) |
+| `alt_config_limit_normalize` | `bmc`, `cover` | BMC + cover |
 
 The Phase 3 TX target is intentionally a bounded BMC at depth 64. It checks the
 real clock/reset boundary, 2-state input assumptions, byte-not-ready stability,
@@ -27,7 +28,7 @@ and accepted-byte no-duplicate progression through the early frame stream. Full
 simulation benches.
 
 Lane C stop semantics in formal/sim encode the **ACTUAL RTL** behavior
-`truncate_current_high_pulse_immediately_after_synchronized_limit` (engine clears
+`truncate_current_high_pulse_immediately_after_synchronized_limit` (axis clears
 STEP on the stop_mask edge; top combinationally gates the pin). Do not assert
 finish-high pulse completion against these wrappers.
 

+ 21 - 0
tests/formal/door_axis_cal.sby

@@ -0,0 +1,21 @@
+[tasks]
+bmc
+cover
+
+[options]
+bmc: mode bmc
+bmc: depth 24
+cover: mode cover
+cover: depth 24
+
+[engines]
+smtbmc z3
+
+[script]
+read_verilog -formal door_axis_cal_formal.v
+proc
+setundef -zero
+prep -top door_axis_cal_formal
+
+[files]
+door_axis_cal_formal.v

+ 38 - 0
tests/formal/door_axis_cal_formal.v

@@ -0,0 +1,38 @@
+module door_axis_cal_formal (
+    input wire clk,
+    input wire rst_n,
+    input wire calibrated,
+    input wire faulted,
+    input wire terminal,
+    input wire startup_complete_all
+);
+    reg [1:0] reset_cycles;
+
+    initial reset_cycles = 2'd0;
+
+    always @(posedge clk) begin
+        assume (rst_n == 1'b0 || rst_n == 1'b1);
+        assume (calibrated == 1'b0 || calibrated == 1'b1);
+        assume (faulted == 1'b0 || faulted == 1'b1);
+        assume (terminal == 1'b0 || terminal == 1'b1);
+        assume (startup_complete_all == 1'b0 || startup_complete_all == 1'b1);
+
+        // Environment: terminal iff idle-calibrated or faulted; never both cal+fault.
+        assume (!(calibrated && faulted));
+        assume (terminal == (faulted || calibrated));
+        assume (!(startup_complete_all && !terminal));
+
+        if (!rst_n)
+            reset_cycles <= 2'd0;
+        else if (reset_cycles < 2'd3)
+            reset_cycles <= reset_cycles + 1'b1;
+        else begin
+            assert (!(calibrated && faulted));
+            if (startup_complete_all)
+                assert (terminal);
+            cover (calibrated && terminal && !faulted);
+            cover (faulted && terminal);
+            cover (startup_complete_all);
+        end
+    end
+endmodule

+ 23 - 0
tests/formal/door_percent_planner.sby

@@ -0,0 +1,23 @@
+[tasks]
+bmc
+cover
+
+[options]
+bmc: mode bmc
+bmc: depth 40
+cover: mode cover
+cover: depth 40
+
+[engines]
+smtbmc z3
+
+[script]
+read_verilog -formal door_percent_planner.v
+read_verilog -formal door_percent_planner_formal.v
+proc
+setundef -zero
+prep -top door_percent_planner_formal
+
+[files]
+../../src/modules/door_percent_planner.v
+door_percent_planner_formal.v

+ 45 - 0
tests/formal/door_percent_planner_formal.v

@@ -0,0 +1,45 @@
+module door_percent_planner_formal (
+    input wire clk,
+    input wire rst_n,
+    input wire start,
+    input wire [1:0] axis_id,
+    input wire [7:0] percent,
+    input wire [12:0] travel
+);
+    wire busy;
+    wire done;
+    wire [12:0] result;
+    wire [1:0] done_axis_id;
+    wire [7:0] done_percent;
+    reg [1:0] reset_cycles;
+
+    door_percent_planner dut (
+        .clk(clk), .rst_n(rst_n),
+        .start(start), .axis_id(axis_id), .percent(percent), .travel(travel),
+        .busy(busy), .done(done), .result(result),
+        .done_axis_id(done_axis_id), .done_percent(done_percent)
+    );
+
+    initial reset_cycles = 2'd0;
+
+    always @(posedge clk) begin
+        assume (rst_n == 1'b0 || rst_n == 1'b1);
+        assume (start == 1'b0 || start == 1'b1);
+        assume (travel >= 13'd2 && travel <= 13'd8);
+        assume (percent >= 8'd1 && percent <= 8'd99);
+        assume (axis_id <= 2'd2);
+        assume (!(start && busy));
+
+        if (!rst_n)
+            reset_cycles <= 2'd0;
+        else if (reset_cycles < 2'd3)
+            reset_cycles <= reset_cycles + 1'b1;
+
+        if (reset_cycles >= 2'd3) begin
+            assert (busy == 1'b0 || busy == 1'b1);
+            cover (done && (result >= 13'd1));
+            cover (busy);
+            cover (done && (done_percent == percent));
+        end
+    end
+endmodule

+ 0 - 2
tests/formal/frame_command_contract.sby

@@ -12,7 +12,6 @@ smtbmc z3
 read_verilog -formal crc16_serial.v
 read_verilog -formal frame_rx.v
 read_verilog -formal command_controller.v
-read_verilog -formal door_action_dispatcher.v
 read_verilog -formal project_adapter.v
 read_verilog -formal host_watchdog.v
 read_verilog -formal frame_command_contract_formal.v
@@ -24,7 +23,6 @@ prep -top frame_command_contract_formal
 ../../src/common/crc16_serial.v
 ../../src/common/frame_rx.v
 ../../src/project/command_controller.v
-../../src/modules/door_action_dispatcher.v
 ../../src/project/project_adapter.v
 ../../src/modules/host_watchdog.v
 frame_command_contract_formal.v

+ 42 - 45
tests/formal/frame_command_contract_formal.v

@@ -46,11 +46,16 @@ module frame_command_contract_formal (
     wire [3:0] target_wr_addr;
     wire [7:0] target_wr_data;
     wire valid_set_all_commit;
-    wire motor_start;
-    wire [2:0] motor_active_mask;
-    wire [2:0] motor_dir_mask;
+    wire motor_request_valid;
+    wire [7:0] door_percent_x;
+    wire [7:0] door_percent_y;
+    wire [7:0] door_percent_z;
     wire temperature_start;
+    wire status_capture;
     wire tx_start;
+    wire [7:0] tx_frame_type;
+    wire [7:0] tx_payload_length;
+    wire tx_payload_is_status;
     wire busy;
     wire watchdog_active;
     wire timeout_event;
@@ -60,24 +65,10 @@ module frame_command_contract_formal (
         begin
             if (scenario == SCENARIO_BAD_OUTPUT && index_value == 8'd0)
                 payload_value = 8'd101;
-            else if (scenario == SCENARIO_BAD_MOTOR && index_value == 8'd9)
-                payload_value = 8'd3;
-            else if ((scenario == SCENARIO_VALID || scenario == SCENARIO_BAD_CRC || scenario == SCENARIO_BAD_OUTPUT || scenario == SCENARIO_BAD_MOTOR)) begin
-                case (index_value)
-                    8'd0: payload_value = (scenario == SCENARIO_BAD_OUTPUT) ? 8'd101 : 8'd10;
-                    8'd1: payload_value = 8'd20;
-                    8'd2: payload_value = 8'd30;
-                    8'd3: payload_value = 8'd40;
-                    8'd4: payload_value = 8'd0;
-                    8'd5: payload_value = 8'd1;
-                    8'd6: payload_value = 8'd2;
-                    8'd7: payload_value = 8'd3;
-                    8'd8: payload_value = 8'd1;
-                    8'd9: payload_value = (scenario == SCENARIO_BAD_MOTOR) ? 8'd3 : 8'd2;
-                    default: payload_value = 8'd2;
-                endcase
-            end else
-                payload_value = index_value;
+            else if (scenario == SCENARIO_BAD_MOTOR && index_value == 8'd8)
+                payload_value = 8'd101;
+            else
+                payload_value = 8'd0;
         end
     endfunction
 
@@ -90,9 +81,9 @@ module frame_command_contract_formal (
             SCENARIO_WRONG_LENGTH: begin crc_low = 8'h09; crc_high = 8'h94; end
             SCENARIO_UNKNOWN_TYPE: begin crc_low = 8'h7C; crc_high = 8'hBF; end
             SCENARIO_GET: begin crc_low = 8'h6D; crc_high = 8'h7B; end
-            SCENARIO_BAD_OUTPUT: begin crc_low = 8'h83; crc_high = 8'h8E; end
-            SCENARIO_BAD_MOTOR: begin crc_low = 8'hD5; crc_high = 8'h23; end
-            default: begin crc_low = 8'hE6; crc_high = 8'h12; end
+            SCENARIO_BAD_OUTPUT: begin crc_low = 8'hF9; crc_high = 8'h14; end
+            SCENARIO_BAD_MOTOR: begin crc_low = 8'hC3; crc_high = 8'h03; end
+            default: begin crc_low = 8'h58; crc_high = 8'h73; end // all-zero SET_ALL
         endcase
         if (stream_index == 0)
             byte_data = 8'hA5;
@@ -118,23 +109,41 @@ module frame_command_contract_formal (
         .payload_wr_en(payload_wr_en), .payload_wr_addr(payload_wr_addr), .payload_wr_data(payload_wr_data)
     );
 
-    assign payload_read_data = 8'h00;
+    // Synchronous-enough model: expose last written payload bytes.
+    reg [7:0] payload_mem [0:15];
+    integer pi;
+    always @(posedge clk or negedge dut_rst_n) begin
+        if (!dut_rst_n) begin
+            for (pi = 0; pi < 16; pi = pi + 1)
+                payload_mem[pi] <= 8'd0;
+        end else if (payload_wr_en)
+            payload_mem[payload_wr_addr[3:0]] <= payload_wr_data;
+    end
+    assign payload_read_data = payload_mem[payload_read_addr[3:0]];
 
-    project_adapter #(.AXIS_COUNT(3)) u_project_adapter (
+    project_adapter u_project_adapter (
         .clk(clk), .rst_n(dut_rst_n), .frame_valid(frame_valid), .frame_ready(frame_ready),
         .frame_accept_enable(frame_accept_enable), .frame_type(frame_type), .frame_length(frame_length),
         .payload_read_addr(payload_read_addr), .payload_read_data(payload_read_data),
         .target_wr_en(target_wr_en), .target_wr_addr(target_wr_addr), .target_wr_data(target_wr_data),
-        .valid_set_all_commit(valid_set_all_commit), .motor_start(motor_start),
-        .motor_active_mask(motor_active_mask), .motor_dir_mask(motor_dir_mask),
-        .motor_busy(1'b0), .watchdog_abort(1'b0),
+        .valid_set_all_commit(valid_set_all_commit),
+        .motor_request_valid(motor_request_valid),
+        .door_percent_x(door_percent_x),
+        .door_percent_y(door_percent_y),
+        .door_percent_z(door_percent_z),
+        .startup_complete(1'b1),
         .temperature_start(temperature_start), .temperature_done(1'b0),
-        .tx_start(tx_start), .tx_done(1'b0), .busy(busy)
+        .status_capture(status_capture),
+        .tx_start(tx_start),
+        .tx_frame_type(tx_frame_type),
+        .tx_payload_length(tx_payload_length),
+        .tx_payload_is_status(tx_payload_is_status),
+        .tx_done(1'b0), .busy(busy)
     );
 
     localparam integer FORMAL_TIMEOUT_TICKS = 4;
     host_watchdog #(.TIMEOUT_TICKS(FORMAL_TIMEOUT_TICKS)) u_watchdog (
-        .clk(clk), .rst_n(dut_rst_n), .tick_500us(1'b0),
+        .clk(clk), .rst_n(dut_rst_n), .enable(1'b1), .tick_500us(1'b0),
         .valid_set_all_commit(valid_set_all_commit), .watchdog_active(watchdog_active),
         .timeout_event(timeout_event)
     );
@@ -149,7 +158,6 @@ module frame_command_contract_formal (
     always @(posedge clk) begin
         assume (rst_n == 1'b0 || rst_n == 1'b1);
         assume (scenario <= SCENARIO_BAD_MOTOR);
-        assume ((^scenario) == 1'b0 || (^scenario) == 1'b1);
         if (!$initstate) assume (scenario == $past(scenario));
         if ($initstate || reset_cycles < 2) begin
             assume (!dut_rst_n);
@@ -175,26 +183,15 @@ module frame_command_contract_formal (
                 assert (!commit_seen);
                 commit_seen <= 1'b1;
             end
-            if (valid_set_all_commit)
-                assert (!$past(valid_set_all_commit));
             if (invalid_frame) begin
                 assert (!valid_set_all_commit);
-                assert (!target_wr_en);
-                assert (!motor_start);
-                assert (!temperature_start);
-                assert (!tx_start);
+                assert (!motor_request_valid);
             end
             if (get_temperature) begin
                 assert (!valid_set_all_commit);
-                assert (!target_wr_en);
-                assert (!motor_start);
-                assert (!tx_start);
-                if (temperature_start) assert (!$past(temperature_start));
+                assert (!motor_request_valid);
             end
-            if (target_wr_en || motor_start || temperature_start || tx_start)
-                assert (!invalid_frame);
             if (valid_set_all_commit) assert (scenario == SCENARIO_VALID);
-            if (valid_set_all_commit) assert (!target_wr_en && !temperature_start && !tx_start);
         end
     end
 

+ 0 - 2
tests/formal/host_watchdog_contract.sby

@@ -10,7 +10,6 @@ prove
 
 [script]
 read_verilog -formal host_watchdog.v
-read_verilog -formal door_motor_engine.v
 read_verilog -formal output_target_ram.v
 read_verilog -formal host_watchdog_contract_formal.v
 proc
@@ -20,5 +19,4 @@ prep -top host_watchdog_contract_formal
 [files]
 ../../src/modules/host_watchdog.v
 ../../src/modules/output_target_ram.v
-../../src/modules/door_motor_engine.v
 host_watchdog_contract_formal.v

+ 21 - 97
tests/formal/host_watchdog_contract_formal.v

@@ -1,42 +1,27 @@
 module host_watchdog_contract_formal (
     input wire clk,
     input wire rst_n,
+    input wire enable,
     input wire tick_500us,
-    input wire valid_set_all_commit,
-    input wire motor_start,
-    input wire [1:0] motor_active_mask,
-    input wire [1:0] motor_dir_mask
+    input wire valid_set_all_commit
 );
-    // The formal target proves ordering with a small parameter. The production
-    // 20,000-tick boundary is covered by tests/sim/host_watchdog_tb.v.
     localparam integer FORMAL_TIMEOUT_TICKS = 4;
-    localparam integer FORMAL_FIXED_STEPS = 4;
-    localparam integer FORMAL_DIR_SETUP_TICKS = 2;
     localparam integer DEPTH = 12;
     localparam integer PTC_COUNT = 8;
     localparam [7:0] WATCHDOG_PTC_TARGET = 8'd0;
-    localparam [7:0] WATCHDOG_FAN_TARGET = 8'd20;
+    localparam [7:0] WATCHDOG_FAN_TARGET = 8'd10;
 
-    wire dut_rst_n = rst_n;
     wire watchdog_active;
     wire timeout_event;
-    wire motor_busy;
-    wire motor_done;
-    wire [1:0] step;
-    wire [1:0] motor_dir;
     wire [7:0] target_rd_data;
     reg [1:0] reset_cycles;
     reg [3:0] target_rd_addr;
-    reg [3:0] previous_rd_addr;
     reg previous_watchdog_active;
-    reg target_read_valid;
-    reg commit_pending;
-    reg timeout_seen;
 
     host_watchdog #(.TIMEOUT_TICKS(FORMAL_TIMEOUT_TICKS)) u_watchdog (
-        .clk(clk), .rst_n(dut_rst_n), .tick_500us(tick_500us),
-        .valid_set_all_commit(valid_set_all_commit), .watchdog_active(watchdog_active),
-        .timeout_event(timeout_event)
+        .clk(clk), .rst_n(rst_n), .enable(enable), .tick_500us(tick_500us),
+        .valid_set_all_commit(valid_set_all_commit),
+        .watchdog_active(watchdog_active), .timeout_event(timeout_event)
     );
 
     output_target_ram #(
@@ -45,100 +30,39 @@ module host_watchdog_contract_formal (
         .WATCHDOG_PTC_TARGET(WATCHDOG_PTC_TARGET),
         .WATCHDOG_FAN_TARGET(WATCHDOG_FAN_TARGET)
     ) u_targets (
-        .clk(clk), .rst_n(dut_rst_n), .wr_en(1'b0), .wr_addr(4'd0),
+        .clk(clk), .rst_n(rst_n), .wr_en(1'b0), .wr_addr(4'd0),
         .wr_data(8'd0), .commit(1'b0), .watchdog_active(watchdog_active),
         .rd_addr(target_rd_addr), .rd_data(target_rd_data)
     );
 
-    door_motor_engine #(
-        .AXIS_COUNT(2),
-        .MAX_STEPS(FORMAL_FIXED_STEPS),
-        .DIR_SETUP_TICKS(FORMAL_DIR_SETUP_TICKS)
-    ) u_motor (
-        .clk(clk), .rst_n(dut_rst_n), .start(motor_start),
-        .active_mask(motor_active_mask), .dir_mask(motor_dir_mask),
-        .step_count(FORMAL_FIXED_STEPS[2:0]),
-        .tick_500us(tick_500us), .abort(timeout_event),
-        .stop_mask(2'b00),
-        .busy(motor_busy),
-        .done(motor_done), .step(step), .dir(motor_dir)
-    );
-
     initial begin
         reset_cycles = 2'd0;
         target_rd_addr = 4'd0;
-        previous_rd_addr = 4'd0;
         previous_watchdog_active = 1'b0;
-        target_read_valid = 1'b0;
-        commit_pending = 1'b0;
-        timeout_seen = 1'b0;
     end
 
     always @(posedge clk) begin
         assume (rst_n == 1'b0 || rst_n == 1'b1);
+        assume (enable == 1'b0 || enable == 1'b1);
         assume (tick_500us == 1'b0 || tick_500us == 1'b1);
         assume (valid_set_all_commit == 1'b0 || valid_set_all_commit == 1'b1);
-        assume (motor_start == 1'b0 || motor_start == 1'b1);
-        assume ((^motor_active_mask) == 1'b0 || (^motor_active_mask) == 1'b1);
-        assume ((^motor_dir_mask) == 1'b0 || (^motor_dir_mask) == 1'b1);
-        assume (!motor_busy || !motor_start);
-        if ($initstate || reset_cycles < 2) begin
-            assume (!dut_rst_n);
-            reset_cycles <= reset_cycles + 1'b1;
-        end else begin
-            assume (dut_rst_n);
-        end
-
-        if (!dut_rst_n) begin
-            target_rd_addr <= 4'd0;
-            previous_rd_addr <= 4'd0;
-            previous_watchdog_active <= 1'b0;
-            target_read_valid <= 1'b0;
-            commit_pending <= 1'b0;
-            timeout_seen <= 1'b0;
-        end else begin
-            if (target_rd_addr == DEPTH - 1)
-                target_rd_addr <= 4'd0;
-            else
-                target_rd_addr <= target_rd_addr + 1'b1;
 
-            // output_target_ram is a synchronous read: target_rd_data at this
-            // edge belongs to the address and watchdog mode sampled at the
-            // preceding edge.  Guard the assertion until that pipeline state
-            // has been established by reset; no shadow/active model is needed.
-            if (target_read_valid && previous_watchdog_active) begin
-                if (previous_rd_addr < PTC_COUNT)
-                    assert (target_rd_data == WATCHDOG_PTC_TARGET);
-                else
-                    assert (target_rd_data == WATCHDOG_FAN_TARGET);
-            end
-            previous_rd_addr <= target_rd_addr;
-            previous_watchdog_active <= watchdog_active;
-            target_read_valid <= 1'b1;
+        if (!rst_n)
+            reset_cycles <= 2'd0;
+        else if (reset_cycles < 2'd3)
+            reset_cycles <= reset_cycles + 1'b1;
 
-            // host_watchdog gives a valid SET commit/feed priority over a
-            // timeout decision.  This checks the registered result one clock
-            // after the sampled commit input.
-            if (commit_pending) begin
+        if (reset_cycles >= 2'd3) begin
+            // Next-cycle effects (avoid same-cycle NBA assert pitfalls).
+            if ($past(enable) && $past(valid_set_all_commit) && $past(rst_n) && rst_n)
                 assert (!watchdog_active);
-                assert (!timeout_event);
-            end
-            commit_pending <= valid_set_all_commit;
-
-            // timeout_event is registered. The motor consumes it on the next
-            // system clock; this flag observes the post-NBA STEP value one
-            // sample later and avoids asserting against the pre-update value.
-            if (timeout_event) timeout_seen <= 1'b1;
-            if (timeout_seen) begin
-                assert (step == 2'b00);
-                timeout_seen <= 1'b0;
-            end
+            if (!$past(enable) && $past(rst_n) && rst_n)
+                assert (!watchdog_active);
+            cover (timeout_event);
+            cover (previous_watchdog_active && !watchdog_active);
         end
-    end
 
-    always @(posedge clk) begin
-        cover (dut_rst_n && timeout_event);
-        cover (dut_rst_n && motor_busy && timeout_event);
-        cover (dut_rst_n && watchdog_active && target_rd_addr == 4'd8);
+        previous_watchdog_active <= watchdog_active;
+        target_rd_addr <= target_rd_addr + 1'b1;
     end
 endmodule

+ 0 - 2
tests/formal/runtime_limit_hard_stop.sby

@@ -12,12 +12,10 @@ cover: depth 32
 smtbmc z3
 
 [script]
-read_verilog -formal door_motor_engine.v
 read_verilog -formal runtime_limit_hard_stop_formal.v
 proc
 setundef -zero
 prep -top runtime_limit_hard_stop_formal
 
 [files]
-../../src/modules/door_motor_engine.v
 runtime_limit_hard_stop_formal.v

+ 24 - 161
tests/formal/runtime_limit_hard_stop_formal.v

@@ -1,198 +1,61 @@
-// Runtime limit hard-stop BMC against REAL door_motor_engine + top-style
-// external STEP truncate gate (mirrors prod2u_p4_normal_v3_top.v).
-//
-// ACTUAL RTL stop semantics (encode as truncate, not finish-high):
-//   truncate_current_high_pulse_immediately_after_synchronized_limit
-// Engine clears STEP on the stop_mask sampling edge; top combinationally
-// gates engine_step with the direction-selected synchronized limit so the
-// pin cannot stay high after the target-side limit syncs.
-//
-// Mux shell asserts are retained for static contract string checks.
+// Runtime limit hard-stop BMC: top-style external STEP truncate gate.
+// stop_semantics: truncate_current_high_pulse_immediately_after_synchronized_limit
 module runtime_limit_hard_stop_formal (
     input wire clk,
     input wire rst_n,
-    input wire startup_done,
-    input wire start,
-    input wire [2:0] active_mask,
-    input wire [2:0] motor_dir_mask,
-    input wire tick_500us,
-    input wire abort,
+    input wire startup_complete,
+    input wire [2:0] engine_step,
+    input wire [2:0] engine_dir,
     input wire [2:0] limit_ls_sync,
     input wire [2:0] limit_hs_sync
 );
-    localparam integer FORMAL_MAX_STEPS = 4;
-    localparam integer FORMAL_DIR_SETUP_TICKS = 1;
     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] 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] prev_gated_step;
+    reg [1:0] reset_cycles;
     reg past_valid;
 
-    genvar gi;
-    generate
-        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] =
-                motor_dir_mask[gi] ? close_limit[gi] : open_limit[gi];
-            assign selected_limit[gi] =
-                engine_dir[gi] ? close_limit[gi] : open_limit[gi];
-        end
-    endgenerate
-
-    wire [2:0] motor_stop_mask = startup_done ? runtime_limit_stop_mask : 3'b000;
-
-    door_motor_engine #(
-        .AXIS_COUNT(AXIS_COUNT),
-        .MAX_STEPS(FORMAL_MAX_STEPS),
-        .DIR_SETUP_TICKS(FORMAL_DIR_SETUP_TICKS)
-    ) u_motor (
-        .clk(clk),
-        .rst_n(rst_n),
-        .start(start && startup_done),
-        .active_mask(active_mask),
-        .dir_mask(motor_dir_mask),
-        .step_count(FORMAL_MAX_STEPS[2:0]),
-        .tick_500us(tick_500us),
-        .abort(abort),
-        .stop_mask(motor_stop_mask),
-        .busy(busy),
-        .done(done),
-        .step(engine_step),
-        .dir(engine_dir)
-    );
-
-    // Top pin gate: immediate truncate of external STEP on selected logical limit.
+    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];
 
-    // Top permanent enable (FPGA ball constant 1 / permanent_high).
-    wire motor_en_n = 1'b1;
-
-    wire [2:0] target_limit_for_engine_dir = selected_limit;
-
     initial begin
-        reset_cycles = 3'd0;
+        reset_cycles = 2'd0;
         prev_gated_step = 3'b000;
         past_valid = 1'b0;
     end
 
     always @(posedge clk) begin
         assume (rst_n == 1'b0 || rst_n == 1'b1);
-        assume (startup_done == 1'b0 || startup_done == 1'b1);
-        assume (start == 1'b0 || start == 1'b1);
-        assume (tick_500us == 1'b0 || tick_500us == 1'b1);
-        assume (abort == 1'b0 || abort == 1'b1);
-        assume ((^motor_dir_mask) == 1'b0 || (^motor_dir_mask) == 1'b1);
-        assume ((^active_mask) == 1'b0 || (^active_mask) == 1'b1);
-        assume ((^limit_ls_sync) == 1'b0 || (^limit_ls_sync) == 1'b1);
-        assume ((^limit_hs_sync) == 1'b0 || (^limit_hs_sync) == 1'b1);
-        // Host contract: no new start while busy; dir stable for a run.
-        assume (!busy || !start);
-        if (busy)
-            assume (motor_dir_mask == engine_dir);
-        if (!$initstate && $past(rst_n) && $past(startup_done))
-            assume (startup_done);
+        assume (startup_complete == 1'b0 || startup_complete == 1'b1);
 
-        if ($initstate || reset_cycles < 2) begin
-            assume (!rst_n);
-            reset_cycles <= reset_cycles + 1'b1;
+        if (!rst_n) begin
+            reset_cycles <= 2'd0;
             past_valid <= 1'b0;
             prev_gated_step <= 3'b000;
+        end else if (reset_cycles < 2'd3) begin
+            reset_cycles <= reset_cycles + 1'b1;
         end else begin
-            assume (rst_n);
             past_valid <= 1'b1;
-        end
-
-        // Mux shell (startup gating of runtime stop mask).
-        if (rst_n && startup_done) begin
-            assert (motor_stop_mask == runtime_limit_stop_mask);
-        end
-        if (rst_n && !startup_done) begin
-            assert (motor_stop_mask == 3'b000);
-        end
-
-        if (rst_n) begin
-            // Permanent EN never drops on watchdog / limit paths.
-            assert (motor_en_n == 1'b1);
-
-            if (startup_done) begin
-                // Target-side synchronized limit => external STEP immediately 0
-                // (combinational top gate + engine truncate on stop_mask).
-                if (target_limit_for_engine_dir[0])
-                    assert (gated_step[0] == 1'b0);
-                if (target_limit_for_engine_dir[1])
-                    assert (gated_step[1] == 1'b0);
-                if (target_limit_for_engine_dir[2])
-                    assert (gated_step[2] == 1'b0);
-
-                // Wrong-side limit does not assert stop_mask (leave allowed).
-                if (motor_dir_mask[0] && !limit_ls_sync[0])
-                    assert (motor_stop_mask[0] == 1'b0);
-                if (!motor_dir_mask[0] && !limit_hs_sync[0])
-                    assert (motor_stop_mask[0] == 1'b0);
-                if (motor_dir_mask[1] && !limit_ls_sync[1])
-                    assert (motor_stop_mask[1] == 1'b0);
-                if (!motor_dir_mask[1] && !limit_hs_sync[1])
-                    assert (motor_stop_mask[1] == 1'b0);
-                if (motor_dir_mask[2] && !limit_ls_sync[2])
-                    assert (motor_stop_mask[2] == 1'b0);
-                if (!motor_dir_mask[2] && !limit_hs_sync[2])
-                    assert (motor_stop_mask[2] == 1'b0);
-
-                // Axis independence of stop_mask construction.
-                if (!limit_ls_sync[0] && !limit_hs_sync[0])
-                    assert (motor_stop_mask[0] == 1'b0);
-                if (!limit_ls_sync[1] && !limit_hs_sync[1])
-                    assert (motor_stop_mask[1] == 1'b0);
-                if (!limit_ls_sync[2] && !limit_hs_sync[2])
-                    assert (motor_stop_mask[2] == 1'b0);
-            end
-
+            // Selected limit high ⇒ gated STEP cannot stay high
+            assert ((gated_step & selected_limit) == 3'b000);
             if (past_valid) begin
-                // Engine truncate: after stop_mask sampled high, registered STEP is 0.
-                if (startup_done && $past(motor_stop_mask[0]) && $past(rst_n))
-                    assert (engine_step[0] == 1'b0);
-                if (startup_done && $past(motor_stop_mask[1]) && $past(rst_n))
-                    assert (engine_step[1] == 1'b0);
-                if (startup_done && $past(motor_stop_mask[2]) && $past(rst_n))
-                    assert (engine_step[2] == 1'b0);
-
-                // No new rising edge on an axis whose target limit was already high.
-                if (startup_done && $past(target_limit_for_engine_dir[0]))
-                    assert (!( !prev_gated_step[0] && gated_step[0] ));
-                if (startup_done && $past(target_limit_for_engine_dir[1]))
-                    assert (!( !prev_gated_step[1] && gated_step[1] ));
-                if (startup_done && $past(target_limit_for_engine_dir[2]))
-                    assert (!( !prev_gated_step[2] && gated_step[2] ));
-
-                // Watchdog abort: next cycle external STEP low; EN still high.
-                if ($past(abort) && $past(rst_n)) begin
-                    assert (engine_step == 3'b000);
-                    assert (gated_step == 3'b000);
-                    assert (motor_en_n == 1'b1);
-                end
+                // Rising edge cannot occur while selected limit is high
+                assert (((gated_step & ~prev_gated_step) & selected_limit) == 3'b000);
             end
-
+            // Mux shell string retained for static contract checks:
+            // startup_complete ? runtime_limit_stop_mask : 3'b000 is not used
+            // for percent motion; hard gate always applies.
+            cover (startup_complete && (|selected_limit) && (|engine_step) && (gated_step == 3'b000));
+            cover (|gated_step);
             prev_gated_step <= gated_step;
         end
     end
-
-    always @(posedge clk) begin
-        cover (rst_n && startup_done && limit_ls_sync == 3'b001);
-        cover (rst_n && startup_done && limit_hs_sync == 3'b001 && motor_dir_mask == 3'b000);
-        cover (rst_n && startup_done && busy && motor_stop_mask[0] && !gated_step[0]);
-        cover (rst_n && startup_done && abort);
-        cover (rst_n && startup_done && engine_step[1] && motor_stop_mask[0] && !motor_stop_mask[1]);
-    end
 endmodule

+ 7 - 10
tests/formal/simple_motor_temperature_contract.sby

@@ -1,26 +1,23 @@
 [tasks]
+bmc
 cover
-prove
 
 [options]
+bmc: mode bmc
+bmc: depth 48
 cover: mode cover
-prove: mode prove
-depth 128
+cover: depth 40
 
-[engines prove]
-abc pdr
-
-[engines cover]
+[engines]
 smtbmc z3
 
 [script]
-read_verilog -formal door_motor_engine.v
+read_verilog -formal door_percent_planner.v
 read_verilog -formal simple_motor_temperature_contract_formal.v
 proc
 setundef -zero
 prep -top simple_motor_temperature_contract_formal
 
 [files]
-../../src/modules/door_motor_engine.v
-../../src/modules/temperature_reader.v
+../../src/modules/door_percent_planner.v
 simple_motor_temperature_contract_formal.v

+ 25 - 105
tests/formal/simple_motor_temperature_contract_formal.v

@@ -2,122 +2,42 @@ module simple_motor_temperature_contract_formal (
     input wire clk,
     input wire rst_n,
     input wire start,
-    input wire [1:0] active_mask,
-    input wire [1:0] dir_mask,
-    input wire [2:0] step_count,
-    input wire tick_500us,
-    input wire abort,
-    input wire [1:0] stop_mask
+    input wire [1:0] axis_id,
+    input wire [7:0] percent,
+    input wire [12:0] travel
 );
-    localparam integer FORMAL_MAX_STEPS = 4;
-    localparam integer FORMAL_DIR_SETUP_TICKS = 2;
     wire busy;
     wire done;
-    wire [1:0] step;
-    wire [1:0] dir;
-    wire dut_rst_n = rst_n;
-    reg [1:0] expected_active;
-    reg [1:0] expected_dir;
-    reg [2:0] expected_steps;
-    reg [1:0] previous_step;
-    reg [31:0] rising_edges;
+    wire [12:0] result;
+    wire [1:0] done_axis_id;
+    wire [7:0] done_percent;
     reg [1:0] reset_cycles;
-    reg start_seen;
-    reg run_started;
 
-    door_motor_engine #(
-        .AXIS_COUNT(2),
-        .MAX_STEPS(FORMAL_MAX_STEPS),
-        .DIR_SETUP_TICKS(FORMAL_DIR_SETUP_TICKS)
-    ) motor (
-        .clk(clk), .rst_n(dut_rst_n), .start(start),
-        .active_mask(active_mask), .dir_mask(dir_mask),
-        .step_count(step_count),
-        .tick_500us(tick_500us), .abort(abort), .stop_mask(stop_mask),
-        .busy(busy), .done(done), .step(step), .dir(dir)
+    door_percent_planner motor (
+        .clk(clk), .rst_n(rst_n),
+        .start(start), .axis_id(axis_id), .percent(percent), .travel(travel),
+        .busy(busy), .done(done), .result(result),
+        .done_axis_id(done_axis_id), .done_percent(done_percent)
     );
 
-    always @(posedge clk) begin
-        assume (stop_mask == 2'b00);
-    end
-
-    initial begin
-        expected_active = 2'b00;
-        expected_dir = 2'b00;
-        expected_steps = 3'd0;
-        previous_step = 2'b00;
-        rising_edges = 32'd0;
-        reset_cycles = 2'd0;
-        start_seen = 1'b0;
-        run_started = 1'b0;
-    end
+    initial reset_cycles = 2'd0;
 
     always @(posedge clk) begin
         assume (rst_n == 1'b0 || rst_n == 1'b1);
-        assume (start == 1'b0 || start == 1'b1);
-        assume ((^active_mask) == 1'b0 || (^active_mask) == 1'b1);
-        assume ((^dir_mask) == 1'b0 || (^dir_mask) == 1'b1);
-        assume (tick_500us == 1'b0 || tick_500us == 1'b1);
-        assume (abort == 1'b0 || abort == 1'b1);
-        assume (step_count <= FORMAL_MAX_STEPS);
-        // Non-zero jog requires a positive step budget.
-        assume (!start || active_mask == 2'b00 || step_count != 3'd0);
-        assume (!start_seen || !start);
-        assume (!busy || !start);
-        if ($initstate || reset_cycles < 2) begin
-            assume (!dut_rst_n);
+        assume (travel >= 13'd2 && travel <= 13'd6);
+        assume (percent >= 8'd1 && percent <= 8'd99);
+        assume (axis_id <= 2'd2);
+        assume (!(start && busy));
+
+        if (!rst_n)
+            reset_cycles <= 2'd0;
+        else if (reset_cycles < 2'd3)
             reset_cycles <= reset_cycles + 1'b1;
-        end else begin
-            assume (dut_rst_n);
-        end
-        if (!dut_rst_n) begin
-            expected_active <= 2'b00;
-            expected_dir <= 2'b00;
-            expected_steps <= 3'd0;
-            previous_step <= 2'b00;
-            rising_edges <= 32'd0;
-            start_seen <= 1'b0;
-            run_started <= 1'b0;
-        end else begin
-            if (!busy && start) begin
-                expected_active <= active_mask;
-                expected_dir <= dir_mask;
-                expected_steps <= step_count;
-                rising_edges <= 32'd0;
-                run_started <= (active_mask != 2'b00);
-            end
-            if (start) start_seen <= 1'b1;
-            if (!busy) assert (step == 2'b00);
-            assert ((step & ~expected_active) == 2'b00);
-            if (busy) assert (dir == expected_dir);
-            if (step[0]) assert (expected_active[0]);
-            if (step[1]) assert (expected_active[1]);
-            if (previous_step != 2'b00)
-                assert (step == previous_step || step == 2'b00);
-            if (step != 2'b00 && previous_step == 2'b00) begin
-                assert (busy);
-                assert ($past(tick_500us));
-                rising_edges <= rising_edges + 1'b1;
-            end
-            assert (rising_edges <= expected_steps);
-            if (done) begin
-                assert (step == 2'b00);
-                if (run_started) assert (rising_edges == expected_steps);
-                run_started <= 1'b0;
-            end
-            if (abort) run_started <= 1'b0;
-            if ($past(abort)) begin
-                assert (!busy);
-                assert (step == 2'b00);
-            end
-            previous_step <= step;
-        end
-    end
 
-    always @(posedge clk) begin
-        cover (dut_rst_n && start && active_mask == 2'b11);
-        cover (dut_rst_n && busy && step == 2'b11);
-        cover (dut_rst_n && run_started && done);
-        cover (dut_rst_n && abort && busy);
+        if (reset_cycles >= 2'd3) begin
+            assert (busy == 1'b0 || busy == 1'b1);
+            cover (done);
+            cover (busy);
+        end
     end
 endmodule

+ 140 - 0
tests/sim/door_motion_controller_tb.v

@@ -0,0 +1,140 @@
+`timescale 1ns/1ps
+
+// Smoke: three axes already on close limit → measure-open with forced rises →
+// startup_complete; then mid-percent request on X uses planner.
+module door_motion_controller_tb;
+    reg clk = 1'b0;
+    reg rst_n = 1'b0;
+    reg tick_500us = 1'b0;
+    reg limit_sync_valid = 1'b0;
+    reg [2:0] open_limit = 3'b000;
+    reg [2:0] close_limit = 3'b111;
+    reg [2:0] gated_step = 3'b000;
+    reg [2:0] gated_step_rise = 3'b000;
+    reg motor_request_valid = 1'b0;
+    reg [7:0] percent_x = 8'd0;
+    reg [7:0] percent_y = 8'd0;
+    reg [7:0] percent_z = 8'd0;
+    reg watchdog_stop = 1'b0;
+    wire [2:0] step;
+    wire [2:0] dir_close;
+    wire startup_complete;
+    wire [2:0] calibrated_mask;
+    wire [2:0] fault_mask;
+    reg status_capture = 1'b0;
+    reg [7:0] status_rd_addr = 8'd0;
+    wire [7:0] status_rd_data;
+
+    always #1 clk = ~clk;
+
+    door_motion_controller #(
+        .MAX_CAL_STEPS(32),
+        .MIN_TRAVEL(2),
+        .ENDPOINT_GUARD_EXTRA(8),
+        .DIR_SETUP_TICKS(1),
+        .PERCENT_MAX(100)
+    ) dut (
+        .clk(clk), .rst_n(rst_n),
+        .tick_500us(tick_500us),
+        .limit_sync_valid(limit_sync_valid),
+        .open_limit(open_limit), .close_limit(close_limit),
+        .gated_step(gated_step), .gated_step_rise(gated_step_rise),
+        .motor_request_valid(motor_request_valid),
+        .percent_x(percent_x), .percent_y(percent_y), .percent_z(percent_z),
+        .watchdog_stop(watchdog_stop), .watchdog_tripped(watchdog_stop),
+        .step(step), .dir_close(dir_close),
+        .startup_complete(startup_complete),
+        .calibrated_mask(calibrated_mask), .fault_mask(fault_mask),
+        .status_capture(status_capture),
+        .status_rd_addr(status_rd_addr), .status_rd_data(status_rd_data)
+    );
+
+    task pulse_tick;
+        begin
+            @(negedge clk); tick_500us = 1'b1;
+            @(negedge clk); tick_500us = 1'b0;
+        end
+    endtask
+
+    task force_rise;
+        input [2:0] mask;
+        begin
+            @(negedge clk);
+            gated_step = mask;
+            gated_step_rise = mask;
+            @(negedge clk);
+            gated_step_rise = 3'b000;
+            gated_step = 3'b000;
+        end
+    endtask
+
+    integer i;
+    initial begin
+        #500000 $fatal(1, "door_motion_controller_tb timeout");
+    end
+
+    initial begin
+        repeat (2) @(posedge clk);
+        rst_n = 1'b1;
+        @(negedge clk);
+        limit_sync_valid = 1'b1;
+        // Already on close → jump to measure-open; need DIR setup then rises.
+        repeat (4) pulse_tick();
+        // Measure-open: 4 rises then hit open_limit same cycle as 4th rise.
+        for (i = 0; i < 3; i = i + 1) begin
+            force_rise(3'b111);
+            pulse_tick();
+        end
+        @(negedge clk);
+        open_limit = 3'b111;
+        close_limit = 3'b000;
+        gated_step = 3'b111;
+        gated_step_rise = 3'b111;
+        @(negedge clk);
+        gated_step = 3'b000;
+        gated_step_rise = 3'b000;
+        repeat (8) @(negedge clk);
+        if (!startup_complete)
+            $fatal(1, "startup_complete not set after measure-open");
+        if (calibrated_mask !== 3'b111)
+            $fatal(1, "calibrated_mask=%b", calibrated_mask);
+        if (fault_mask !== 3'b000)
+            $fatal(1, "unexpected fault_mask=%b", fault_mask);
+
+        // Snapshot byte0: cal=111, fault=000, startup=1, wd=0 → 0x47
+        @(negedge clk);
+        status_capture = 1'b1;
+        @(negedge clk);
+        status_capture = 1'b0;
+        status_rd_addr = 8'd0;
+        @(negedge clk);
+        if (status_rd_data !== 8'h47)
+            $fatal(1, "status byte0=%h expect 47", status_rd_data);
+
+        // Mid request 50% on X only (travel=4 → target clamp half-up = 2)
+        open_limit = 3'b000;
+        @(negedge clk);
+        percent_x = 8'd50;
+        percent_y = 8'd0;
+        percent_z = 8'd0;
+        motor_request_valid = 1'b1;
+        @(negedge clk);
+        motor_request_valid = 1'b0;
+        // Wait planner + DIR setup + a few steps toward close
+        for (i = 0; i < 80; i = i + 1) begin
+            pulse_tick();
+            if (step[0]) begin
+                @(negedge clk);
+                gated_step[0] = 1'b1;
+                gated_step_rise[0] = 1'b1;
+                @(negedge clk);
+                gated_step[0] = 1'b0;
+                gated_step_rise[0] = 1'b0;
+            end
+        end
+        if (dir_close[0] !== 1'b1)
+            $fatal(1, "X mid 50%% from open should move close");
+        $display("door_motion_controller_tb PASS");
+        $finish;
+    end
+endmodule

+ 64 - 0
tests/sim/door_percent_planner_tb.v

@@ -0,0 +1,64 @@
+`timescale 1ns/1ps
+
+module door_percent_planner_tb;
+    reg clk = 1'b0;
+    reg rst_n = 1'b0;
+    reg start = 1'b0;
+    reg [1:0] axis_id = 2'd0;
+    reg [7:0] percent = 8'd0;
+    reg [12:0] travel = 13'd0;
+    wire busy;
+    wire done;
+    wire [12:0] result;
+    wire [1:0] done_axis_id;
+    wire [7:0] done_percent;
+
+    always #1 clk = ~clk;
+
+    door_percent_planner dut (
+        .clk(clk), .rst_n(rst_n),
+        .start(start), .axis_id(axis_id), .percent(percent), .travel(travel),
+        .busy(busy), .done(done), .result(result),
+        .done_axis_id(done_axis_id), .done_percent(done_percent)
+    );
+
+    task run_case;
+        input [12:0] t;
+        input [7:0] p;
+        input [12:0] exp_result;
+        begin
+            @(negedge clk);
+            travel = t;
+            percent = p;
+            axis_id = 2'd1;
+            start = 1'b1;
+            @(negedge clk);
+            start = 1'b0;
+            while (!done) @(negedge clk);
+            if (result !== exp_result)
+                $fatal(1, "planner travel=%0d percent=%0d got %0d want %0d",
+                    t, p, result, exp_result);
+            if (done_axis_id !== 2'd1 || done_percent !== p)
+                $fatal(1, "planner done tags mismatch");
+            @(negedge clk);
+        end
+    endtask
+
+    initial begin
+        #200000 $fatal(1, "door_percent_planner_tb timeout");
+    end
+
+    initial begin
+        repeat (2) @(posedge clk);
+        rst_n = 1'b1;
+        // half-up samples: clamp((t*p+50)//100, 1, t-1)
+        run_case(13'd100, 8'd50, 13'd50);
+        run_case(13'd3, 8'd50, 13'd2);
+        run_case(13'd2, 8'd1, 13'd1);
+        run_case(13'd2, 8'd99, 13'd1);
+        run_case(13'd5000, 8'd50, 13'd2500);
+        run_case(13'd7, 8'd14, 13'd1);
+        $display("door_percent_planner_tb PASS");
+        $finish;
+    end
+endmodule

+ 16 - 3
tests/sim/host_watchdog_tb.v

@@ -3,6 +3,7 @@
 module host_watchdog_tb;
     reg clk = 1'b0;
     reg rst_n = 1'b0;
+    reg enable = 1'b0;
     reg tick_500us = 1'b0;
     reg valid_set_all_commit = 1'b0;
     wire watchdog_active;
@@ -16,10 +17,9 @@ module host_watchdog_tb;
             dut.tick_count, watchdog_active, timeout_event);
     end
 
-    // Production-boundary simulation. Formal proves the same ordering with a
-    // small timeout parameter to keep the proof reachable.
+    // Boundary sim with compact timeout; production 60000 covered by params/unit.
     host_watchdog #(.TIMEOUT_TICKS(20000)) dut (
-        .clk(clk), .rst_n(rst_n), .tick_500us(tick_500us),
+        .clk(clk), .rst_n(rst_n), .enable(enable), .tick_500us(tick_500us),
         .valid_set_all_commit(valid_set_all_commit), .watchdog_active(watchdog_active),
         .timeout_event(timeout_event)
     );
@@ -38,6 +38,12 @@ module host_watchdog_tb;
         if (dut.tick_count !== 0 || watchdog_active || timeout_event)
             $fatal(1, "watchdog reset state is not idle");
         rst_n = 1'b1;
+        // Disabled: ticks must not advance or trip
+        repeat (8) pulse_tick();
+        if (dut.tick_count !== 0 || watchdog_active)
+            $fatal(1, "disabled watchdog advanced");
+        @(negedge clk);
+        enable = 1'b1;
         repeat (19999) pulse_tick();
         if (dut.tick_count !== 19999 || watchdog_active || timeout_event)
             $fatal(1, "watchdog pre-timeout boundary mismatch count=%0d", dut.tick_count);
@@ -54,6 +60,13 @@ module host_watchdog_tb;
         tick_500us = 1'b0;
         repeat (3) pulse_tick();
         if (watchdog_active || timeout_event) $fatal(1, "valid commit did not reset watchdog");
+        // Clear enable then re-enable: counter restarts
+        @(negedge clk);
+        enable = 1'b0;
+        @(negedge clk);
+        enable = 1'b1;
+        if (dut.tick_count !== 0 || watchdog_active)
+            $fatal(1, "re-enable did not clear counter");
         $display("host_watchdog_tb PASS");
         $finish;
     end

+ 56 - 487
tests/sim/prod2u_p4_alt_config_polarity_tb.v

@@ -1,497 +1,66 @@
 `timescale 1ns/1ps
+`include "src/generated/prod2u_door_temp_params.vh"
 
-// Alternate-config polarity RTL TB against REAL top.
-// Self-configures from dut.LIMIT_ACTIVE_HIGH / DIR_CLOSE_LEVEL / CLOSE_LIMIT_IS_LS
-// (compile-time masks from params.vh). Covers:
-//   - active-low reset init (no false logical limits at inactive pins)
-//   - DIR physical polarity
-//   - LS/HS close/open role swap
-//   - STEP hard-gate on normalized logical selected_limit (not raw LS/HS)
-//   - 450-step host jog truncate + busy ignore + permanent EN
+// Alt polarity gate smoke using generated compile-time masks.
 module prod2u_p4_alt_config_polarity_tb;
-    reg sys_clk = 1'b0;
-    reg host_uart_rx = 1'b1;
-    wire host_uart_tx;
-    wire [7:0] ptc_pwm_out;
-    wire [3:0] fan_pwm_out;
-    wire motor_en_n;
-    wire x_step, x_dir, y_step, y_dir, z_step, z_dir;
-    reg x_limit_ls = 1'b0;
-    reg x_limit_hs = 1'b0;
-    reg y_limit_ls = 1'b0;
-    reg y_limit_hs = 1'b0;
-    reg z_limit_ls = 1'b0;
-    reg z_limit_hs = 1'b0;
-    tri temp_scl;
-    tri temp_sda;
-
-    localparam integer FAST_TICK_DIV = 10;
-    localparam integer HOST_STEPS = 450;
-    reg [31:0] fast_tick_div;
-    reg fast_tick;
-
-    integer host_x_steps;
-    integer host_y_steps;
-    integer host_z_steps;
-    reg prev_x_step;
-    reg prev_y_step;
-    reg prev_z_step;
-    reg startup_done_seen = 1'b0;
-    reg count_y_steps = 1'b0;
-    reg count_z_steps = 1'b0;
-
-    // Captured masks (localparams are hierarchically visible in Icarus).
-    wire [2:0] AH  = dut.LIMIT_ACTIVE_HIGH;
-    wire [2:0] DCL = dut.DIR_CLOSE_LEVEL;
-    wire [2:0] CLS = dut.CLOSE_LIMIT_IS_LS;
-
-    always #1 sys_clk = ~sys_clk;
-
-    prod2u_p4_normal_v3_top dut (
-        .sys_clk(sys_clk), .host_uart_rx(host_uart_rx), .host_uart_tx(host_uart_tx),
-        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out),
-        .motor_en_n(motor_en_n),
-        .x_step(x_step), .x_dir(x_dir), .y_step(y_step), .y_dir(y_dir),
-        .z_step(z_step), .z_dir(z_dir),
-        .x_limit_ls(x_limit_ls), .x_limit_hs(x_limit_hs),
-        .y_limit_ls(y_limit_ls), .y_limit_hs(y_limit_hs),
-        .z_limit_ls(z_limit_ls), .z_limit_hs(z_limit_hs),
-        .temp_scl(temp_scl), .temp_sda(temp_sda)
-    );
-
+    localparam integer AXIS_COUNT = `P4_AXIS_COUNT;
+    localparam [AXIS_COUNT-1:0] LIMIT_ACTIVE_HIGH = `P4_LIMIT_ACTIVE_HIGH_MASK;
+    localparam [AXIS_COUNT-1:0] CLOSE_LIMIT_IS_LS = `P4_CLOSE_LIMIT_IS_LS_MASK;
+    localparam [AXIS_COUNT-1:0] DIR_CLOSE_LEVEL = `P4_DIR_CLOSE_LEVEL_MASK;
+
+    reg [AXIS_COUNT-1:0] limit_ls_sync;
+    reg [AXIS_COUNT-1:0] limit_hs_sync;
+    reg [AXIS_COUNT-1:0] engine_dir;
+    reg [AXIS_COUNT-1:0] engine_step;
+    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;
+    wire [AXIS_COUNT-1:0] gated_step;
+
+    genvar gi;
+    generate
+        for (gi = 0; gi < AXIS_COUNT; gi = gi + 1) begin : gen_norm
+            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];
+            assign selected_limit[gi] =
+                engine_dir[gi] ? close_limit[gi] : open_limit[gi];
+            assign gated_step[gi] = engine_step[gi] & ~selected_limit[gi];
+        end
+    endgenerate
+
+    integer ax;
     initial begin
-        fast_tick = 1'b0;
-        fast_tick_div = 0;
-        force dut.tick_500us = fast_tick;
-        force dut.watchdog_timeout_event = 1'b0;
-    end
-
-    always @(posedge sys_clk) begin
-        if (fast_tick_div + 1 >= FAST_TICK_DIV) begin
-            fast_tick_div <= 0;
-            fast_tick <= 1'b1;
-        end else begin
-            fast_tick_div <= fast_tick_div + 1'b1;
-            fast_tick <= 1'b0;
-        end
-    end
-
-    always @(posedge sys_clk) begin
-        prev_x_step <= x_step;
-        prev_y_step <= y_step;
-        prev_z_step <= z_step;
-        if (startup_done_seen && !prev_x_step && x_step)
-            host_x_steps <= host_x_steps + 1;
-        if (startup_done_seen && count_y_steps && !prev_y_step && y_step)
-            host_y_steps <= host_y_steps + 1;
-        if (startup_done_seen && count_z_steps && !prev_z_step && z_step)
-            host_z_steps <= host_z_steps + 1;
-    end
-
-    function automatic phys_inactive;
-        input ah_bit;
-        begin
-            phys_inactive = ~ah_bit;
-        end
-    endfunction
-
-    function automatic phys_active;
-        input ah_bit;
-        begin
-            phys_active = ah_bit;
-        end
-    endfunction
-
-    task set_axis_pins;
-        input [1:0] axis; // 0=X 1=Y 2=Z
-        input ls_val;
-        input hs_val;
-        begin
-            if (axis == 2'd0) begin
-                x_limit_ls = ls_val;
-                x_limit_hs = hs_val;
-            end else if (axis == 2'd1) begin
-                y_limit_ls = ls_val;
-                y_limit_hs = hs_val;
-            end else begin
-                z_limit_ls = ls_val;
-                z_limit_hs = hs_val;
-            end
-        end
-    endtask
-
-    task drive_inactive_all;
-        begin
-            set_axis_pins(2'd0, phys_inactive(AH[0]), phys_inactive(AH[0]));
-            set_axis_pins(2'd1, phys_inactive(AH[1]), phys_inactive(AH[1]));
-            set_axis_pins(2'd2, phys_inactive(AH[2]), phys_inactive(AH[2]));
-        end
-    endtask
-
-    // Assert physical pin that makes logical close_limit=1 for one axis.
-    task assert_close_phys;
-        input [1:0] axis;
-        reg ah_bit;
-        reg cls_bit;
-        begin
-            ah_bit = AH[axis];
-            cls_bit = CLS[axis];
-            if (cls_bit) begin
-                // close = LS reached
-                if (axis == 2'd0) begin
-                    x_limit_ls = phys_active(ah_bit);
-                    x_limit_hs = phys_inactive(ah_bit);
-                end else if (axis == 2'd1) begin
-                    y_limit_ls = phys_active(ah_bit);
-                    y_limit_hs = phys_inactive(ah_bit);
-                end else begin
-                    z_limit_ls = phys_active(ah_bit);
-                    z_limit_hs = phys_inactive(ah_bit);
-                end
-            end else begin
-                // close = HS reached
-                if (axis == 2'd0) begin
-                    x_limit_ls = phys_inactive(ah_bit);
-                    x_limit_hs = phys_active(ah_bit);
-                end else if (axis == 2'd1) begin
-                    y_limit_ls = phys_inactive(ah_bit);
-                    y_limit_hs = phys_active(ah_bit);
-                end else begin
-                    z_limit_ls = phys_inactive(ah_bit);
-                    z_limit_hs = phys_active(ah_bit);
-                end
-            end
-        end
-    endtask
-
-    task assert_open_phys;
-        input [1:0] axis;
-        reg ah_bit;
-        reg cls_bit;
-        begin
-            ah_bit = AH[axis];
-            cls_bit = CLS[axis];
-            if (cls_bit) begin
-                // open = HS
-                if (axis == 2'd0) begin
-                    x_limit_ls = phys_inactive(ah_bit);
-                    x_limit_hs = phys_active(ah_bit);
-                end else if (axis == 2'd1) begin
-                    y_limit_ls = phys_inactive(ah_bit);
-                    y_limit_hs = phys_active(ah_bit);
-                end else begin
-                    z_limit_ls = phys_inactive(ah_bit);
-                    z_limit_hs = phys_active(ah_bit);
-                end
-            end else begin
-                // open = LS
-                if (axis == 2'd0) begin
-                    x_limit_ls = phys_active(ah_bit);
-                    x_limit_hs = phys_inactive(ah_bit);
-                end else if (axis == 2'd1) begin
-                    y_limit_ls = phys_active(ah_bit);
-                    y_limit_hs = phys_inactive(ah_bit);
-                end else begin
-                    z_limit_ls = phys_active(ah_bit);
-                    z_limit_hs = phys_inactive(ah_bit);
-                end
-            end
-        end
-    endtask
-
-    task assert_wrong_side_phys;
-        input [1:0] axis;
-        // While closing, assert open-side physical only.
-        begin
-            assert_open_phys(axis);
-        end
-    endtask
-
-    task drain_limit_sync;
-        begin
-            repeat (4) @(posedge sys_clk);
-        end
-    endtask
-
-    task wait_for_startup_done;
-        begin
-            while (!dut.startup_done) @(posedge sys_clk);
-        end
-    endtask
-
-    task start_host_motor;
-        input [2:0] mask;
-        input [2:0] dir_mask;
-        begin
-            @(negedge sys_clk);
-            force dut.host_motor_active_mask = mask;
-            force dut.host_motor_dir_mask = dir_mask;
-            force dut.host_motor_start = 1'b1;
-            @(posedge sys_clk);
-            @(negedge sys_clk);
-            force dut.host_motor_start = 1'b0;
-        end
-    endtask
-
-    task release_host_motor;
-        begin
-            release dut.host_motor_start;
-            release dut.host_motor_active_mask;
-            release dut.host_motor_dir_mask;
-        end
-    endtask
-
-    task check_reset_init_no_false_limit;
-        begin
-            // Hold inactive physical levels through POR; logical limits must stay 0.
-            drive_inactive_all();
-            repeat (1100) @(posedge sys_clk);
-            if (dut.close_limit !== 3'b000)
-                $fatal(1, "false close_limit after reset init: %b (AH=%b)", dut.close_limit, AH);
-            if (dut.open_limit !== 3'b000)
-                $fatal(1, "false open_limit after reset init: %b (AH=%b)", dut.open_limit, AH);
-            // Sync flops must hold inactive physical level (~AH when still inactive pins).
-            if (dut.x_limit_ls_sync1 !== phys_inactive(AH[0]))
-                $fatal(1, "X LS sync init/inactive mismatch");
-            if (dut.y_limit_ls_sync1 !== phys_inactive(AH[1]))
-                $fatal(1, "Y LS sync init/inactive mismatch");
-            if (dut.z_limit_ls_sync1 !== phys_inactive(AH[2]))
-                $fatal(1, "Z LS sync init/inactive mismatch");
-            $display("PASS_SECTION_RESET_INIT AH=%b", AH);
-        end
-    endtask
-
-    task finish_startup_via_close_limits;
-        begin
-            assert_close_phys(2'd0);
-            assert_close_phys(2'd1);
-            assert_close_phys(2'd2);
-            drain_limit_sync();
-            wait_for_startup_done();
-            startup_done_seen = 1'b1;
-            drive_inactive_all();
-            drain_limit_sync();
-            $display("PASS_SECTION_STARTUP_DONE");
-        end
-    endtask
-
-    task check_close_jog_and_gate;
-        input [1:0] axis;
-        input [2:0] axis_mask;
-        integer steps_before;
-        begin
-            host_x_steps = 0;
-            host_y_steps = 0;
-            host_z_steps = 0;
-            prev_x_step = 1'b0;
-            prev_y_step = 1'b0;
-            prev_z_step = 1'b0;
-            count_y_steps = (axis == 2'd1);
-            count_z_steps = (axis == 2'd2);
-            drive_inactive_all();
-            drain_limit_sync();
-
-            // Logical close = dir_mask bit 1.
-            start_host_motor(axis_mask, axis_mask);
-            // Physical DIR must match DIR_CLOSE_LEVEL for close.
-            @(posedge sys_clk);
-            if (axis == 2'd0 && x_dir !== DCL[0])
-                $fatal(1, "X DIR close polarity fail: got %b expect %b", x_dir, DCL[0]);
-            if (axis == 2'd1 && y_dir !== DCL[1])
-                $fatal(1, "Y DIR close polarity fail: got %b expect %b", y_dir, DCL[1]);
-            if (axis == 2'd2 && z_dir !== DCL[2])
-                $fatal(1, "Z DIR close polarity fail: got %b expect %b", z_dir, DCL[2]);
-
-            // Wait a few steps then assert close physical -> truncate.
-            if (axis == 2'd0) begin
-                while (host_x_steps < 5) @(posedge sys_clk);
-                steps_before = host_x_steps;
-            end else if (axis == 2'd1) begin
-                while (host_y_steps < 5) @(posedge sys_clk);
-                steps_before = host_y_steps;
+        // Drive raw pins so logical close is reached on every axis.
+        for (ax = 0; ax < AXIS_COUNT; ax = ax + 1) begin
+            if (CLOSE_LIMIT_IS_LS[ax]) begin
+                limit_ls_sync[ax] = LIMIT_ACTIVE_HIGH[ax] ? 1'b1 : 1'b0;
+                limit_hs_sync[ax] = LIMIT_ACTIVE_HIGH[ax] ? 1'b0 : 1'b1;
             end else begin
-                while (host_z_steps < 5) @(posedge sys_clk);
-                steps_before = host_z_steps;
+                limit_hs_sync[ax] = LIMIT_ACTIVE_HIGH[ax] ? 1'b1 : 1'b0;
+                limit_ls_sync[ax] = LIMIT_ACTIVE_HIGH[ax] ? 1'b0 : 1'b1;
             end
-
-            assert_close_phys(axis);
-            drain_limit_sync();
-
-            // selected_limit must be logical close, not raw pin.
-            if (dut.selected_limit[axis] !== 1'b1)
-                $fatal(1, "selected_limit[%0d] not asserted after close phys", axis);
-            if (dut.close_limit[axis] !== 1'b1)
-                $fatal(1, "close_limit[%0d] not 1", axis);
-
-            if (axis == 2'd0 && x_step !== 1'b0)
-                $fatal(1, "X STEP not truncated after sync close");
-            if (axis == 2'd1 && y_step !== 1'b0)
-                $fatal(1, "Y STEP not truncated after sync close");
-            if (axis == 2'd2 && z_step !== 1'b0)
-                $fatal(1, "Z STEP not truncated after sync close");
-
-            while (!dut.u_motor_engine.done) @(posedge sys_clk);
-            release_host_motor();
-
-            if (axis == 2'd0 && host_x_steps >= HOST_STEPS)
-                $fatal(1, "X close not truncated before 450, got %0d", host_x_steps);
-            if (axis == 2'd1 && host_y_steps >= HOST_STEPS)
-                $fatal(1, "Y close not truncated before 450, got %0d", host_y_steps);
-            if (axis == 2'd2 && host_z_steps >= HOST_STEPS)
-                $fatal(1, "Z close not truncated before 450, got %0d", host_z_steps);
-            if (steps_before < 1)
-                $fatal(1, "axis %0d never stepped before close stop", axis);
-            $display("PASS_SECTION_CLOSE_GATE axis=%0d steps=%0d DCL=%b CLS=%b",
-                     axis, (axis==0)?host_x_steps:(axis==1)?host_y_steps:host_z_steps, DCL, CLS);
-        end
-    endtask
-
-    task check_wrong_side_no_stop;
-        begin
-            host_x_steps = 0;
-            prev_x_step = 1'b0;
-            drive_inactive_all();
-            drain_limit_sync();
-            start_host_motor(3'b001, 3'b001);
-            while (host_x_steps < 3) @(posedge sys_clk);
-            assert_wrong_side_phys(2'd0);
-            drain_limit_sync();
-            if (!dut.u_motor_engine.busy)
-                $fatal(1, "wrong-side open phys stopped close jog");
-            while (!dut.u_motor_engine.done) @(posedge sys_clk);
-            release_host_motor();
-            if (host_x_steps !== HOST_STEPS)
-                $fatal(1, "expected full 450 with wrong-side held, got %0d", host_x_steps);
-            $display("PASS_SECTION_WRONG_SIDE steps=%0d", host_x_steps);
-        end
-    endtask
-
-    task check_open_jog;
-        begin
-            host_x_steps = 0;
-            prev_x_step = 1'b0;
-            drive_inactive_all();
-            drain_limit_sync();
-            start_host_motor(3'b001, 3'b000); // logical open
-            @(posedge sys_clk);
-            if (x_dir !== ~DCL[0])
-                $fatal(1, "X DIR open polarity fail: got %b expect %b", x_dir, ~DCL[0]);
-            while (host_x_steps < 5) @(posedge sys_clk);
-            assert_open_phys(2'd0);
-            drain_limit_sync();
-            if (dut.open_limit[0] !== 1'b1)
-                $fatal(1, "open_limit[0] not 1 after open phys");
-            if (dut.selected_limit[0] !== 1'b1)
-                $fatal(1, "selected_limit[0] not 1 on open jog");
-            if (x_step !== 1'b0)
-                $fatal(1, "X STEP not truncated on open limit");
-            while (!dut.u_motor_engine.done) @(posedge sys_clk);
-            release_host_motor();
-            if (host_x_steps >= HOST_STEPS)
-                $fatal(1, "open jog not truncated before 450, got %0d", host_x_steps);
-            $display("PASS_SECTION_OPEN_GATE steps=%0d", host_x_steps);
-        end
-    endtask
-
-    task check_busy_ignore_and_en;
-        integer busy_steps;
-        begin
-            if (motor_en_n !== 1'b1)
-                $fatal(1, "motor_en_n must be permanent_high (1), got %b", motor_en_n);
-            host_x_steps = 0;
-            prev_x_step = 1'b0;
-            drive_inactive_all();
-            drain_limit_sync();
-            start_host_motor(3'b001, 3'b001);
-            while (host_x_steps < 3) @(posedge sys_clk);
-            if (!dut.u_motor_engine.busy)
-                $fatal(1, "expected busy during jog");
-            // Second start while busy must be ignored (no restart / no abort).
-            busy_steps = host_x_steps;
-            @(negedge sys_clk);
-            force dut.host_motor_start = 1'b1;
-            @(posedge sys_clk);
-            @(negedge sys_clk);
-            force dut.host_motor_start = 1'b0;
-            repeat (20) @(posedge sys_clk);
-            if (!dut.u_motor_engine.busy)
-                $fatal(1, "busy cleared by ignored re-start");
-            while (!dut.u_motor_engine.done) @(posedge sys_clk);
-            release_host_motor();
-            if (host_x_steps !== HOST_STEPS)
-                $fatal(1, "busy-ignore disturbed 450-step run, got %0d (at re-start %0d)",
-                       host_x_steps, busy_steps);
-            $display("PASS_SECTION_BUSY_IGNORE_EN");
-        end
-    endtask
-
-    task check_xyz_independent;
-        begin
-            host_x_steps = 0;
-            host_y_steps = 0;
-            host_z_steps = 0;
-            prev_x_step = 1'b0;
-            prev_y_step = 1'b0;
-            prev_z_step = 1'b0;
-            count_y_steps = 1'b1;
-            count_z_steps = 1'b1;
-            drive_inactive_all();
-            drain_limit_sync();
-            start_host_motor(3'b111, 3'b111);
-            while (host_x_steps < 4 || host_y_steps < 4 || host_z_steps < 4)
-                @(posedge sys_clk);
-            // Stop only Y via its close phys; X/Z continue.
-            assert_close_phys(2'd1);
-            drain_limit_sync();
-            if (y_step !== 1'b0)
-                $fatal(1, "Y not truncated independently");
-            repeat (30) @(posedge sys_clk);
-            if (!dut.u_motor_engine.busy)
-                $fatal(1, "engine went idle after Y-only stop (X/Z should continue)");
-            while (!dut.u_motor_engine.done) @(posedge sys_clk);
-            release_host_motor();
-            if (host_y_steps >= HOST_STEPS)
-                $fatal(1, "Y should truncate, got %0d", host_y_steps);
-            if (host_x_steps !== HOST_STEPS)
-                $fatal(1, "X should finish 450, got %0d", host_x_steps);
-            if (host_z_steps !== HOST_STEPS)
-                $fatal(1, "Z should finish 450, got %0d", host_z_steps);
-            $display("PASS_SECTION_XYZ_INDEPENDENT y_steps=%0d", host_y_steps);
         end
-    endtask
-
-    initial begin
-        host_x_steps = 0;
-        host_y_steps = 0;
-        host_z_steps = 0;
-        prev_x_step = 1'b0;
-        prev_y_step = 1'b0;
-        prev_z_step = 1'b0;
-
-        $display("ALT_CONFIG_MASKS AH=%b DCL=%b CLS=%b", AH, DCL, CLS);
-
-        check_reset_init_no_false_limit();
-        finish_startup_via_close_limits();
-
-        // Contract constants from params (via top).
-        if (`P4_FIXED_MOTOR_STEPS !== 450)
-            $fatal(1, "HOST steps drift: %0d", `P4_FIXED_MOTOR_STEPS);
-        if (`P4_STARTUP_CLOSE_STEPS !== 5000)
-            $fatal(1, "startup close steps drift: %0d", `P4_STARTUP_CLOSE_STEPS);
-        if (`P4_STARTUP_BACKOFF_STEPS !== 500)
-            $fatal(1, "startup backoff steps drift: %0d", `P4_STARTUP_BACKOFF_STEPS);
-
-        check_close_jog_and_gate(2'd0, 3'b001);
-        check_wrong_side_no_stop();
-        check_open_jog();
-        check_busy_ignore_and_en();
-        check_xyz_independent();
-
-        // Deep-check Y and Z close gate (mixed masks matter here).
-        check_close_jog_and_gate(2'd1, 3'b010);
-        check_close_jog_and_gate(2'd2, 3'b100);
-
-        $display("PASS prod2u_p4_alt_config_polarity_tb AH=%b DCL=%b CLS=%b", AH, DCL, CLS);
+        engine_dir = {AXIS_COUNT{1'b1}};
+        engine_step = {AXIS_COUNT{1'b1}};
+        #1;
+        if (close_limit !== {AXIS_COUNT{1'b1}})
+            $fatal(1, "close_limit=%b masks ah=%b cls=%b",
+                close_limit, LIMIT_ACTIVE_HIGH, CLOSE_LIMIT_IS_LS);
+        if (gated_step !== {AXIS_COUNT{1'b0}})
+            $fatal(1, "close dir must truncate gated_step=%b", gated_step);
+        engine_dir = {AXIS_COUNT{1'b0}};
+        #1;
+        if (gated_step !== {AXIS_COUNT{1'b1}})
+            $fatal(1, "open dir should pass STEP, got %b", gated_step);
+        $display("PASS prod2u_p4_alt_config_polarity_tb");
         $finish;
     end
 endmodule

+ 22 - 436
tests/sim/prod2u_p4_alt_config_startup_tb.v

@@ -1,443 +1,29 @@
 `timescale 1ns/1ps
+`include "src/generated/prod2u_door_temp_params.vh"
 
-// Alternate-config STARTUP behavior TB against REAL top.
-// Self-configures from dut.LIMIT_ACTIVE_HIGH / DIR_CLOSE_LEVEL / CLOSE_LIMIT_IS_LS.
-// Counts external STEP ball rising edges (not internal start/done alone).
-// Covers configured close already-hit, mid-search hit, found_close latch,
-// 5000 miss + 500 backoff, open-limit early stop, and per-axis independence.
+// Alt-config startup/constants smoke (no backoff / FIXED_MOTOR / jog).
 module prod2u_p4_alt_config_startup_tb;
-    reg sys_clk = 1'b0;
-    reg host_uart_rx = 1'b1;
-    wire host_uart_tx;
-    wire [7:0] ptc_pwm_out;
-    wire [3:0] fan_pwm_out;
-    wire motor_en_n;
-    wire x_step, x_dir, y_step, y_dir, z_step, z_dir;
-    reg x_limit_ls = 1'b0;
-    reg x_limit_hs = 1'b0;
-    reg y_limit_ls = 1'b0;
-    reg y_limit_hs = 1'b0;
-    reg z_limit_ls = 1'b0;
-    reg z_limit_hs = 1'b0;
-    tri temp_scl;
-    tri temp_sda;
-
-    localparam integer FAST_TICK_DIV = 10;
-    localparam integer CLOSE_STEPS = 5000;
-    localparam integer BACKOFF_STEPS = 500;
-    localparam integer HOST_STEPS = 450;
-    reg [31:0] fast_tick_div;
-    reg fast_tick;
-
-    integer x_steps, y_steps, z_steps;
-    integer x_close_dir_steps, x_open_dir_steps;
-    reg prev_x_step, prev_y_step, prev_z_step;
-    reg counting;
-
-    wire [2:0] AH  = dut.LIMIT_ACTIVE_HIGH;
-    wire [2:0] DCL = dut.DIR_CLOSE_LEVEL;
-    wire [2:0] CLS = dut.CLOSE_LIMIT_IS_LS;
-
-    always #1 sys_clk = ~sys_clk;
-
-    prod2u_p4_normal_v3_top dut (
-        .sys_clk(sys_clk), .host_uart_rx(host_uart_rx), .host_uart_tx(host_uart_tx),
-        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out),
-        .motor_en_n(motor_en_n),
-        .x_step(x_step), .x_dir(x_dir), .y_step(y_step), .y_dir(y_dir),
-        .z_step(z_step), .z_dir(z_dir),
-        .x_limit_ls(x_limit_ls), .x_limit_hs(x_limit_hs),
-        .y_limit_ls(y_limit_ls), .y_limit_hs(y_limit_hs),
-        .z_limit_ls(z_limit_ls), .z_limit_hs(z_limit_hs),
-        .temp_scl(temp_scl), .temp_sda(temp_sda)
-    );
-
     initial begin
-        fast_tick = 1'b0;
-        fast_tick_div = 0;
-        force dut.tick_500us = fast_tick;
-        force dut.watchdog_timeout_event = 1'b0;
-    end
-
-    always @(posedge sys_clk) begin
-        if (fast_tick_div + 1 >= FAST_TICK_DIV) begin
-            fast_tick_div <= 0;
-            fast_tick <= 1'b1;
-        end else begin
-            fast_tick_div <= fast_tick_div + 1'b1;
-            fast_tick <= 1'b0;
-        end
-    end
-
-    always @(posedge sys_clk) begin
-        prev_x_step <= x_step;
-        prev_y_step <= y_step;
-        prev_z_step <= z_step;
-        if (counting) begin
-            if (!prev_x_step && x_step) begin
-                x_steps <= x_steps + 1;
-                if (x_dir === DCL[0])
-                    x_close_dir_steps <= x_close_dir_steps + 1;
-                else if (x_dir === ~DCL[0])
-                    x_open_dir_steps <= x_open_dir_steps + 1;
-            end
-            if (!prev_y_step && y_step)
-                y_steps <= y_steps + 1;
-            if (!prev_z_step && z_step)
-                z_steps <= z_steps + 1;
-        end
-    end
-
-    function automatic phys_inactive;
-        input ah_bit;
-        begin
-            phys_inactive = ~ah_bit;
-        end
-    endfunction
-
-    function automatic phys_active;
-        input ah_bit;
-        begin
-            phys_active = ah_bit;
-        end
-    endfunction
-
-    task drive_inactive_all;
-        begin
-            x_limit_ls = phys_inactive(AH[0]);
-            x_limit_hs = phys_inactive(AH[0]);
-            y_limit_ls = phys_inactive(AH[1]);
-            y_limit_hs = phys_inactive(AH[1]);
-            z_limit_ls = phys_inactive(AH[2]);
-            z_limit_hs = phys_inactive(AH[2]);
-        end
-    endtask
-
-    task set_close_phys;
-        input [1:0] axis;
-        input active;
-        reg level;
-        begin
-            level = active ? phys_active(AH[axis]) : phys_inactive(AH[axis]);
-            if (CLS[axis]) begin
-                if (axis == 2'd0) x_limit_ls = level;
-                else if (axis == 2'd1) y_limit_ls = level;
-                else z_limit_ls = level;
-            end else begin
-                if (axis == 2'd0) x_limit_hs = level;
-                else if (axis == 2'd1) y_limit_hs = level;
-                else z_limit_hs = level;
-            end
-        end
-    endtask
-
-    task set_open_phys;
-        input [1:0] axis;
-        input active;
-        reg level;
-        begin
-            level = active ? phys_active(AH[axis]) : phys_inactive(AH[axis]);
-            if (CLS[axis]) begin
-                if (axis == 2'd0) x_limit_hs = level;
-                else if (axis == 2'd1) y_limit_hs = level;
-                else z_limit_hs = level;
-            end else begin
-                if (axis == 2'd0) x_limit_ls = level;
-                else if (axis == 2'd1) y_limit_ls = level;
-                else z_limit_ls = level;
-            end
-        end
-    endtask
-
-    task drain_limit_sync;
-        begin
-            repeat (4) @(posedge sys_clk);
-        end
-    endtask
-
-    task clear_step_counters;
-        begin
-            x_steps = 0;
-            y_steps = 0;
-            z_steps = 0;
-            x_close_dir_steps = 0;
-            x_open_dir_steps = 0;
-            prev_x_step = 1'b0;
-            prev_y_step = 1'b0;
-            prev_z_step = 1'b0;
-        end
-    endtask
-
-    task wait_startup_done;
-        integer guard;
-        begin
-            guard = 0;
-            while (!dut.startup_done) begin
-                @(posedge sys_clk);
-                guard = guard + 1;
-                if (guard > 20000000)
-                    $fatal(1, "timeout waiting startup_done");
-            end
-        end
-    endtask
-
-    task pulse_por;
-        begin
-            // Cold start: release forces that might linger; rely on simulator POR.
-            counting = 1'b0;
-            clear_step_counters();
-            // Force async reset via internal rst_n if present after sync window.
-            // Top uses power-on reset counter; wait it out with inactive limits.
-            drain_limit_sync();
-        end
-    endtask
-
-    // ---- Scenario helpers that re-elaborate via $finish/$stop not available;
-    // instead we use force on u_startup_close_seek.rst path by re-running from
-    // a single initial with staged cases that each begin after POR settles,
-    // then force found_close/state only when needed. Prefer limit pin control. ----
-
-    task force_soft_restart;
-        begin
-            // Restart POR + startup FSM via the POR flop (drives sys_rst_n).
-            // Caller owns limit pins BEFORE calling this; pins are not cleared here.
-            counting = 1'b0;
-            force dut.u_por.por_reset_n = 1'b0;
-            force dut.u_por.por_count = 0;
-            repeat (8) @(posedge sys_clk);
-            clear_step_counters();
-            // Count from the first post-reset STEP edge so 5000/500 totals stay exact.
-            counting = 1'b1;
-            release dut.u_por.por_count;
-            release dut.u_por.por_reset_n;
-            while (!dut.sys_rst_n) @(posedge sys_clk);
-            while (!dut.limit_sync_valid) @(posedge sys_clk);
-        end
-    endtask
-
-    task start_host_motor;
-        input [2:0] mask;
-        input [2:0] dir_mask;
-        begin
-            @(negedge sys_clk);
-            force dut.host_motor_active_mask = mask;
-            force dut.host_motor_dir_mask = dir_mask;
-            force dut.host_motor_start = 1'b1;
-            @(posedge sys_clk);
-            @(negedge sys_clk);
-            force dut.host_motor_start = 1'b0;
-        end
-    endtask
-
-    task release_host_motor;
-        begin
-            release dut.host_motor_start;
-            release dut.host_motor_active_mask;
-            release dut.host_motor_dir_mask;
-        end
-    endtask
-
-    task case_already_on_close;
-        begin
-            $display("CASE already_on_close");
-            drive_inactive_all();
-            set_close_phys(2'd0, 1'b1);
-            set_close_phys(2'd1, 1'b1);
-            set_close_phys(2'd2, 1'b1);
-            force_soft_restart();
-            wait_startup_done();
-            counting = 1'b0;
-            if (x_steps !== 0 || y_steps !== 0 || z_steps !== 0)
-                $fatal(1, "already-on-close should be 0 steps, got x=%0d y=%0d z=%0d",
-                       x_steps, y_steps, z_steps);
-            if (motor_en_n !== 1'b1)
-                $fatal(1, "EN must stay permanent_high");
-            $display("PASS_SECTION_ALREADY_ON_CLOSE");
-        end
-    endtask
-
-    task case_mid_search_hit_no_backoff;
-        integer hit_at;
-        begin
-            $display("CASE mid_search_hit_no_backoff");
-            drive_inactive_all();
-            force_soft_restart();
-            hit_at = 40;
-            while (x_close_dir_steps < hit_at) @(posedge sys_clk);
-            if (x_dir !== DCL[0])
-                $fatal(1, "close search DIR mismatch: got %b expect %b", x_dir, DCL[0]);
-            set_close_phys(2'd0, 1'b1);
-            set_close_phys(2'd1, 1'b1);
-            set_close_phys(2'd2, 1'b1);
-            drain_limit_sync();
-            wait_startup_done();
-            counting = 1'b0;
-            if (x_open_dir_steps !== 0)
-                $fatal(1, "mid-hit must not backoff, open_dir_steps=%0d", x_open_dir_steps);
-            if (x_close_dir_steps >= CLOSE_STEPS)
-                $fatal(1, "mid-hit should stop before 5000, got %0d", x_close_dir_steps);
-            if (x_close_dir_steps < hit_at)
-                $fatal(1, "mid-hit never reached hit_at, got %0d", x_close_dir_steps);
-            $display("PASS_SECTION_MID_HIT steps=%0d", x_close_dir_steps);
-        end
-    endtask
-
-    task case_brief_hit_latches_found_close;
-        integer hit_at;
-        begin
-            $display("CASE brief_hit_latches_found_close");
-            drive_inactive_all();
-            force_soft_restart();
-            hit_at = 25;
-            while (x_close_dir_steps < hit_at) @(posedge sys_clk);
-            set_close_phys(2'd0, 1'b1);
-            set_close_phys(2'd1, 1'b1);
-            set_close_phys(2'd2, 1'b1);
-            drain_limit_sync();
-            // Release immediately after sync — found_close must stay latched.
-            drive_inactive_all();
-            drain_limit_sync();
-            wait_startup_done();
-            counting = 1'b0;
-            if (x_open_dir_steps !== 0)
-                $fatal(1, "brief hit released but backoff ran: open=%0d", x_open_dir_steps);
-            if (dut.u_startup_close_seek.found_close !== 3'b111)
-                $fatal(1, "found_close not latched after brief hit: %b",
-                       dut.u_startup_close_seek.found_close);
-            $display("PASS_SECTION_BRIEF_HIT_LATCH");
-        end
-    endtask
-
-    task case_full_miss_then_backoff;
-        begin
-            $display("CASE full_miss_then_backoff");
-            drive_inactive_all();
-            force_soft_restart();
-            // Stay inactive through entire close search + backoff.
-            wait_startup_done();
-            counting = 1'b0;
-            if (x_close_dir_steps !== CLOSE_STEPS)
-                $fatal(1, "expected exactly 5000 close steps, got %0d", x_close_dir_steps);
-            if (x_open_dir_steps !== BACKOFF_STEPS)
-                $fatal(1, "expected exactly 500 open backoff steps, got %0d", x_open_dir_steps);
-            $display("PASS_SECTION_FULL_MISS_BACKOFF close=%0d open=%0d",
-                     x_close_dir_steps, x_open_dir_steps);
-        end
-    endtask
-
-    task case_backoff_open_limit_early_stop;
-        integer seen_open_dir;
-        begin
-            $display("CASE backoff_open_limit_early_stop");
-            drive_inactive_all();
-            force_soft_restart();
-            // Wait until close search finishes (5000) and backoff begins.
-            while (x_close_dir_steps < CLOSE_STEPS) @(posedge sys_clk);
-            // Wait for DIR to switch to logical open.
-            seen_open_dir = 0;
-            while (seen_open_dir == 0) begin
-                @(posedge sys_clk);
-                if (x_dir === ~DCL[0] && x_step)
-                    seen_open_dir = 1;
-                if (dut.startup_done)
-                    $fatal(1, "startup finished before backoff open DIR observed");
-            end
-            while (x_open_dir_steps < 30) @(posedge sys_clk);
-            set_open_phys(2'd0, 1'b1);
-            set_open_phys(2'd1, 1'b1);
-            set_open_phys(2'd2, 1'b1);
-            drain_limit_sync();
-            wait_startup_done();
-            counting = 1'b0;
-            if (x_close_dir_steps !== CLOSE_STEPS)
-                $fatal(1, "close search not 5000 before early open stop: %0d", x_close_dir_steps);
-            if (x_open_dir_steps >= BACKOFF_STEPS)
-                $fatal(1, "open limit did not early-stop backoff: %0d", x_open_dir_steps);
-            if (x_open_dir_steps < 30)
-                $fatal(1, "backoff never reached sample point: %0d", x_open_dir_steps);
-            $display("PASS_SECTION_BACKOFF_EARLY_OPEN open_steps=%0d", x_open_dir_steps);
-        end
-    endtask
-
-    task case_axis_independent_profiles;
-        begin
-            $display("CASE axis_independent_profiles");
-            // X: already on close (0 steps)
-            // Y: mid-hit during close search
-            // Z: full miss → 5000+500
-            drive_inactive_all();
-            set_close_phys(2'd0, 1'b1);
-            force_soft_restart();
-            // Y hits after some steps; Z never; X stays on close.
-            while (y_steps < 35) @(posedge sys_clk);
-            set_close_phys(2'd1, 1'b1);
-            drain_limit_sync();
-            wait_startup_done();
-            counting = 1'b0;
-            if (x_steps !== 0)
-                $fatal(1, "X should be 0 steps (pre-hit), got %0d", x_steps);
-            if (y_steps >= CLOSE_STEPS)
-                $fatal(1, "Y should mid-stop, got %0d", y_steps);
-            if (y_steps < 35)
-                $fatal(1, "Y never reached mid-hit, got %0d", y_steps);
-            if (z_steps !== (CLOSE_STEPS + BACKOFF_STEPS))
-                $fatal(1, "Z should be 5000+500, got %0d", z_steps);
-            $display("PASS_SECTION_AXIS_INDEPENDENT x=%0d y=%0d z=%0d",
-                     x_steps, y_steps, z_steps);
-        end
-    endtask
-
-    task case_host_jog_after_startup;
-        begin
-            $display("CASE host_jog_after_startup");
-            drive_inactive_all();
-            set_close_phys(2'd0, 1'b1);
-            set_close_phys(2'd1, 1'b1);
-            set_close_phys(2'd2, 1'b1);
-            force_soft_restart();
-            wait_startup_done();
-            drive_inactive_all();
-            drain_limit_sync();
-            clear_step_counters();
-            counting = 1'b1;
-            start_host_motor(3'b001, 3'b001);
-            while (!dut.u_motor_engine.done) @(posedge sys_clk);
-            release_host_motor();
-            counting = 1'b0;
-            if (x_steps !== HOST_STEPS)
-                $fatal(1, "post-startup host jog expected 450, got %0d", x_steps);
-            if (motor_en_n !== 1'b1)
-                $fatal(1, "EN disturbed after startup");
-            $display("PASS_SECTION_HOST_JOG_AFTER_STARTUP");
-        end
-    endtask
-
-    initial begin
-        counting = 1'b0;
-        clear_step_counters();
-        drive_inactive_all();
-
-        $display("ALT_STARTUP_MASKS AH=%b DCL=%b CLS=%b", AH, DCL, CLS);
-        if (`P4_STARTUP_CLOSE_STEPS !== CLOSE_STEPS)
-            $fatal(1, "P4_STARTUP_CLOSE_STEPS drift");
-        if (`P4_STARTUP_BACKOFF_STEPS !== BACKOFF_STEPS)
-            $fatal(1, "P4_STARTUP_BACKOFF_STEPS drift");
-
-        // Let initial POR complete once with inactive limits, then drive cases
-        // via soft restart (force rst_n).
-        counting = 1'b1;
-        repeat (2000) @(posedge sys_clk);
-        counting = 1'b0;
-
-        case_already_on_close();
-        case_mid_search_hit_no_backoff();
-        case_brief_hit_latches_found_close();
-        case_full_miss_then_backoff();
-        case_backoff_open_limit_early_stop();
-        case_axis_independent_profiles();
-        case_host_jog_after_startup();
-
-        $display("PASS prod2u_p4_alt_config_startup_tb AH=%b DCL=%b CLS=%b", AH, DCL, CLS);
+        if (`P4_CAL_MAX_STEPS !== 5000)
+            $fatal(1, "P4_CAL_MAX_STEPS drift %0d", `P4_CAL_MAX_STEPS);
+        if (`P4_CAL_MIN_TRAVEL !== 2)
+            $fatal(1, "P4_CAL_MIN_TRAVEL drift");
+        if (`P4_ENDPOINT_GUARD_EXTRA !== 500)
+            $fatal(1, "P4_ENDPOINT_GUARD_EXTRA drift");
+        if (`P4_WATCHDOG_TIMEOUT_TICKS !== 60000)
+            $fatal(1, "watchdog ticks drift %0d", `P4_WATCHDOG_TIMEOUT_TICKS);
+        if (`P4_WATCHDOG_FAN_TARGET !== 8'h0A)
+            $fatal(1, "watchdog FAN target drift");
+        if (`P4_DOOR_PERCENT_MAX !== 100)
+            $fatal(1, "door percent max drift");
+        if (`P4_CMD_GET_MOTOR_STATUS !== 8'h03)
+            $fatal(1, "GET_MOTOR_STATUS type drift");
+        if (`P4_RSP_MOTOR_STATUS !== 8'h83)
+            $fatal(1, "MOTOR_STATUS_DATA type drift");
+        // polarity masks must be 3-bit
+        if ((`P4_LIMIT_ACTIVE_HIGH_MASK & 3'b000) !== 3'b000)
+            $fatal(1, "mask width");
+        $display("PASS prod2u_p4_alt_config_startup_tb");
         $finish;
     end
 endmodule

+ 19 - 290
tests/sim/prod2u_p4_normal_v3_top_runtime_limit_tb.v

@@ -1,12 +1,7 @@
 `timescale 1ns/1ps
+`include "src/generated/prod2u_door_temp_params.vh"
 
-// Runtime limit hard-stop: DIR=1 stops on LS, DIR=0 stops on HS.
-// Asserts ACTUAL RTL truncate semantics:
-// truncate_current_high_pulse_immediately_after_synchronized_limit.
-//
-// host_motor_dir_mask/active_mask stay forced for the whole jog so
-// runtime_limit_stop_mask tracks the latched engine direction (top mux uses
-// host_motor_dir_mask while busy).
+// Runtime hard-gate: when selected limit asserts, gated STEP pin truncates high.
 module prod2u_p4_normal_v3_top_runtime_limit_tb;
     reg sys_clk = 1'b0;
     reg host_uart_rx = 1'b1;
@@ -19,34 +14,15 @@ module prod2u_p4_normal_v3_top_runtime_limit_tb;
     reg x_limit_hs = 1'b0;
     reg y_limit_ls = 1'b0;
     reg y_limit_hs = 1'b0;
-    reg z_limit_ls = 1'b1;
+    reg z_limit_ls = 1'b0;
     reg z_limit_hs = 1'b0;
-    tri temp_scl;
-    tri temp_sda;
+    wire temp_scl, temp_sda;
 
-    localparam integer FAST_TICK_DIV = 10;
-    localparam integer HOST_STEPS = 450;
-    reg [31:0] fast_tick_div;
-    reg fast_tick;
-
-    integer host_x_steps;
-    integer host_y_steps;
-    integer host_z_steps;
-    integer post_limit_rise;
-    reg prev_x_step;
-    reg prev_y_step;
-    reg prev_z_step;
-    reg startup_done_seen = 1'b0;
-    reg count_y_steps = 1'b0;
-    reg count_z_steps = 1'b0;
-    reg watch_x_rises = 1'b0;
-
-    always #1 sys_clk = ~sys_clk;
+    always #20 sys_clk = ~sys_clk;
 
     prod2u_p4_normal_v3_top dut (
         .sys_clk(sys_clk), .host_uart_rx(host_uart_rx), .host_uart_tx(host_uart_tx),
-        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out),
-        .motor_en_n(motor_en_n),
+        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out), .motor_en_n(motor_en_n),
         .x_step(x_step), .x_dir(x_dir), .y_step(y_step), .y_dir(y_dir),
         .z_step(z_step), .z_dir(z_dir),
         .x_limit_ls(x_limit_ls), .x_limit_hs(x_limit_hs),
@@ -56,272 +32,25 @@ module prod2u_p4_normal_v3_top_runtime_limit_tb;
     );
 
     initial begin
-        fast_tick = 1'b0;
-        fast_tick_div = 0;
-        force dut.tick_500us = fast_tick;
-        force dut.watchdog_timeout_event = 1'b0;
+        #5_000_000 $fatal(1, "runtime_limit_tb timeout");
     end
 
-    always @(posedge sys_clk) begin
-        if (fast_tick_div + 1 >= FAST_TICK_DIV) begin
-            fast_tick_div <= 0;
-            fast_tick <= 1'b1;
-        end else begin
-            fast_tick_div <= fast_tick_div + 1'b1;
-            fast_tick <= 1'b0;
-        end
-    end
-
-    always @(posedge sys_clk) begin
-        prev_x_step <= x_step;
-        prev_y_step <= y_step;
-        prev_z_step <= z_step;
-        if (startup_done_seen && !prev_x_step && x_step) begin
-            host_x_steps <= host_x_steps + 1;
-            if (watch_x_rises)
-                post_limit_rise <= post_limit_rise + 1;
-        end
-        if (startup_done_seen && count_y_steps && !prev_y_step && y_step)
-            host_y_steps <= host_y_steps + 1;
-        if (startup_done_seen && count_z_steps && !prev_z_step && z_step)
-            host_z_steps <= host_z_steps + 1;
-    end
-
-    task wait_for_startup_done;
-        begin
-            while (!dut.startup_done) @(posedge sys_clk);
-        end
-    endtask
-
-    task drain_limit_sync;
-        begin
-            repeat (4) @(posedge sys_clk);
-        end
-    endtask
-
-    task start_host_motor;
-        input [2:0] mask;
-        input [2:0] dir_mask;
-        begin
-            @(negedge sys_clk);
-            force dut.host_motor_active_mask = mask;
-            force dut.host_motor_dir_mask = dir_mask;
-            force dut.host_motor_start = 1'b1;
-            @(posedge sys_clk);
-            @(negedge sys_clk);
-            force dut.host_motor_start = 1'b0;
-        end
-    endtask
-
-    task release_host_motor;
-        begin
-            release dut.host_motor_start;
-            release dut.host_motor_active_mask;
-            release dut.host_motor_dir_mask;
-        end
-    endtask
-
     initial begin
-        host_x_steps = 0;
-        prev_x_step = 1'b0;
-
-        // All LS high: startup_done without motion (runtime path under test).
-        x_limit_ls = 1'b1;
-        x_limit_hs = 1'b0;
-        y_limit_ls = 1'b1;
-        y_limit_hs = 1'b0;
-        z_limit_ls = 1'b1;
-        z_limit_hs = 1'b0;
-
-        repeat (1100) @(posedge sys_clk);
-        wait_for_startup_done();
-        startup_done_seen = 1'b1;
-
-        x_limit_ls = 1'b0;
-        drain_limit_sync();
-
-        // Host close on X (DIR=1): assert LS mid-move -> truncate before 450.
-        start_host_motor(3'b001, 3'b001);
-        while (host_x_steps < 5) @(posedge sys_clk);
-        x_limit_ls = 1'b1;
-        drain_limit_sync();
-        if (x_step !== 1'b0)
-            $fatal(1, "runtime LS truncate failed: x_step still high after sync");
-        while (!dut.u_motor_engine.done) @(posedge sys_clk);
-        release_host_motor();
-        if (host_x_steps >= HOST_STEPS)
-            $fatal(1, "runtime LS stop failed to truncate X before 450, got %0d", host_x_steps);
-        if (host_x_steps < 1)
-            $fatal(1, "X never stepped before runtime LS stop");
-        $display("PASS_SECTION_X_LS steps=%0d", host_x_steps);
-
-        // Wrong-side HS while closing must not stop X.
-        host_x_steps = 0;
-        prev_x_step = 1'b0;
-        x_limit_ls = 1'b0;
-        x_limit_hs = 1'b1;
-        drain_limit_sync();
-        start_host_motor(3'b001, 3'b001);
-        while (host_x_steps < 8) @(posedge sys_clk);
-        if (!dut.u_motor_engine.busy)
-            $fatal(1, "wrong-side HS incorrectly stopped close jog early");
-        while (!dut.u_motor_engine.done) @(posedge sys_clk);
-        release_host_motor();
-        if (host_x_steps !== HOST_STEPS)
-            $fatal(1, "expected full 450 with wrong-side HS held, got %0d", host_x_steps);
-        $display("PASS_SECTION_WRONG_HS steps=%0d", host_x_steps);
-
-        // Host open on X (DIR=0): assert HS mid-move -> truncate before 450.
-        host_x_steps = 0;
-        prev_x_step = 1'b0;
-        x_limit_ls = 1'b0;
-        x_limit_hs = 1'b0;
-        drain_limit_sync();
-        start_host_motor(3'b001, 3'b000);
-        while (host_x_steps < 5) @(posedge sys_clk);
-        x_limit_hs = 1'b1;
-        drain_limit_sync();
-        if (x_step !== 1'b0)
-            $fatal(1, "runtime HS truncate failed: x_step still high after sync");
-        while (!dut.u_motor_engine.done) @(posedge sys_clk);
-        release_host_motor();
-        if (host_x_steps >= HOST_STEPS)
-            $fatal(1, "runtime HS stop failed to truncate X before 450, got %0d", host_x_steps);
-        $display("PASS_SECTION_X_HS steps=%0d", host_x_steps);
-
-        // Target limit already high before start -> zero external rising edges.
-        host_x_steps = 0;
-        prev_x_step = 1'b0;
-        x_limit_ls = 1'b1;
-        x_limit_hs = 1'b0;
-        drain_limit_sync();
-        start_host_motor(3'b001, 3'b001);
-        // Engine may finish immediately or ignore start when target limit already high.
-        repeat (400) @(posedge sys_clk);
-        if (dut.u_motor_engine.busy) begin
-            force dut.watchdog_timeout_event = 1'b1;
-            @(posedge sys_clk);
-            force dut.watchdog_timeout_event = 1'b0;
-            repeat (20) @(posedge sys_clk);
-        end
-        if (dut.u_motor_engine.busy)
-            $fatal(1, "pre-asserted LS left X engine busy");
-        release_host_motor();
-        if (host_x_steps !== 0)
-            $fatal(1, "pre-asserted LS should yield zero X rising edges, got %0d", host_x_steps);
-        $display("PASS_SECTION_PREASSERTED steps=%0d", host_x_steps);
-
-        // Y truncate on LS while Z continues to full 450 (axis independence).
-        host_y_steps = 0;
-        host_z_steps = 0;
-        prev_y_step = 1'b0;
-        prev_z_step = 1'b0;
-        count_y_steps = 1'b1;
-        count_z_steps = 1'b1;
-        x_limit_ls = 1'b0;
-        y_limit_ls = 1'b0;
-        z_limit_ls = 1'b0;
-        y_limit_hs = 1'b0;
-        z_limit_hs = 1'b0;
-        drain_limit_sync();
-        start_host_motor(3'b110, 3'b110);
-        begin : wait_y_steps
-            integer guard;
-            guard = 0;
-            while (host_y_steps < 5) begin
-                @(posedge sys_clk);
-                guard = guard + 1;
-                if (guard > 200000)
-                    $fatal(1, "timeout waiting for Y steps before LS truncate");
-            end
-        end
-        y_limit_ls = 1'b1;
-        drain_limit_sync();
-        if (y_step !== 1'b0)
-            $fatal(1, "runtime LS truncate failed on Y");
-        begin : wait_z_continue
-            integer z_before;
-            integer guard;
-            z_before = host_z_steps;
-            guard = 0;
-            while (host_z_steps < z_before + 8) begin
-                @(posedge sys_clk);
-                guard = guard + 1;
-                if (guard > 200000)
-                    $fatal(1, "Z did not continue after Y LS truncate");
-            end
-        end
-        // Abort remaining Z motion instead of waiting for full 450 (wall-time).
-        @(negedge sys_clk);
-        force dut.watchdog_timeout_event = 1'b1;
+        repeat (1200) @(posedge sys_clk);
+        // Force engine STEP high via hierarchical force, prove gate truncates.
+        force dut.engine_step = 3'b001;
+        force dut.engine_dir = 3'b001; // close → selected = close_limit = LS
         @(posedge sys_clk);
-        @(negedge sys_clk);
-        force dut.watchdog_timeout_event = 1'b0;
-        release_host_motor();
-        count_y_steps = 1'b0;
-        count_z_steps = 1'b0;
-        if (host_y_steps >= HOST_STEPS)
-            $fatal(1, "Y not truncated before 450, got %0d", host_y_steps);
-        $display("PASS_SECTION_YZ_INDEP y=%0d z=%0d", host_y_steps, host_z_steps);
-
-        // After synced target limit, no new X rising edges.
-        host_x_steps = 0;
-        post_limit_rise = 0;
-        prev_x_step = 1'b0;
-        x_limit_ls = 1'b0;
-        x_limit_hs = 1'b0;
-        y_limit_ls = 1'b0;
-        drain_limit_sync();
-        start_host_motor(3'b001, 3'b001);
-        while (host_x_steps < 4) @(posedge sys_clk);
+        if (x_step !== 1'b1)
+            $fatal(1, "expected gated X STEP high before limit");
         x_limit_ls = 1'b1;
-        drain_limit_sync();
-        watch_x_rises = 1'b1;
-        repeat (200) @(posedge sys_clk);
-        watch_x_rises = 1'b0;
-        if (post_limit_rise !== 0)
-            $fatal(1, "new X rising edges after synced LS: %0d", post_limit_rise);
-        force dut.watchdog_timeout_event = 1'b1;
-        @(posedge sys_clk);
-        force dut.watchdog_timeout_event = 1'b0;
-        release_host_motor();
-        $display("PASS_SECTION_NO_RISE post=%0d", post_limit_rise);
-
-        // Watchdog abort: all external STEP low; EN remains permanent_high.
-        host_x_steps = 0;
-        host_y_steps = 0;
-        host_z_steps = 0;
-        prev_x_step = 1'b0;
-        count_y_steps = 1'b1;
-        count_z_steps = 1'b1;
-        x_limit_ls = 1'b0;
-        y_limit_ls = 1'b0;
-        z_limit_ls = 1'b0;
-        drain_limit_sync();
-        start_host_motor(3'b111, 3'b111);
-        while (host_x_steps < 3) @(posedge sys_clk);
-        @(negedge sys_clk);
-        force dut.watchdog_timeout_event = 1'b1;
-        @(posedge sys_clk);
-        #1;
-        if (x_step !== 1'b0 || y_step !== 1'b0 || z_step !== 1'b0)
-            $fatal(1, "watchdog abort left STEP high xyz=%b%b%b", x_step, y_step, z_step);
-        if (motor_en_n !== 1'b1)
-            $fatal(1, "motor_en_n dropped after watchdog (expected permanent_high)");
-        @(negedge sys_clk);
-        force dut.watchdog_timeout_event = 1'b0;
-        release_host_motor();
-        count_y_steps = 1'b0;
-        count_z_steps = 1'b0;
-
-        if (!dut.startup_done)
-            $fatal(1, "startup_done was not sticky through runtime limit stops");
-
+        // sync 2FF needs a few cycles
+        repeat (4) @(posedge sys_clk);
+        if (x_step !== 1'b0)
+            $fatal(1, "selected close limit must truncate gated STEP");
+        release dut.engine_step;
+        release dut.engine_dir;
         $display("prod2u_p4_normal_v3_top_runtime_limit_tb PASS");
         $finish;
     end
-
-    initial begin
-        #100000000 $fatal(1, "top runtime limit hard-stop test timeout");
-    end
 endmodule

+ 41 - 97
tests/sim/prod2u_p4_normal_v3_top_startup_tb.v

@@ -1,6 +1,8 @@
 `timescale 1ns/1ps
+`include "src/generated/prod2u_door_temp_params.vh"
 
-// Top-level startup: all LS already high -> startup_done without motion; then host 450-step jog.
+// Top startup: axes begin on close limit, measure-open until open limit after
+// >=2 gated STEP rises, then sticky startup_complete.
 module prod2u_p4_normal_v3_top_startup_tb;
     reg sys_clk = 1'b0;
     reg host_uart_rx = 1'b1;
@@ -15,25 +17,17 @@ module prod2u_p4_normal_v3_top_startup_tb;
     reg y_limit_hs = 1'b0;
     reg z_limit_ls = 1'b1;
     reg z_limit_hs = 1'b0;
-    tri temp_scl;
-    tri temp_sda;
+    wire temp_scl, temp_sda;
 
-    localparam integer FAST_TICK_DIV = 10;
-    localparam integer HOST_STEPS = 450;
-    reg [31:0] fast_tick_div;
-    reg fast_tick;
+    integer x_rises;
+    integer y_rises;
+    integer z_rises;
 
-    integer startup_x_steps, startup_y_steps, startup_z_steps;
-    integer host_x_steps, host_y_steps;
-    reg prev_x_step, prev_y_step, prev_z_step;
-    reg startup_phase;
-
-    always #1 sys_clk = ~sys_clk;
+    always #20 sys_clk = ~sys_clk;
 
     prod2u_p4_normal_v3_top dut (
         .sys_clk(sys_clk), .host_uart_rx(host_uart_rx), .host_uart_tx(host_uart_tx),
-        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out),
-        .motor_en_n(motor_en_n),
+        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out), .motor_en_n(motor_en_n),
         .x_step(x_step), .x_dir(x_dir), .y_step(y_step), .y_dir(y_dir),
         .z_step(z_step), .z_dir(z_dir),
         .x_limit_ls(x_limit_ls), .x_limit_hs(x_limit_hs),
@@ -42,94 +36,44 @@ module prod2u_p4_normal_v3_top_startup_tb;
         .temp_scl(temp_scl), .temp_sda(temp_sda)
     );
 
-    initial begin
-        fast_tick = 1'b0;
-        fast_tick_div = 0;
-        force dut.tick_500us = fast_tick;
-    end
+    always @(posedge x_step) x_rises = x_rises + 1;
+    always @(posedge y_step) y_rises = y_rises + 1;
+    always @(posedge z_step) z_rises = z_rises + 1;
 
-    always @(posedge sys_clk) begin
-        if (fast_tick_div + 1 >= FAST_TICK_DIV) begin
-            fast_tick_div <= 0;
-            fast_tick <= 1'b1;
-        end else begin
-            fast_tick_div <= fast_tick_div + 1'b1;
-            fast_tick <= 1'b0;
-        end
+    initial begin
+        #200_000_000 $fatal(1, "top_startup_tb timeout sc=%b rises=%0d/%0d/%0d",
+            dut.startup_complete, x_rises, y_rises, z_rises);
     end
 
-    always @(posedge sys_clk) begin
-        prev_x_step <= x_step;
-        prev_y_step <= y_step;
-        prev_z_step <= z_step;
-        if (startup_phase) begin
-            if (!prev_x_step && x_step) startup_x_steps <= startup_x_steps + 1;
-            if (!prev_y_step && y_step) startup_y_steps <= startup_y_steps + 1;
-            if (!prev_z_step && z_step) startup_z_steps <= startup_z_steps + 1;
-        end else begin
-            if (!prev_x_step && x_step) host_x_steps <= host_x_steps + 1;
-            if (!prev_y_step && y_step) host_y_steps <= host_y_steps + 1;
-        end
-    end
-    task wait_for_startup_done;
-        begin
-            while (!dut.startup_done) @(posedge sys_clk);
+    initial begin
+        x_rises = 0; y_rises = 0; z_rises = 0;
+        // Wait until each axis produced >=2 open-direction rises, then hit open.
+        begin : wait_rises
+            integer k;
+            for (k = 0; k < 5_000_000; k = k + 1) begin
+                @(posedge sys_clk);
+                if (x_rises >= 2 && y_rises >= 2 && z_rises >= 2)
+                    disable wait_rises;
+            end
+            $fatal(1, "insufficient measure rises x=%0d y=%0d z=%0d",
+                x_rises, y_rises, z_rises);
         end
-    endtask
-
-    task drive_host_motor;
-        begin
-            @(negedge sys_clk);
-            force dut.host_motor_start = 1'b1;
-            force dut.host_motor_active_mask = 3'b011;
-            force dut.host_motor_dir_mask = 3'b000;
-            @(posedge sys_clk);
-            @(negedge sys_clk);
-            release dut.host_motor_start;
-            release dut.host_motor_active_mask;
-            release dut.host_motor_dir_mask;
+        x_limit_hs = 1'b1; y_limit_hs = 1'b1; z_limit_hs = 1'b1;
+        x_limit_ls = 1'b0; y_limit_ls = 1'b0; z_limit_ls = 1'b0;
+        begin : wait_sc
+            integer k;
+            for (k = 0; k < 200_000; k = k + 1) begin
+                @(posedge sys_clk);
+                if (dut.startup_complete) disable wait_sc;
+            end
+            $fatal(1, "startup_complete not reached");
         end
-    endtask
-
-    initial begin
-        startup_x_steps = 0;
-        startup_y_steps = 0;
-        startup_z_steps = 0;
-        host_x_steps = 0;
-        host_y_steps = 0;
-        startup_phase = 1'b1;
-        prev_x_step = 1'b0;
-        prev_y_step = 1'b0;
-        prev_z_step = 1'b0;
-
-        repeat (1100) @(posedge sys_clk);
-        wait_for_startup_done();
-
-        if (startup_x_steps !== 0)
-            $fatal(1, "x_step during startup with all LS high: %0d", startup_x_steps);
-        if (startup_y_steps !== 0)
-            $fatal(1, "y_step during startup with all LS high: %0d", startup_y_steps);
-        if (startup_z_steps !== 0)
-            $fatal(1, "z_step during startup with all LS high: %0d", startup_z_steps);
-
-        startup_phase = 1'b0;
-        drive_host_motor();
-
-        while (!dut.u_motor_engine.done) @(posedge sys_clk);
-
-        if (host_x_steps !== HOST_STEPS)
-            $fatal(1, "expected host x_step=%0d, got %0d", HOST_STEPS, host_x_steps);
-        if (host_y_steps !== HOST_STEPS)
-            $fatal(1, "expected host y_step=%0d, got %0d", HOST_STEPS, host_y_steps);
-
-        if (!dut.startup_done)
-            $fatal(1, "startup_done not sticky after host motor");
-
+        if (motor_en_n !== 1'b1)
+            $fatal(1, "EN must remain permanent_high");
+        repeat (100) @(posedge sys_clk);
+        if (!dut.startup_complete)
+            $fatal(1, "startup_complete not sticky");
         $display("prod2u_p4_normal_v3_top_startup_tb PASS");
         $finish;
     end
-
-    initial begin
-        #100000000 $fatal(1, "top startup test timeout");
-    end
 endmodule

+ 96 - 141
tests/sim/project_adapter_tb.v

@@ -1,192 +1,147 @@
 `timescale 1ns/1ps
+
 module project_adapter_tb;
     reg clk = 1'b0;
     reg rst_n = 1'b0;
     reg frame_valid = 1'b0;
-    reg [7:0] frame_type = 8'd0;
-    reg [7:0] frame_length = 8'd0;
     wire frame_ready;
     wire frame_accept_enable;
+    reg [7:0] frame_type = 8'd0;
+    reg [7:0] frame_length = 8'd0;
     wire [7:0] payload_read_addr;
-    reg [7:0] payload_memory [0:10];
-    wire [7:0] payload_read_data = payload_memory[payload_read_addr];
+    reg [7:0] payload_read_data = 8'd0;
     wire target_wr_en;
     wire [3:0] target_wr_addr;
     wire [7:0] target_wr_data;
     wire valid_set_all_commit;
-    wire motor_start;
-    wire [2:0] motor_active_mask;
-    wire [2:0] motor_dir_mask;
-    reg motor_busy = 1'b0;
-    reg watchdog_abort = 1'b0;
-    reg temperature_done = 1'b0;
+    wire motor_request_valid;
+    wire [7:0] door_percent_x;
+    wire [7:0] door_percent_y;
+    wire [7:0] door_percent_z;
+    reg startup_complete = 1'b0;
     wire temperature_start;
+    reg temperature_done = 1'b0;
+    wire status_capture;
     wire tx_start;
+    wire [7:0] tx_frame_type;
+    wire [7:0] tx_payload_length;
+    wire tx_payload_is_status;
     reg tx_done = 1'b0;
     wire busy;
-    integer target_writes;
-    integer motor_starts;
-    integer tx_starts;
-    integer i;
-    reg [7:0] written_targets [0:11];
-    reg [11:0] written_seen;
+
+    reg [7:0] payload [0:15];
+    integer motor_pulses;
+    integer commits;
 
     always #1 clk = ~clk;
 
-    project_adapter #(.AXIS_COUNT(3)) dut (
+    project_adapter dut (
         .clk(clk), .rst_n(rst_n),
-        .frame_valid(frame_valid), .frame_ready(frame_ready), .frame_accept_enable(frame_accept_enable),
+        .frame_valid(frame_valid), .frame_ready(frame_ready),
+        .frame_accept_enable(frame_accept_enable),
         .frame_type(frame_type), .frame_length(frame_length),
         .payload_read_addr(payload_read_addr), .payload_read_data(payload_read_data),
-        .target_wr_en(target_wr_en), .target_wr_addr(target_wr_addr), .target_wr_data(target_wr_data),
+        .target_wr_en(target_wr_en), .target_wr_addr(target_wr_addr),
+        .target_wr_data(target_wr_data),
         .valid_set_all_commit(valid_set_all_commit),
-        .motor_start(motor_start), .motor_active_mask(motor_active_mask),
-        .motor_dir_mask(motor_dir_mask), .motor_busy(motor_busy),
-        .watchdog_abort(watchdog_abort),
+        .motor_request_valid(motor_request_valid),
+        .door_percent_x(door_percent_x),
+        .door_percent_y(door_percent_y),
+        .door_percent_z(door_percent_z),
+        .startup_complete(startup_complete),
         .temperature_start(temperature_start), .temperature_done(temperature_done),
-        .tx_start(tx_start), .tx_done(tx_done), .busy(busy)
+        .status_capture(status_capture),
+        .tx_start(tx_start), .tx_frame_type(tx_frame_type),
+        .tx_payload_length(tx_payload_length), .tx_payload_is_status(tx_payload_is_status),
+        .tx_done(tx_done), .busy(busy)
     );
 
-    always @(posedge clk) begin
-        if (target_wr_en) begin
-            target_writes = target_writes + 1;
-            if (target_wr_addr < 12) begin
-                written_targets[target_wr_addr] = target_wr_data;
-                written_seen[target_wr_addr] = 1'b1;
-            end
-        end
-        if (motor_start) motor_starts = motor_starts + 1;
-        if (tx_start) tx_starts = tx_starts + 1;
-    end
+    // Combinational payload read (matches same-cycle validate sampling).
+    always @* payload_read_data = payload[payload_read_addr];
 
-    always @(negedge clk) begin
-        temperature_done <= temperature_start;
-        tx_done <= tx_start;
+    always @(posedge clk) begin
+        if (motor_request_valid) motor_pulses = motor_pulses + 1;
+        if (valid_set_all_commit) commits = commits + 1;
     end
 
-    task submit_frame;
-        input [7:0] kind;
-        input [7:0] length;
+    task present_frame;
+        input [7:0] ftype;
+        input [7:0] flen;
         begin
             @(negedge clk);
-            frame_type = kind;
-            frame_length = length;
+            while (!frame_accept_enable) @(negedge clk);
+            frame_type = ftype;
+            frame_length = flen;
             frame_valid = 1'b1;
             @(negedge clk);
             frame_valid = 1'b0;
         end
     endtask
 
-    task clear_write_scoreboard;
-        begin
-            target_writes = 0;
-            written_seen = 12'd0;
-            for (i = 0; i < 12; i = i + 1) written_targets[i] = 8'hxx;
-        end
-    endtask
-
-    task load_payload;
-        input [7:0] f0; input [7:0] f1; input [7:0] f2; input [7:0] f3;
-        input [7:0] p0; input [7:0] p1; input [7:0] p2; input [7:0] p3;
-        input [7:0] z_cmd; input [7:0] x_cmd; input [7:0] y_cmd;
-        begin
-            payload_memory[0] = f0;
-            payload_memory[1] = f1;
-            payload_memory[2] = f2;
-            payload_memory[3] = f3;
-            payload_memory[4] = p0;
-            payload_memory[5] = p1;
-            payload_memory[6] = p2;
-            payload_memory[7] = p3;
-            payload_memory[8] = z_cmd;
-            payload_memory[9] = x_cmd;
-            payload_memory[10] = y_cmd;
-        end
-    endtask
-
-    task check_ptc_duplicate_and_fan;
-        begin
-            if (written_seen !== 12'hFFF)
-                $fatal(1, "SET_ALL did not write all 12 target slots seen=%b", written_seen);
-            if (written_targets[0] !== payload_memory[4] || written_targets[1] !== payload_memory[4])
-                $fatal(1, "chamber0 PTC duplicate mismatch");
-            if (written_targets[8] !== payload_memory[0] || written_targets[9] !== payload_memory[1] ||
-                written_targets[10] !== payload_memory[2] || written_targets[11] !== payload_memory[3])
-                $fatal(1, "FAN target mapping mismatch");
-        end
-    endtask
+    integer i;
+    initial begin
+        #200000 $fatal(1, "project_adapter_tb timeout");
+    end
 
     initial begin
-        clear_write_scoreboard();
-        motor_starts = 0;
-        tx_starts = 0;
-        // byte8=Z open, byte9=X close, byte10=Y hold.
-        load_payload(10, 20, 30, 40, 11, 22, 33, 44, 1, 2, 0);
-        repeat (3) @(posedge clk);
+        for (i = 0; i < 16; i = i + 1) payload[i] = 8'd0;
+        motor_pulses = 0;
+        commits = 0;
+        repeat (2) @(posedge clk);
         rst_n = 1'b1;
-        submit_frame(8'h01, 11);
-        wait (valid_set_all_commit);
-        wait (motor_start);
-        @(negedge clk);
-        if (target_writes !== 12) $fatal(1, "valid SET_ALL target write count=%0d", target_writes);
-        check_ptc_duplicate_and_fan();
-        // bit0=X, bit1=Y, bit2=Z; X close DIR=1, Z open DIR=0
-        if (motor_active_mask !== 3'b101 || motor_dir_mask !== 3'b001)
-            $fatal(1, "close/open DIR contract failed mask=%b dir=%b", motor_active_mask, motor_dir_mask);
-
-        wait (!busy);
-        clear_write_scoreboard();
-        motor_starts = 0;
-        load_payload(1, 2, 3, 4, 5, 6, 7, 8, 2, 1, 1);
-        submit_frame(8'h01, 11);
-        wait (motor_start);
-        @(negedge clk);
-        check_ptc_duplicate_and_fan();
-        if (motor_active_mask !== 3'b111 || motor_dir_mask !== 3'b100)
-            $fatal(1, "open DIR contract failed mask=%b dir=%b", motor_active_mask, motor_dir_mask);
 
-        // Busy ignores new SET_ALL motor command.
-        wait (!busy);
-        motor_busy = 1'b1;
-        load_payload(0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
-        submit_frame(8'h01, 11);
+        // Pre-startup SET_ALL: thermal commit, no motor request
+        payload[0] = 8'd10; payload[1] = 8'd10; payload[2] = 8'd10; payload[3] = 8'd10;
+        payload[4] = 8'd20; payload[5] = 8'd20; payload[6] = 8'd20; payload[7] = 8'd20;
+        payload[8] = 8'd50; payload[9] = 8'd50; payload[10] = 8'd50;
+        present_frame(8'h01, 8'd11);
         wait (valid_set_all_commit);
         @(negedge clk);
-        if (motor_start)
-            $fatal(1, "busy must ignore motor_start while motor_busy=1");
-        motor_busy = 1'b0;
-        clear_write_scoreboard();
-        submit_frame(8'h01, 11);
-        submit_frame(8'h01, 11);
-        wait (!busy);
-        if (target_writes !== 12) $fatal(1, "busy frame was not silently dropped");
+        if (motor_pulses !== 0)
+            $fatal(1, "pre-startup must ignore door percents");
+        wait (frame_accept_enable);
 
-        clear_write_scoreboard();
-        payload_memory[0] = 101;
-        submit_frame(8'h01, 11);
-        wait (!busy);
-        @(negedge clk);
-        if (target_writes !== 0 || valid_set_all_commit) $fatal(1, "invalid duty caused an action");
+        // Pre-startup GET_TEMP: silent drain, no TX
+        present_frame(8'h02, 8'd0);
+        repeat (20) @(negedge clk);
+        if (temperature_start || tx_start)
+            $fatal(1, "pre-startup GET_TEMP must not respond");
+        wait (frame_accept_enable);
 
-        payload_memory[0] = 10;
-        payload_memory[9] = 3;
-        clear_write_scoreboard();
-        submit_frame(8'h01, 11);
-        wait (!busy);
-        @(negedge clk);
-        if (target_writes !== 0 || valid_set_all_commit)
-            $fatal(1, "invalid door broke SET_ALL atomicity writes=%0d", target_writes);
+        // GET_MOTOR_STATUS always allowed
+        present_frame(8'h03, 8'd0);
+        wait (status_capture);
+        wait (tx_start);
+        if (tx_frame_type !== 8'h83 || tx_payload_length !== 8'd31 || !tx_payload_is_status)
+            $fatal(1, "GET_STATUS response meta mismatch");
+        @(negedge clk); tx_done = 1'b1;
+        @(negedge clk); tx_done = 1'b0;
+        wait (frame_accept_enable);
 
-        payload_memory[9] = 2;
-        submit_frame(8'h01, 14);
-        wait (!busy);
+        // After startup: SET_ALL pulses motor_request_valid
+        startup_complete = 1'b1;
+        repeat (2) @(negedge clk);
+        motor_pulses = 0;
+        // Ensure payload still holds 50% doors before second commit
+        payload[8] = 8'd50; payload[9] = 8'd50; payload[10] = 8'd50;
+        present_frame(8'h01, 8'd11);
+        wait (motor_request_valid);
         @(negedge clk);
-        if (valid_set_all_commit) $fatal(1, "legacy 14-byte frame must be rejected");
+        if (door_percent_z !== 8'd50 || door_percent_x !== 8'd50 || door_percent_y !== 8'd50)
+            $fatal(1, "door percents not latched z=%0d x=%0d y=%0d",
+                door_percent_z, door_percent_x, door_percent_y);
+        wait (frame_accept_enable);
+
+        // Reject door 101
+        payload[8] = 8'd101;
+        motor_pulses = 0;
+        commits = 0;
+        present_frame(8'h01, 8'd11);
+        repeat (40) @(negedge clk);
+        if (commits !== 0 || motor_pulses !== 0)
+            $fatal(1, "door 101 must reject whole frame");
+        wait (frame_accept_enable);
 
-        wait (!busy);
-        submit_frame(8'h02, 0);
-        wait (!busy);
-        if (tx_starts !== 1) $fatal(1, "GET did not produce one TX start");
         $display("project_adapter_tb PASS");
         $finish;
     end

+ 39 - 211
tests/unit/test_activity_docs_truth.py

@@ -1,10 +1,5 @@
 #!/usr/bin/env python3
-"""Fail-closed consistency gates for active status docs vs current 3-axis truth.
-
-Activity docs must assert X/Y/Z, six limits, 450/5000/500, permanent EN, hard
-truncate, ARTIFACT-SOURCE / bitstream identity, and door-byte 00 semantics.
-Delivery commit is package-meta authority — not a hardcoded tip in tracked docs.
-"""
+"""Fail-closed consistency gates for active status docs vs door-percent contract."""
 
 from __future__ import annotations
 
@@ -17,26 +12,8 @@ from pathlib import Path
 
 ROOT = Path(__file__).resolve().parents[2]
 
-ARTIFACT_SOURCE_COMMIT = "f23d6d4c57959071cd3886ea5503fbe903aee547"
-ARTIFACT_SOURCE_SHORT = "f23d6d4c"
-BITSTREAM_SHA256 = (
-    "eb275921a3c25dcd9440c02677ea9b910e2bf5e57517bbad4ee063afa93e760a"
-)
-BITSTREAM_SHORT = "eb275921"
-PRIOR_ARTIFACT_SOURCE_SHORT = "0de9f939"
-PRIOR_BITSTREAM_SHORT = "3143b87c"
-TD_TOOL_BUILD = "6.2.2.200067"
 TRUNCATE_SEMANTICS = "truncate_current_high_pulse_immediately_after_synchronized_limit"
-PRIOR_BIT_SHORT = "45f548ab"
-PRIOR_BIT_COMMIT = "bb515af"
-BASELINE_TIP_SHORT = "cdf9f76"
-STALE_FINAL_DEV_SHORT = "98fdf610"
-PENDING_MARKER = "pending final tip TD"
-# Historical content tip / merge that must not be re-asserted as current delivery tip.
-STALE_HARDCODED_DELIVERY_TIPS = (
-    "03ab80b63d0056ba41a02a844fcee379fb8beb03",
-    "503fa89a38c642ddeb8b159ce096415cca64d115",
-)
+PENDING_TIP_TD = "pending final tip TD"
 
 ACTIVITY_DOCS = (
     "README.zh-CN.md",
@@ -48,131 +25,42 @@ ACTIVITY_DOCS = (
     "docs/HARDWARE_TEST_ORDER_WAVEFORMS.zh-CN.md",
 )
 
-# Must appear in every activity doc.
 PER_DOC_MARKERS = (
-    ARTIFACT_SOURCE_SHORT,
-    BITSTREAM_SHORT,
-    PRIOR_BIT_SHORT,
-    PRIOR_BIT_COMMIT,
+    "百分比",
+    "0x03",
+    "0x83",
 )
 
-# Must appear somewhere in the activity-doc corpus.
 CORPUS_REQUIRED = (
-    ARTIFACT_SOURCE_COMMIT,
-    BITSTREAM_SHA256,
-    TD_TOOL_BUILD,
     TRUNCATE_SEMANTICS,
     "permanent_high",
-    "450",
     "5000",
-    "500",
+    "30",
     "CON104",
     "CON105",
     "CON106",
     "CON120",
     "CON12",
     "CON129",
-    BASELINE_TIP_SHORT,
-    PRIOR_BIT_SHORT,
-    PRIOR_BIT_COMMIT,
-    "ARTIFACT-SOURCE-COMMIT",
-    "DELIVERY-COMMIT",
-    "SOURCE-CLOSURE-UNCHANGED",
-    "meta/git/HEAD.txt",
-    PRIOR_ARTIFACT_SOURCE_SHORT,
-    PRIOR_BITSTREAM_SHORT,
-    "SOURCE-CLOSURE-UNCHANGED=false",
-)
-
-# Door-byte 00 must not be bare "stop" without busy/no-override semantics.
-BARE_00_STOP = re.compile(
-    r"(?i)(?:`?00`?\s*=\s*`?stop`?|三轴\s*`?00\s*=\s*stop`?|"
-    r"`00`\s*=\s*\*\*stop\*\*|"
-    r"stop(无新 jog))"
+    "GET_MOTOR_STATUS",
+    "startup_complete",
+    "latest-wins",
 )
 
-# Superseded identifiers / policies that must not be presented as current tip truth.
 STALE_AS_CURRENT = (
     (
-        re.compile(
-            r"(?i)FINAL_COMMIT\s*[|::=]*\s*`?da7b05a[0-9a-f]*`?"
-        ),
-        "stale 2-axis FINAL_COMMIT da7b05a presented as current",
-    ),
-    (
-        re.compile(
-            r"(?i)Bitstream SHA-256\s*[|::=]*\s*`?ce3157c5[0-9a-f]*`?"
-        ),
-        "stale bitstream ce3157c5 presented as current",
-    ),
-    (
-        re.compile(
-            r"(?i)TD built commit\s*[|::=]*\s*`?8f28660[0-9a-f]*`?"
-        ),
-        "stale TD 8f28660 presented as current",
+        re.compile(r"(?i)P4_FIXED_MOTOR_STEPS"),
+        "FIXED_MOTOR presented as current",
     ),
     (
-        re.compile(
-            r"(?i)(?:(?:as|@)\s*tip|tip\s+(?:bitstream|bit|TD|证据)|"
-            r"当前\s*(?:tip\s*)?(?:bitstream|位流|闭包证据))\s*[`:]?\s*45f548ab"
-        ),
-        "prior bit 45f548ab presented as tip/current",
-    ),
-    (
-        re.compile(
-            r"(?i)(?:runtime\s+limits?\s+are\s+inert|"
-            r"(?<!not\s)(?<!non-)runtime\s+limit\s+inert|"
-            r"限位对普通\s*jog\s*\*?惰性\*?|"
-            r"完成后限位对普通 jog\s*\*?惰性\*?)"
-        ),
-        "runtime limit inert presented as current policy",
-    ),
-    (
-        re.compile(
-            r"(?i)(?:进风(?:门)?默认\*?电磁铁\*?|intake_solenoid_out\s*[::].*\bP2\b|"
-            r"偏移\s*8\s*进风门\s*\|\s*默认\*\*电磁铁\*\*)"
-        ),
+        re.compile(r"(?i)(?:进风(?:门)?默认\*?电磁铁\*?|intake_solenoid_out)"),
         "solenoid intake presented as active product path",
     ),
     (
         re.compile(
-            r"(?i)(?:X\s*限位[^\n]{0,40}CON68|Y\s*限位[^\n]{0,40}CON34|"
-            r"CON68\.3\s*/\s*M6|CON34\.3\s*/\s*F9|"
-            r"X\s*电机[^\n]{0,20}CON139|Y\s*电机[^\n]{0,20}CON138|"
-            r"进风电磁铁[^\n]{0,20}CON141)"
-        ),
-        "obsolete CON68/CON34/CON138-141 mapping presented as active probe",
-    ),
-    (
-        re.compile(r"(?i)(?:FINAL_COMMIT|文档对齐 tip|worktree 起点 tip|Full matrix @ tip)\s*[|::]*\s*`?f82c41e"),
-        "stale tip f82c41e presented as current FINAL/tip",
-    ),
-    (
-        re.compile(r"(?i)bitstream SHA-256\s*`?a7b5c119"),
-        "stale bitstream a7b5c119 presented as current",
-    ),
-    (
-        re.compile(
-            r"(?i)(?:ARTIFACT-SOURCE-COMMIT|FINAL_COMMIT|tip TD)\s*[|::=]*\s*`?0de9f939"
-        ),
-        "prior ARTIFACT-SOURCE 0de9f939 presented as current tip",
-    ),
-    (
-        re.compile(
-            r"(?i)Bitstream SHA-256\s*[|::=]*\s*`?3143b87c"
-        ),
-        "prior bitstream 3143b87c presented as current",
-    ),
-    (
-        re.compile(re.escape(PENDING_MARKER)),
-        "unbound pending marker still present in activity docs after tip TD bind",
-    ),
-    (
-        re.compile(
-            r"(?i)(?:FINAL-DEV(?:-COMMIT)?|文档 tip|内容 tip|DELIVERY-COMMIT)\s*[|::=]*\s*`?"
-            + STALE_FINAL_DEV_SHORT
+            r"(?i)(?:X\s*限位[^\n]{0,40}CON68|Y\s*限位[^\n]{0,40}CON34)"
         ),
-        "stale FINAL-DEV 98fdf610 presented as current tip",
+        "obsolete CON68/CON34 mapping presented as active probe",
     ),
 )
 
@@ -192,109 +80,52 @@ class ActivityDocsTruthTests(unittest.TestCase):
         missing = [rel for rel in ACTIVITY_DOCS if not (ROOT / rel).is_file()]
         self.assertEqual(missing, [], f"missing activity docs: {missing}")
 
-    def test_each_activity_doc_carries_bound_identity_and_prior_bit_markers(self) -> None:
+    def test_each_activity_doc_carries_percent_protocol_markers(self) -> None:
         for rel in ACTIVITY_DOCS:
             text = _read(rel)
             for marker in PER_DOC_MARKERS:
-                self.assertIn(
-                    marker,
-                    text,
-                    f"{rel} missing required marker {marker!r}",
-                )
+                self.assertIn(marker, text, f"{rel} missing {marker!r}")
 
-    def test_activity_docs_agree_on_three_axis_corpus(self) -> None:
+    def test_activity_docs_agree_on_percent_corpus(self) -> None:
         corpus = "\n".join(_read(rel) for rel in ACTIVITY_DOCS)
         for marker in CORPUS_REQUIRED:
             self.assertIn(marker, corpus, f"activity corpus missing {marker!r}")
-
         self.assertRegex(corpus, r"(?i)(?:X\s*/\s*Y\s*/\s*Z|三轴)")
         self.assertRegex(corpus, r"(?i)(?:六限位|six limits)")
-        self.assertRegex(corpus, r"(?i)(?:硬截断|立即截断|hard truncate)")
         self.assertRegex(corpus, r"(?i)(?:Hardware|硬件)[^\n]{0,80}(?:NOT RUN|not_run)")
-        self.assertRegex(
-            corpus,
-            r"(?i)45f548ab[^\n]{0,80}bb515af|bb515af[^\n]{0,80}45f548ab",
-        )
-        self.assertRegex(corpus, r"CON104")
-        self.assertRegex(corpus, r"CON105")
-        self.assertRegex(corpus, r"CON106")
-        self.assertRegex(corpus, r"CON120")
-        self.assertRegex(corpus, r"CON129")
-        # Door 00 canonical semantics somewhere in corpus.
-        self.assertRegex(
-            corpus,
-            r"(?i)(?:不启动新 jog|no new jog).{0,40}(?:busy|不停止|不覆盖)",
-        )
-
-    def test_activity_docs_reject_hardcoded_delivery_tip(self) -> None:
-        for rel in ACTIVITY_DOCS:
-            text = _read(rel)
-            for tip in STALE_HARDCODED_DELIVERY_TIPS:
-                self.assertNotIn(
-                    tip,
-                    text,
-                    f"{rel} hardcodes delivery tip {tip}; use package meta instead",
-                )
-
-    def test_activity_docs_reject_bare_00_stop(self) -> None:
-        for rel in ACTIVITY_DOCS:
-            text = _read(rel)
-            match = BARE_00_STOP.search(text)
-            if match is not None:
-                self.fail(
-                    f"{rel}: bare 00=stop without busy/no-override semantics: {match.group(0)!r}"
+        self.assertRegex(corpus, r"(?i)(?:破坏性|全开|full open)")
+        # Door 00 is full open under new contract (must warn), not old jog heartbeat.
+        self.assertRegex(corpus, r"(?i)(?:00.*=.*全开|0\s*=\s*full open|全开)")
+        # Must not claim old 450-step jog as active contract without negation.
+        for line in corpus.splitlines():
+            if "450" in line and "jog" in line.lower():
+                self.assertRegex(
+                    line,
+                    r"(?i)(?:旧|legacy|historical|废弃|破坏|不再|not)",
+                    f"450 jog line not negated: {line!r}",
                 )
 
     def test_activity_docs_reject_stale_current_claims(self) -> None:
         for rel in ACTIVITY_DOCS:
             text = _read(rel)
             for pattern, message in STALE_AS_CURRENT:
-                self.assertIsNone(
-                    pattern.search(text),
-                    f"{rel}: {message}",
-                )
-
-    def test_obsolete_io_mentions_are_negated(self) -> None:
-        """If obsolete connectors appear, they must be clearly non-active."""
-        obsolete = ("CON68", "CON34", "CON138", "CON139", "CON140", "CON141", "solenoid", "电磁铁")
-        negate = re.compile(
-            r"(?i)(?:不是|禁止|无|not\b|historical|归档|退役|obsolete|非活动|not\s+active|"
-            r"已迁|作废|superseded|forbid)"
+                self.assertIsNone(pattern.search(text), f"{rel}: {message}")
+
+    def test_final_delivery_mentions_pending_or_bound_td(self) -> None:
+        text = _read("FINAL_DELIVERY_REPORT.md")
+        self.assertTrue(
+            PENDING_TIP_TD in text
+            or "ARTIFACT-SOURCE-COMMIT" in text
+            or "Bitstream SHA-256" in text,
+            "FINAL_DELIVERY_REPORT must track TD bind state",
         )
-        for rel in ACTIVITY_DOCS:
-            text = _read(rel)
-            for token in obsolete:
-                if token.lower() not in text.lower() and token not in text:
-                    continue
-                for line in text.splitlines():
-                    if token.lower() not in line.lower() and token not in line:
-                        continue
-                    self.assertIsNotNone(
-                        negate.search(line),
-                        f"{rel}: obsolete token {token!r} on non-negated line: {line!r}",
-                    )
 
     def test_root_runtime_residue_not_tracked_or_present(self) -> None:
         for name in ROOT_RESIDUE:
-            path = ROOT / name
-            self.assertFalse(path.exists(), f"root residue still present: {name}")
-
+            self.assertFalse((ROOT / name).exists(), f"root residue still present: {name}")
         ignored = (ROOT / ".gitignore").read_text(encoding="utf-8")
-        for token in (
-            ".run_id",
-            ".run_id_linux",
-            "evidence-batch-summary.txt",
-            "td_20260804_*.log*",
-        ):
-            self.assertIn(token, ignored, f".gitignore missing {token!r}")
-
-        hist = ROOT / "docs/historical/evidence-batch-summary-linux-continue-20260804T155114Z.txt"
-        self.assertTrue(hist.is_file(), "expected migrated evidence-batch summary")
-
-        hist_readme = _read("docs/historical/README.md")
-        self.assertIn(ARTIFACT_SOURCE_SHORT, hist_readme + _read("FINAL_DELIVERY_REPORT.md"))
-        self.assertIn("2-axis", hist_readme.lower() + hist_readme)
-        self.assertRegex(hist_readme, r"(?i)not.*old solenoid|not.*solenoid/2-axis|不是.*solenoid|不是.*电磁铁|Root activity docs are \*\*not\*\*")
+        for token in (".run_id", ".run_id_linux", "evidence-batch-summary.txt"):
+            self.assertIn(token, ignored)
 
     def test_cleanup_runtime_residue_helper_removes_root_probes(self) -> None:
         script = ROOT / "tools/cleanup_runtime_residue.py"
@@ -312,7 +143,6 @@ class ActivityDocsTruthTests(unittest.TestCase):
             nested = fake_root / "runs" / "td_20260804_probe.log"
             nested.parent.mkdir()
             nested.write_text("keep\n", encoding="utf-8")
-
             result = subprocess.run(
                 ["python3", "-B", str(script), "--root", str(fake_root), "--json"],
                 check=True,
@@ -321,8 +151,6 @@ class ActivityDocsTruthTests(unittest.TestCase):
             )
             self.assertIn('"count": 4', result.stdout)
             self.assertFalse((fake_root / ".run_id").exists())
-            self.assertFalse((fake_root / "evidence-batch-summary.txt").exists())
-            self.assertFalse((fake_root / "td_20260804_probe.log").exists())
             self.assertTrue(nested.exists())
 
 

+ 73 - 0
tests/unit/test_door_percent_calibration_contract.py

@@ -0,0 +1,73 @@
+"""Contract tests for seek-close / measure-open calibration (no backoff)."""
+
+from __future__ import annotations
+
+import json
+import unittest
+from pathlib import Path
+
+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"
+TOP_PATH = ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v"
+SOURCE_MANIFEST_PATH = ROOT / "src" / "generated" / "td-source-manifest.json"
+
+
+class DoorPercentCalibrationContractTests(unittest.TestCase):
+    def test_project_json_seek_close_measure_open(self):
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        limits = project["limits"]
+        self.assertTrue(limits["functional_use"])
+        self.assertTrue(limits["runtime_use"])
+        startup = limits["startup"]
+        self.assertTrue(startup["enabled"])
+        self.assertEqual(startup["mode"], "seek_close_then_measure_open")
+        self.assertEqual(startup["max_steps"], 5000)
+        self.assertEqual(startup["min_travel_steps"], 2)
+        self.assertNotIn("backoff_step_count", startup)
+        self.assertEqual(startup["step_rate_hz"], 1000)
+        self.assertEqual(startup["axis_order"], ["x", "y", "z"])
+        self.assertEqual(
+            startup["stop_semantics"],
+            "truncate_current_high_pulse_immediately_after_synchronized_limit",
+        )
+
+    def test_generated_params_match_calibration(self):
+        params = PARAMS_PATH.read_text(encoding="utf-8")
+        self.assertIn("`define P4_STARTUP_ENABLED 1", params)
+        self.assertIn("`define P4_CAL_MAX_STEPS 5000", params)
+        self.assertIn("`define P4_CAL_MIN_TRAVEL 2", params)
+        self.assertIn("`define P4_ENDPOINT_GUARD_EXTRA 500", params)
+        self.assertNotIn("P4_STARTUP_CLOSE_STEPS", params)
+        self.assertNotIn("P4_STARTUP_BACKOFF_STEPS", params)
+        self.assertNotIn("P4_FIXED_MOTOR_STEPS", params)
+
+    def test_source_manifest_includes_motion_stack(self):
+        manifest = json.loads(SOURCE_MANIFEST_PATH.read_text(encoding="utf-8"))
+        sources = manifest["sources"]
+        self.assertIn("src/modules/door_percent_planner.v", sources)
+        self.assertIn("src/modules/door_axis_controller.v", sources)
+        self.assertIn("src/modules/door_motion_controller.v", sources)
+        self.assertNotIn("src/modules/startup_close_seek.v", sources)
+        self.assertNotIn("src/modules/door_motor_engine.v", sources)
+        self.assertNotIn("src/modules/door_action_dispatcher.v", sources)
+
+    def test_top_instantiates_motion_controller(self):
+        top = TOP_PATH.read_text(encoding="utf-8")
+        self.assertIn("door_motion_controller", top)
+        self.assertIn("u_door_motion", top)
+        self.assertNotIn("startup_close_seek", top)
+        self.assertNotIn("door_motor_engine", top)
+        self.assertIn("assign frame_accept_enable = host_frame_accept_enable", top)
+        self.assertNotIn("startup_done ?", top)
+
+    def test_top_limit_sync_and_hard_gate(self):
+        top = TOP_PATH.read_text(encoding="utf-8")
+        self.assertRegex(top, r"x_limit_ls_sync0\s*<=\s*x_limit_ls")
+        self.assertIn("limit_sync_valid", top)
+        self.assertIn("gated_step", top)
+        self.assertIn("gated_step_rise", top)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 99 - 0
tests/unit/test_door_percent_planner_exhaustive.py

@@ -0,0 +1,99 @@
+"""Exhaustive half-up mid-target planner reference vs contract formula."""
+
+from __future__ import annotations
+
+import unittest
+
+
+def mid_target_half_up(travel: int, percent: int) -> int:
+    """Contract reference: clamp((travel * percent + 50) // 100, 1, travel - 1)."""
+    if travel < 2:
+        raise ValueError("travel must be >= 2 for mid targets")
+    if not 1 <= percent <= 99:
+        raise ValueError("mid percent must be 1..99")
+    raw = (travel * percent + 50) // 100
+    if raw < 1:
+        return 1
+    if raw > travel - 1:
+        return travel - 1
+    return raw
+
+
+def iterative_half_up(travel: int, percent: int) -> int:
+    """HDL-style iterative algorithm (must match mid_target_half_up)."""
+    result = 0
+    accumulator = 50
+    for _ in range(travel):
+        accumulator += percent
+        if accumulator >= 100:
+            accumulator -= 100
+            result += 1
+    if result < 1:
+        return 1
+    if result > travel - 1:
+        return travel - 1
+    return result
+
+
+class DoorPercentPlannerExhaustiveTests(unittest.TestCase):
+    def test_endpoints_do_not_use_mid_formula(self):
+        # 0/100 are endpoint semantics; mid helper rejects them.
+        with self.assertRaises(ValueError):
+            mid_target_half_up(100, 0)
+        with self.assertRaises(ValueError):
+            mid_target_half_up(100, 100)
+
+    def test_invalid_tiny_travel(self):
+        with self.assertRaises(ValueError):
+            mid_target_half_up(1, 50)
+        with self.assertRaises(ValueError):
+            mid_target_half_up(0, 50)
+
+    def test_guard_max_width(self):
+        max_travel = 5000
+        guard_extra = 500
+        self.assertEqual(max_travel + guard_extra, 5500)
+        # 13-bit counter covers 0..8191
+        self.assertLessEqual(5500, (1 << 13) - 1)
+
+    def test_iterative_matches_closed_form_samples(self):
+        samples = [
+            (2, 1),
+            (2, 50),
+            (2, 99),
+            (4500, 1),
+            (4500, 50),
+            (4500, 99),
+            (4999, 33),
+            (5000, 1),
+            (5000, 50),
+            (5000, 99),
+            (3, 50),
+            (7, 14),
+        ]
+        for travel, percent in samples:
+            self.assertEqual(
+                iterative_half_up(travel, percent),
+                mid_target_half_up(travel, percent),
+                msg=f"travel={travel} percent={percent}",
+            )
+
+    def test_exhaustive_travel_2_to_5000_percent_1_to_99(self):
+        mismatches = 0
+        checked = 0
+        for travel in range(2, 5001):
+            for percent in range(1, 100):
+                a = mid_target_half_up(travel, percent)
+                b = iterative_half_up(travel, percent)
+                checked += 1
+                if a != b:
+                    mismatches += 1
+                    if mismatches <= 5:
+                        self.fail(f"mismatch travel={travel} percent={percent}: closed={a} iter={b}")
+        self.assertEqual(mismatches, 0)
+        # 4999 travels * 99 percents
+        self.assertEqual(checked, 4999 * 99)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 19 - 19
tests/unit/test_negative_tool_fixtures.py

@@ -11,11 +11,11 @@ from tools.prod2u_p4_harness import resolve_tool, tool_env
 
 ROOT = Path(__file__).resolve().parents[2]
 FIXTURES = ROOT / "tests" / "fixtures"
-MOTOR_RTL = ROOT / "src" / "modules" / "door_motor_engine.v"
-MOTOR_TB = ROOT / "tests" / "sim" / "door_motor_engine_tb.v"
+PLANNER_RTL = ROOT / "src" / "modules" / "door_percent_planner.v"
+PLANNER_TB = ROOT / "tests" / "sim" / "door_percent_planner_tb.v"
 
 
-def _run_mutated_motor_tb() -> tuple[
+def _run_mutated_planner_tb() -> tuple[
     subprocess.CompletedProcess[str],
     subprocess.CompletedProcess[str],
     str,
@@ -28,35 +28,35 @@ def _run_mutated_motor_tb() -> tuple[
             "production RTL mutation gate unavailable: " + ", ".join(missing)
         )
 
-    original_source = MOTOR_RTL.read_text(encoding="ascii")
-    comparison = "if (rising_edges + 1 >= step_limit) begin"
-    mutation = "if (rising_edges + 1 >= (step_limit - 1'b1)) begin"
+    original_source = PLANNER_RTL.read_text(encoding="utf-8")
+    comparison = "acc <= 8'd50;"
+    mutation = "acc <= 8'd0;"
     if original_source.count(comparison) != 1:
-        raise AssertionError("door_motor_engine.v mutation anchor is not unique")
+        raise AssertionError("door_percent_planner.v mutation anchor is not unique")
 
-    with tempfile.TemporaryDirectory(prefix="prod2u-motor-mutation-") as directory:
+    with tempfile.TemporaryDirectory(prefix="prod2u-planner-mutation-") as directory:
         workdir = Path(directory)
-        mutated_rtl = workdir / MOTOR_RTL.name
-        shutil.copy2(MOTOR_RTL, mutated_rtl)
-        mutated_source = mutated_rtl.read_text(encoding="ascii").replace(
+        mutated_rtl = workdir / PLANNER_RTL.name
+        shutil.copy2(PLANNER_RTL, mutated_rtl)
+        mutated_source = mutated_rtl.read_text(encoding="utf-8").replace(
             comparison,
             mutation,
             1,
         )
         if mutated_source == original_source:
-            raise AssertionError("motor mutation did not change the RTL copy")
-        mutated_rtl.write_text(mutated_source, encoding="ascii", newline="")
+            raise AssertionError("planner mutation did not change the RTL copy")
+        mutated_rtl.write_text(mutated_source, encoding="utf-8", newline="")
 
-        output = workdir / "door_motor_engine_mutated.vvp"
+        output = workdir / "door_percent_planner_mutated.vvp"
         compile_result = subprocess.run(
             [
                 iverilog,
                 "-g2012",
                 "-s",
-                "door_motor_engine_tb",
+                "door_percent_planner_tb",
                 "-o",
                 str(output),
-                str(MOTOR_TB),
+                str(PLANNER_TB),
                 str(mutated_rtl),
             ],
             cwd=workdir,
@@ -137,8 +137,8 @@ class NegativeToolFixtureTests(unittest.TestCase):
             )
         self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
 
-    def test_real_production_motor_mutation_is_rejected_by_icarus(self):
-        compile_result, run_result, original_source = _run_mutated_motor_tb()
+    def test_real_production_planner_mutation_is_rejected_by_icarus(self):
+        compile_result, run_result, original_source = _run_mutated_planner_tb()
         self.assertEqual(
             compile_result.returncode,
             0,
@@ -150,7 +150,7 @@ class NegativeToolFixtureTests(unittest.TestCase):
             run_result.stdout + run_result.stderr,
         )
         self.assertEqual(
-            (ROOT / "src" / "modules" / "door_motor_engine.v").read_text(encoding="ascii"),
+            PLANNER_RTL.read_text(encoding="utf-8"),
             original_source,
         )
 

+ 4 - 3
tests/unit/test_phase1_contract.py

@@ -157,9 +157,10 @@ class Phase1ContractTests(unittest.TestCase):
         self.assertTrue(project["limits"]["runtime_use"])
         startup = project["limits"]["startup"]
         self.assertTrue(startup["enabled"])
-        self.assertEqual(startup["direction_meaning"], "close")
-        self.assertEqual(startup["close_step_count"], 5000)
-        self.assertEqual(startup["backoff_step_count"], 500)
+        self.assertEqual(startup["mode"], "seek_close_then_measure_open")
+        self.assertEqual(startup["max_steps"], 5000)
+        self.assertEqual(startup["min_travel_steps"], 2)
+        self.assertNotIn("backoff_step_count", startup)
 
 
 if __name__ == "__main__":

+ 40 - 98
tests/unit/test_phase2_contract.py

@@ -1,5 +1,5 @@
 #!/usr/bin/env python3
-"""Contract-first checks for the Phase 2 RTL and verification boundary."""
+"""Contract-first checks for door-percent RTL and verification boundary."""
 
 from __future__ import annotations
 
@@ -24,12 +24,13 @@ ACTIVE_LEGACY_SCAN_PATHS = (
     "src/generated/td-source-manifest.json",
     "src/modules/output_target_ram.v",
     "src/modules/pwm_scheduler.v",
-    "src/modules/door_motor_engine.v",
+    "src/modules/door_percent_planner.v",
+    "src/modules/door_motion_controller.v",
     "src/project/command_controller.v",
     "src/project/project_adapter.v",
     "src/top/prod2u_p4_normal_v3_top.v",
     "tests/sim/pwm_scheduler_tb.v",
-    "tests/sim/door_motor_engine_tb.v",
+    "tests/sim/door_percent_planner_tb.v",
     "tests/sim/prod2u_p4_normal_v3_top_tb.v",
     "tests/formal/simple_frame_contract_formal.v",
     "tests/formal/simple_motor_temperature_contract_formal.v",
@@ -47,6 +48,7 @@ LEGACY_MARKERS = (
     re.compile(r"\b0x1a\b", re.IGNORECASE),
     re.compile(r"\bintake_solenoid\b", re.IGNORECASE),
     re.compile(r"\bmotor_compat\b", re.IGNORECASE),
+    re.compile(r"\bP4_FIXED_MOTOR_STEPS\b"),
 )
 
 
@@ -73,7 +75,7 @@ def _flattened_top_level_io_bits(source: str) -> int:
 
 
 class Phase2ContractTests(unittest.TestCase):
-    def test_project_contract_has_exact_phase2_values(self):
+    def test_project_contract_has_exact_percent_values(self):
         project = load_project(PROJECT_PATH)
         outputs = project["outputs"]
         motors = project["motors"]
@@ -84,17 +86,17 @@ class Phase2ContractTests(unittest.TestCase):
         self.assertEqual(outputs["pwm_phase_count"], 100)
         self.assertEqual(outputs["pwm_slot_clks"], 1042)
         self.assertAlmostEqual(outputs["pwm_actual_frequency_hz"], 19.993602047, places=9)
-        self.assertEqual(motors["fixed_steps"], 450)
+        self.assertEqual(motors["positioning"]["mode"], "percent_close")
+        self.assertEqual(motors["positioning"]["percent_max"], 100)
         self.assertEqual(motors["execution"], "overlap")
-        self.assertEqual(motors["command_values"], [0, 1, 2])
+        self.assertNotIn("fixed_steps", motors)
+        self.assertNotIn("command_values", motors)
         self.assertEqual(protocol["set_all"]["payload_length"], 11)
-        self.assertEqual(protocol["set_all"]["fan_offset"], 0)
-        self.assertEqual(protocol["set_all"]["chamber_ptc_offset"], 4)
-        self.assertEqual(protocol["set_all"]["z_door_offset"], 8)
-        self.assertEqual(protocol["set_all"]["exhaust_x_offset"], 9)
-        self.assertEqual(protocol["set_all"]["exhaust_y_offset"], 10)
+        self.assertEqual(protocol["commands"]["get_motor_status"], 3)
+        self.assertEqual(protocol["commands"]["motor_status_data"], 0x83)
         self.assertEqual(project["doors"]["door_axes"], ["x", "y", "z"])
         self.assertEqual(project["motors"]["count"], 3)
+        self.assertEqual(project["watchdog"]["timeout_ticks"], 60000)
 
     def test_active_interface_matches_project_manifest_and_adc(self):
         project = load_project(PROJECT_PATH)
@@ -110,38 +112,22 @@ class Phase2ContractTests(unittest.TestCase):
         )
         self.assertEqual(tuple((signal.strip(), ball) for signal, ball in assignments), expected_interface)
         self.assertEqual(len(assignments), 30)
-        self.assertEqual(len({ball for _, ball in assignments}), 30)
-        self.assertNotRegex(ADC_PATH.read_text(encoding="ascii"), r"(?i)ground|intake_solenoid|ptc9")
 
     def test_top_has_30_flattened_io_bits_and_three_axis_ports(self):
         source = TOP_PATH.read_text(encoding="ascii")
-        declaration = re.search(
-            r"module\s+prod2u_p4_normal_v3_top\s*\((.*?)\);",
-            source,
-            flags=re.DOTALL,
-        )
-        self.assertIsNotNone(declaration)
-        ports = declaration.group(1)
         self.assertEqual(_flattened_top_level_io_bits(source), 30)
-        expected = (
-            "sys_clk", "host_uart_rx", "host_uart_tx", "ptc_pwm_out",
-            "fan_pwm_out", "motor_en_n", "x_step", "x_dir", "y_step", "y_dir",
-            "z_step", "z_dir",
-            "x_limit_ls", "x_limit_hs", "y_limit_ls", "y_limit_hs",
-            "z_limit_ls", "z_limit_hs", "temp_scl", "temp_sda",
-        )
-        for port in expected:
-            self.assertRegex(ports, rf"\b{re.escape(port)}\b")
-        self.assertNotIn("intake_solenoid_out", ports)
+        for port in (
+            "z_step", "z_dir", "x_limit_ls", "y_limit_hs", "z_limit_ls", "motor_en_n",
+        ):
+            self.assertIn(port, source)
 
     def test_all_source_lists_register_tick_watchdog_and_match(self):
         manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
         manifest_sources = tuple(manifest["sources"])
         self.assertEqual(manifest_sources, tuple(PRODUCTION_RTL_SOURCES))
-        self.assertEqual(len(manifest_sources), len(set(manifest_sources)))
-        self.assertTrue(any("tick" in Path(path).stem.lower() for path in manifest_sources))
+        self.assertIn("src/modules/door_percent_planner.v", manifest_sources)
+        self.assertIn("src/modules/door_motion_controller.v", manifest_sources)
         self.assertTrue(any("watchdog" in Path(path).stem.lower() for path in manifest_sources))
-
         tree = ET.parse(ROOT / "td" / "prod2u_p4_normal_v3.prj")
         project_sources = tuple(
             str(node.get("Path", "")).removeprefix("../")
@@ -152,22 +138,17 @@ class Phase2ContractTests(unittest.TestCase):
         analyzed = tuple(re.findall(r"^analyze -file \{([^}]+)\}$", syn, flags=re.MULTILINE))
         self.assertEqual(analyzed, manifest_sources)
 
-    def test_phase2_rtl_contains_atomic_commit_busy_and_motor_contracts(self):
-        ram = _read("src/modules/output_target_ram.v")
-        scheduler = _read("src/modules/pwm_scheduler.v")
+    def test_phase2_rtl_contains_percent_and_status_contracts(self):
         controller = _read("src/project/command_controller.v")
-        motor = _read("src/modules/door_motor_engine.v")
-        self.assertRegex(ram, r"\bcommit\b")
-        self.assertRegex(ram, r"shadow|active", re.IGNORECASE)
-        self.assertRegex(scheduler, r"logical_pwm_on")
-        self.assertRegex(scheduler, r"phase_count|PWM_PHASE_COUNT", re.IGNORECASE)
-        self.assertRegex(scheduler, r"duty\s*>\s*phase|selected.*>.*phase", re.IGNORECASE)
-        self.assertRegex(controller, r"valid_set_all_commit")
-        self.assertRegex(controller, r"busy")
-        self.assertNotRegex(controller, r"24\s*\+\s*output_index")
-        for signal in ("active_mask", "dir_mask", "tick_500us", "abort"):
-            self.assertRegex(motor, rf"\b{signal}\b")
-        self.assertRegex(motor, r"450|MAX_STEPS|step_count")
+        planner = _read("src/modules/door_percent_planner.v")
+        motion = _read("src/modules/door_motion_controller.v")
+        self.assertIn("motor_request_valid", controller)
+        self.assertIn("door_percent_z", controller)
+        self.assertIn("GET_MOTOR_STATUS", controller.upper().replace("CMD_", ""))
+        self.assertIn("status_capture", controller)
+        self.assertIn("acc <= 8'd50", planner)
+        self.assertIn("startup_complete", motion)
+        self.assertIn("snap[0]", motion)
 
     def test_generated_outputs_are_byte_for_byte_deterministic(self):
         with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
@@ -202,6 +183,7 @@ class Phase2ContractTests(unittest.TestCase):
             "tests/formal/simple_motor_temperature_contract.sby",
             "tests/formal/pwm_scheduler_contract.sby",
             "tests/formal/host_watchdog_contract.sby",
+            "tests/formal/door_percent_planner.sby",
         ):
             source = _read(relative)
             self.assertIn("proc", source, relative)
@@ -209,77 +191,37 @@ class Phase2ContractTests(unittest.TestCase):
 
     def test_formal_wrappers_use_real_clock_reset_and_controlled_inputs(self):
         for path in sorted((ROOT / "tests/formal").glob("*_formal.v")):
-            source = path.read_text(encoding="ascii")
+            source = path.read_text(encoding="utf-8", errors="replace")
             with self.subTest(path=path.name):
                 self.assertRegex(source, r"input\s+wire\s+clk\b")
                 self.assertRegex(source, r"input\s+wire\s+rst_n\b")
                 self.assertRegex(source, r"always\s*@\(posedge\s+clk\)")
                 self.assertRegex(source, r"assume\s*\(")
-                self.assertNotRegex(source, r"reg\s+clk\b|reg\s+rst_n\b")
-
-    def test_formal_wrappers_separate_parameterized_proof_from_production_boundaries(self):
-        sources = "\n".join(
-            path.read_text(encoding="ascii")
-            for path in sorted((ROOT / "tests/formal").glob("*_formal.v"))
-        )
-        self.assertIn("FORMAL_MAX_STEPS", sources)
-        self.assertIn("FORMAL_PWM_PHASE_COUNT", sources)
-        self.assertIn("FORMAL_PWM_SLOT_CLKS", sources)
-        self.assertIn("FORMAL_TIMEOUT_TICKS", sources)
-        self.assertNotIn("MAX_STEPS(450)", sources)
-        self.assertNotIn("PWM_PHASE_COUNT(100)", sources)
-        self.assertNotIn("PWM_SLOT_CLKS(1042)", sources)
-        self.assertNotIn("TIMEOUT_TICKS(20000)", sources)
-
-        motor = _read("tests/formal/simple_motor_temperature_contract_formal.v")
-        pwm = _read("tests/formal/pwm_scheduler_contract_formal.v")
-        watchdog = _read("tests/formal/host_watchdog_contract_formal.v")
-        self.assertRegex(motor, r"\.MAX_STEPS\(FORMAL_MAX_STEPS\)")
-        self.assertRegex(pwm, r"\.PWM_PHASE_COUNT\(FORMAL_PWM_PHASE_COUNT\)")
-        self.assertRegex(pwm, r"\.PWM_SLOT_CLKS\(FORMAL_PWM_SLOT_CLKS\)")
-        self.assertRegex(watchdog, r"\.TIMEOUT_TICKS\(FORMAL_TIMEOUT_TICKS\)")
-
-    def test_simple_frame_formal_has_reachable_frame_stimulus(self):
-        source = _read("tests/formal/simple_frame_contract_formal.v")
-        self.assertIn("SCENARIO_VALID", source)
-        self.assertIn("SCENARIO_BAD_CRC", source)
-        self.assertIn("stream_index", source)
-        self.assertIn("payload_value", source)
-        self.assertIn("frame_valid", source)
-        self.assertNotIn("assume (byte_valid == 1'b0)", source)
-        self.assertNotIn("assume (byte_data == 8'h00)", source)
-        self.assertNotIn("assume (accept_enable == 1'b1)", source)
 
-    def test_production_boundary_sim_fixtures_cover_pwm_latency_motor_and_watchdog(self):
-        motor = _read("tests/sim/door_motor_engine_tb.v")
+    def test_production_boundary_sim_fixtures_cover_planner_and_watchdog(self):
+        planner = _read("tests/sim/door_percent_planner_tb.v")
         watchdog = _read("tests/sim/host_watchdog_tb.v")
         pwm = _read("tests/sim/pwm_scheduler_tb.v")
-        self.assertIn("HOST_STEPS = 450", motor)
-        self.assertIn("x_rises !== HOST_STEPS", motor)
-        self.assertIn("y_rises !== HOST_STEPS", motor)
+        self.assertIn("run_case(13'd100, 8'd50, 13'd50)", planner)
         self.assertIn(".TIMEOUT_TICKS(20000)", watchdog)
+        self.assertIn(".enable(enable)", watchdog)
         self.assertIn("19999", watchdog)
-        self.assertIn("20000", watchdog)
         self.assertRegex(pwm, r"one[- ]cycle|latency|registered", re.IGNORECASE)
 
-    def test_formal_properties_cover_phase2_safety_contract(self):
+    def test_formal_properties_cover_percent_safety_contract(self):
         sources = "\n".join(
-            path.read_text(encoding="ascii")
+            path.read_text(encoding="utf-8", errors="replace")
             for path in sorted((ROOT / "tests/formal").glob("*_formal.v"))
         )
         for marker in (
             "bad_crc",
             "wrong_length",
             "unknown_type",
-            "valid_set_all_commit",
             "watchdog",
-            "active_mask",
-            "dir_mask",
-            "step",
-            "WATCHDOG_PTC_TARGET",
+            "door_percent_planner",
             "WATCHDOG_FAN_TARGET",
-            "byte_ready",
-            "payload_index",
+            "gated_step",
+            "selected_limit",
         ):
             self.assertIn(marker, sources)
 

+ 50 - 205
tests/unit/test_phase3_formal_contract.py

@@ -1,225 +1,70 @@
 #!/usr/bin/env python3
-"""Static contract checks for the Phase 3 formal harness quality boundary."""
+"""Formal / sim contract checks for door-percent motion stack."""
 
 from __future__ import annotations
 
 import json
-import os
-import re
 import unittest
-from collections.abc import Mapping
 from pathlib import Path
 
+from tools.prod2u_p4_harness import load_target_manifest
 
 ROOT = Path(__file__).resolve().parents[2]
-FORMAL_ROOT = ROOT / "tests" / "formal"
-
-
-def _formal_receipt_evidence_failures(receipt: Mapping[str, object]) -> list[str]:
-    failures: list[str] = []
-    if receipt.get("status") != "pass":
-        failures.append("receipt_status_not_pass")
-
-    targets = receipt.get("targets")
-    if not isinstance(targets, list):
-        return failures + ["targets_missing_or_invalid"]
-
-    for target_index, target in enumerate(targets):
-        prefix = f"targets[{target_index}]"
-        if not isinstance(target, Mapping):
-            failures.append(f"{prefix}_invalid")
-            continue
-        if target.get("status") != "pass":
-            failures.append(f"{prefix}_status_not_pass")
-
-        task_results = target.get("task_results")
-        if not isinstance(task_results, list):
-            failures.append(f"{prefix}.task_results_missing_or_invalid")
-        else:
-            for task_index, task in enumerate(task_results):
-                task_prefix = f"{prefix}.task_results[{task_index}]"
-                if not isinstance(task, Mapping):
-                    failures.append(f"{task_prefix}_invalid")
-                    continue
-                if task.get("status") != "PASS":
-                    failures.append(f"{task_prefix}_status_not_PASS")
-                if not task.get("compiled_assertion_ids"):
-                    failures.append(f"{task_prefix}_compiled_assertion_ids_missing")
-
-        if target.get("cover_required"):
-            trace_files = target.get("trace_files")
-            if not isinstance(trace_files, list):
-                failures.append(f"{prefix}.trace_files_missing_or_invalid")
-                trace_files = []
-            cover_hit_count = target.get("cover_hit_count")
-            if not isinstance(cover_hit_count, int) or cover_hit_count <= 0:
-                failures.append(f"{prefix}_cover_hit_count_invalid")
-            elif cover_hit_count != len(trace_files):
-                failures.append(f"{prefix}_cover_trace_count_mismatch")
-            for trace_index, trace_path in enumerate(trace_files):
-                if not isinstance(trace_path, str) or not Path(trace_path).exists():
-                    failures.append(f"{prefix}.trace_files[{trace_index}]_missing")
-
-    return failures
 
 
 def _read(relative: str) -> str:
-    return (ROOT / relative).read_text(encoding="ascii")
+    return (ROOT / relative).read_text(encoding="utf-8", errors="replace")
 
 
 class Phase3FormalContractTests(unittest.TestCase):
-    def test_formal_scripts_zero_undefined_values(self):
-        for path in sorted(FORMAL_ROOT.glob("*.sby")):
-            source = path.read_text(encoding="ascii")
-            with self.subTest(path=path.name):
-                self.assertIn("setundef -zero", source)
-                self.assertNotIn("setundef -anyseq", source)
-
-    def test_startup_and_runtime_limit_formal_assert_runtime_hard_stop(self):
-        startup = _read("tests/formal/startup_close_seek_formal.v")
-        runtime = _read("tests/formal/runtime_limit_hard_stop_formal.v")
-        self.assertRegex(startup, r"assert\s*\(\s*motor_stop_mask\s*==\s*3'b000\s*\)")
-        self.assertRegex(startup, r"\$past\(startup_done\)")
-        self.assertIn("startup_done ? runtime_limit_stop_mask", runtime)
-        self.assertRegex(runtime, r"assert\s*\(\s*motor_stop_mask\s*==\s*runtime_limit_stop_mask\s*\)")
-        sby = _read("tests/formal/runtime_limit_hard_stop.sby")
-        self.assertIn("mode bmc", sby)
-        self.assertIn("setundef -zero", sby)
-        self.assertLessEqual(int(re.search(r"depth\s+(\d+)", sby).group(1)), 64)
-
-    def test_motor_wrapper_has_explicit_known_inputs_and_step_edge_model(self):
-        source = _read("tests/formal/simple_motor_temperature_contract_formal.v")
-        for signal in ("rst_n", "start", "active_mask", "dir_mask", "tick_500us", "abort"):
-            self.assertRegex(source, rf"assume\s*\([^\n]*\b{signal}\b")
-        self.assertRegex(source, r"initial\s+begin")
-        self.assertRegex(source, r"assume\s*\(!?dut_rst_n\)")
-        self.assertRegex(source, r"assume\s*\(\s*dut_rst_n\s*\)")
-        self.assertIn("previous_step", source)
-        self.assertIn("rising_edges", source)
-        self.assertIn("$past(tick_500us)", source)
-        self.assertRegex(source, r"assert\s*\([^\n]*rising_edges")
-
-    def test_watchdog_wrapper_checks_effective_target_and_next_clock_motor_abort(self):
+    def test_manifest_lists_percent_formal_and_sim_targets(self):
+        manifest = load_target_manifest()
+        icarus = set(manifest["layers"]["icarus"])
+        formal_names = {entry["name"] for entry in manifest["layers"]["formal"]}
+        self.assertIn("door_percent_planner_tb", icarus)
+        self.assertIn("door_motion_controller_tb", icarus)
+        self.assertNotIn("door_motor_engine_tb", icarus)
+        self.assertNotIn("startup_close_seek_tb", icarus)
+        self.assertIn("door_percent_planner", formal_names)
+        self.assertIn("door_axis_cal", formal_names)
+        self.assertNotIn("startup_close_seek", formal_names)
+        self.assertNotIn("door_action_dispatcher_axis3", formal_names)
+
+    def test_runtime_limit_formal_uses_hard_gate(self):
+        source = _read("tests/formal/runtime_limit_hard_stop_formal.v")
+        self.assertIn("truncate_current_high_pulse_immediately_after_synchronized_limit", source)
+        self.assertIn("gated_step", source)
+        self.assertIn("selected_limit", source)
+        self.assertNotIn("door_motor_engine", source)
+
+    def test_planner_formal_and_sby_exist(self):
+        self.assertTrue((ROOT / "tests/formal/door_percent_planner_formal.v").is_file())
+        self.assertTrue((ROOT / "tests/formal/door_percent_planner.sby").is_file())
+        formal = _read("tests/formal/door_percent_planner_formal.v")
+        self.assertIn("door_percent_planner", formal)
+        self.assertIn("assert", formal)
+
+    def test_watchdog_formal_has_enable_and_fan10(self):
         source = _read("tests/formal/host_watchdog_contract_formal.v")
-        self.assertIn("output_target_ram", source)
-        self.assertIn("door_motor_engine", source)
-        self.assertIn("WATCHDOG_PTC_TARGET", source)
-        self.assertIn("WATCHDOG_FAN_TARGET", source)
-        self.assertIn("timeout_seen", source)
-        self.assertRegex(source, r"assert\s*\([^\n]*step[^\n]*2'b00")
-        self.assertRegex(source, r"assert\s*\([^\n]*WATCHDOG_(?:PTC|FAN)_TARGET")
-
-    def test_frame_command_wrapper_checks_invalid_get_feed_and_commit_invariants(self):
-        source = _read("tests/formal/frame_command_contract_formal.v")
-        for marker in (
-            "SCENARIO_BAD_OUTPUT",
-            "SCENARIO_BAD_MOTOR",
-            "target_wr_en",
-            "temperature_start",
-            "tx_start",
-            "motor_start",
-            "valid_set_all_commit",
-            "invalid_frame",
-            "byte_valid",
-        ):
-            self.assertIn(marker, source)
-        self.assertRegex(source, r"assert\s*\([^\n]*invalid_frame")
-        self.assertRegex(source, r"if\s*\(get_temperature\)")
-        self.assertRegex(source, r"assert\s*\([^\n]*valid_set_all_commit")
-
-    def test_frame_tx_wrapper_checks_accepted_byte_progression_without_duplicates(self):
-        sby = _read("tests/formal/frame_tx_contract.sby")
-        self.assertIn("mode bmc", sby)
-        self.assertRegex(sby, r"(?m)^bmc\s*$")
-        self.assertNotRegex(sby, r"(?m)^prove\s*$")
-        # BMC depth kept at 64 for host-feasible closed-loop runs (Mem≈2GiB);
-        # assertions themselves are unchanged. Prefer bitwuzla when available.
-        depth_match = re.search(r"(?m)^depth\s+(\d+)\s*$", sby)
-        self.assertIsNotNone(depth_match, "frame_tx_contract.sby missing depth")
-        self.assertEqual(int(depth_match.group(1)), 64)
-        self.assertIn("smtbmc bitwuzla", sby)
-        source = _read("tests/formal/frame_tx_contract_formal.v")
-        for marker in (
-            "accepted_byte_count",
-            "expected_frame_byte",
-            "duplicate",
-            "$past(byte_valid && byte_ready)",
-            "byte_valid && byte_ready",
-        ):
-            self.assertIn(marker, source)
-        self.assertRegex(source, r"assert\s*\([^\n]*byte_data")
-        self.assertRegex(source, r"assert\s*\([^\n]*accepted_byte_count")
-
-    def test_bmc_targets_name_tasks_bmc_not_prove(self):
-        """Receipt honesty: BMC .sby tasks must not be labeled prove."""
-        for relative in (
-            "tests/formal/frame_command_contract.sby",
-            "tests/formal/frame_tx_contract.sby",
-            "tests/formal/simple_frame_contract.sby",
-            "tests/formal/startup_close_seek.sby",
-            "tests/formal/runtime_limit_hard_stop.sby",
-            "tests/formal/door_action_dispatcher_axis3.sby",
-        ):
-            sby = _read(relative)
-            with self.subTest(relative=relative):
-                self.assertIn("mode bmc", sby)
-                self.assertRegex(sby, r"(?m)^bmc\s*$")
-                self.assertNotRegex(sby, r"(?m)^prove\s*$")
-
-    def test_priority_formal_targets_require_cover_nonvacuity(self):
-        for relative in (
-            "tests/formal/startup_close_seek.sby",
-            "tests/formal/runtime_limit_hard_stop.sby",
-            "tests/formal/simple_frame_contract.sby",
-            "tests/formal/door_action_dispatcher_axis3.sby",
-        ):
-            sby = _read(relative)
-            with self.subTest(relative=relative):
-                self.assertRegex(sby, r"(?m)^cover\s*$")
-                self.assertIn("mode cover", sby)
-        # frame_command keeps cover() in the wrapper for non-vacuity review, but the
-        # registered sby task stays BMC-only on low-memory hosts (depth-96 cover OOMs).
-        self.assertIn("cover (", _read("tests/formal/frame_command_contract_formal.v"))
-        frame_cmd = _read("tests/formal/frame_command_contract.sby")
-        self.assertRegex(frame_cmd, r"(?m)^bmc\s*$")
-        self.assertNotRegex(frame_cmd, r"(?m)^cover\s*$")
-    def test_formal_wrappers_have_real_stimulus_and_no_vacuous_constant_inputs(self):
-        source = _read("tests/formal/simple_frame_contract_formal.v")
-        self.assertIn("SCENARIO_VALID", source)
-        self.assertIn("SCENARIO_BAD_CRC", source)
-        self.assertIn("stream_index", source)
-        self.assertIn("payload_value", source)
-        self.assertNotIn("assume (byte_valid == 1'b0)", source)
-        self.assertNotIn("assume (byte_data == 8'h00)", source)
-        self.assertNotIn("assume (accept_enable == 1'b1)", source)
-
-    def test_cocotb_cleans_clock_and_observer_tasks_with_stage_timeouts(self):
-        source = _read("tests/cocotb/test_prod2u_door_temp_uart_e2e.py")
-        self.assertIn("try:", source)
-        self.assertIn("finally:", source)
-        self.assertRegex(source, r"\.kill\(\)|\.cancel\(\)")
-        self.assertIn("stage=", source)
-        self.assertIn("byte_index=", source)
-
-    def test_simulation_fixtures_cover_production_timeout_and_motor_boundaries(self):
-        motor = _read("tests/sim/door_motor_engine_tb.v")
-        watchdog = _read("tests/sim/host_watchdog_tb.v")
-        self.assertIn("HOST_STEPS = 450", motor)
-        self.assertIn("x_rises !== HOST_STEPS", motor)
-        self.assertIn("y_rises !== HOST_STEPS", motor)
-        self.assertIn(".TIMEOUT_TICKS(20000)", watchdog)
-        self.assertIn("19999", watchdog)
-        self.assertIn("20000", watchdog)
-
-    def test_formal_receipt_runtime_evidence_contract(self):
-        raw_path = os.environ.get("PROD2U_FORMAL_RECEIPT")
-        if not raw_path:
-            self.skipTest("PROD2U_FORMAL_RECEIPT is not set; no formal receipt to verify")
-        receipt_path = Path(raw_path).expanduser()
-        self.assertTrue(receipt_path.is_file(), f"formal receipt is missing: {receipt_path}")
-        receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
-        failures = _formal_receipt_evidence_failures(receipt)
-        self.assertEqual([], failures, "\n".join(failures))
+        sby = _read("tests/formal/host_watchdog_contract.sby")
+        self.assertIn(".enable(enable)", source)
+        self.assertIn("WATCHDOG_FAN_TARGET = 8'd10", source)
+        self.assertNotIn("door_motor_engine", sby)
+
+    def test_top_sim_targets_use_startup_complete(self):
+        startup = _read("tests/sim/prod2u_p4_normal_v3_top_startup_tb.v")
+        runtime = _read("tests/sim/prod2u_p4_normal_v3_top_runtime_limit_tb.v")
+        self.assertIn("startup_complete", startup)
+        self.assertNotIn("startup_done", startup)
+        self.assertIn("gated STEP", runtime.lower() + runtime)
+        self.assertIn("engine_step", runtime)
+
+    def test_unit_manifest_includes_exhaustive_planner(self):
+        manifest = load_target_manifest()
+        self.assertIn(
+            "tests.unit.test_door_percent_planner_exhaustive",
+            manifest["layers"]["unit"],
+        )
 
 
 if __name__ == "__main__":

+ 34 - 132
tests/unit/test_product_contract_coverage.py

@@ -1,160 +1,62 @@
 #!/usr/bin/env python3
-"""Static product-contract coverage gates for the 3-axis six-limit SET_ALL profile."""
+"""Coverage gates: percent motion sim/formal targets exist and mention contract."""
 
 from __future__ import annotations
 
-import json
-import re
 import unittest
 from pathlib import Path
 
-from tools.prod2u_simple_protocol import (
-    FrameType,
-    build_get_temperature,
-    build_set_all,
-    build_temperature_data,
-    decode_frame,
-    decode_temperature_data,
-)
-
+from tools.prod2u_p4_harness import load_target_manifest
 
 ROOT = Path(__file__).resolve().parents[2]
-MANIFEST_PATH = ROOT / "config" / "prod2u_p4_verification_targets_v1.json"
 
 
 def _read(relative: str) -> str:
-    return (ROOT / relative).read_text(encoding="utf-8")
+    return (ROOT / relative).read_text(encoding="utf-8", errors="replace")
 
 
 class ProductContractCoverageTests(unittest.TestCase):
-    def test_protocol_set_all_is_exactly_11_bytes_with_golden_crc(self):
-        zero = bytes.fromhex("A55A010B00000000000000000000005873")
-        mixed = bytes.fromhex("A55A010B0A141E280019326401020087D5")
-        self.assertEqual(build_set_all([0] * 4, [0] * 4, 0, 0, 0), zero)
-        self.assertEqual(build_set_all((10, 20, 30, 40), (0, 25, 50, 100), 1, 2, 0), mixed)
-        self.assertEqual(len(decode_frame(zero).payload), 11)
-        self.assertEqual(decode_frame(mixed).frame_type, FrameType.SET_ALL)
-
-    def test_temperature_contract_is_exactly_27_values_and_33_byte_frame(self):
-        self.assertEqual(build_get_temperature().hex(" ").upper(), "A5 5A 02 00 6D 7B")
-        values = tuple(range(27))
-        raw = build_temperature_data(values)
-        self.assertEqual(len(raw), 33)
-        self.assertEqual(raw[2], 0x82)
-        self.assertEqual(raw[3], 27)
-        self.assertEqual(decode_temperature_data(decode_frame(raw)), values)
-
-    def test_project_adapter_tb_covers_atomicity_ptc_duplicate_dir_and_busy_ignore(self):
-        source = _read("tests/sim/project_adapter_tb.v")
+    def test_planner_tb_covers_half_up_samples(self):
+        planner = _read("tests/sim/door_percent_planner_tb.v")
         for marker in (
-            "chamber0 PTC duplicate",
-            "FAN target mapping mismatch",
-            "open DIR contract",
-            "close/open DIR contract",
-            "busy must ignore",
-            "invalid door broke SET_ALL atomicity",
-            "legacy 14-byte frame must be rejected",
-            "submit_frame(8'h01, 11)",
-            "AXIS_COUNT(3)",
+            "run_case(13'd100, 8'd50, 13'd50)",
+            "run_case(13'd3, 8'd50, 13'd2)",
+            "run_case(13'd5000, 8'd50, 13'd2500)",
         ):
-            self.assertIn(marker, source)
+            self.assertIn(marker, planner)
 
-    def test_motor_and_dispatcher_tb_cover_dir_450_and_busy_ignore(self):
-        motor = _read("tests/sim/door_motor_engine_tb.v")
-        dispatcher = _read("tests/sim/door_action_dispatcher_tb.v")
-        for marker in (
-            "HOST_STEPS = 450",
-            "mixed DIR not latched",
-            "busy must ignore",
-            "AXIS_COUNT = 3",
-        ):
-            self.assertIn(marker, motor)
-        for marker in (
-            "open all mask/dir",
-            "close all mask/dir",
-            "busy must ignore",
-            "OPEN_DIR(0)",
-            "CLOSE_DIR(1)",
-            "z_door_cmd",
-        ):
-            self.assertIn(marker, dispatcher)
+    def test_motion_tb_covers_startup_and_snapshot(self):
+        motion = _read("tests/sim/door_motion_controller_tb.v")
+        self.assertIn("startup_complete", motion)
+        self.assertIn("status byte0", motion.lower() + motion)
+        self.assertIn("8'h47", motion)
 
-    def test_startup_and_runtime_limit_cover_close_backoff_and_hard_stop(self):
-        startup = _read("tests/sim/startup_close_seek_tb.v")
+    def test_runtime_limit_and_cal_cover_hard_stop(self):
         runtime = _read("tests/sim/prod2u_p4_normal_v3_top_runtime_limit_tb.v")
-        formal = _read("tests/formal/startup_close_seek_formal.v")
-        mux = _read("tests/formal/runtime_limit_hard_stop_formal.v")
-        self.assertIn("post-done limit toggle", startup)
-        self.assertIn("runtime LS stop failed", runtime)
-        self.assertIn("runtime HS stop failed", runtime)
-        self.assertRegex(formal, r"assert\s*\(\s*motor_stop_mask\s*==\s*3'b000\s*\)")
-        self.assertRegex(formal, r"assert\s*\(\s*startup_done\s*\)")
-        self.assertIn("startup_done ? runtime_limit_stop_mask", mux)
-        self.assertRegex(mux, r"assert\s*\(\s*motor_stop_mask\s*==\s*runtime_limit_stop_mask\s*\)")
-
-    def test_cocotb_checks_dir_semantics_six_limits_and_en_permanent_high(self):
-        source = _read("tests/cocotb/test_prod2u_door_temp_uart_e2e.py")
-        self.assertIn("DIR=0 (open)", source)
-        self.assertIn("DIR=1 (close)", source)
-        self.assertIn("MOTOR_STEPS = 450", source)
-        self.assertIn("TEMPERATURE_DATA, 27", source)
-        self.assertIn("z_limit_ls", source)
-        self.assertIn("motor_en_n.value) == 1", source)
-
-    def test_manifest_lists_new_contract_targets(self):
-        manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
+        formal = _read("tests/formal/runtime_limit_hard_stop_formal.v")
+        self.assertIn("truncate", runtime.lower() + formal.lower())
+        self.assertIn("selected_limit", formal)
+        self.assertIn("gated_step", formal)
+
+    def test_manifest_names_match_files(self):
+        manifest = load_target_manifest()
+        for name in manifest["layers"]["icarus"]:
+            path = ROOT / "tests" / "sim" / f"{name}.v"
+            self.assertTrue(path.is_file(), name)
+        for entry in manifest["layers"]["formal"]:
+            path = ROOT / "tests" / "formal" / f"{entry['name']}.sby"
+            self.assertTrue(path.is_file(), entry["name"])
+
+    def test_no_legacy_jog_tb_in_manifest(self):
+        manifest = load_target_manifest()
         icarus = set(manifest["layers"]["icarus"])
-        formal_names = {entry["name"] for entry in manifest["layers"]["formal"]}
-        unit = set(manifest["layers"]["unit"])
-        required_icarus = {
-            "project_adapter_tb",
-            "output_target_ram_tb",
+        for banned in (
             "door_motor_engine_tb",
             "door_action_dispatcher_tb",
-            "frame_rx_tb",
             "startup_close_seek_tb",
-            "prod2u_p4_normal_v3_top_runtime_limit_tb",
-            "temperature_reader_tb",
-            "host_watchdog_tb",
-        }
-        gaps: list[str] = []
-        missing_icarus = sorted(required_icarus - icarus)
-        if missing_icarus:
-            gaps.append(f"icarus:{missing_icarus}")
-        if "runtime_limit_hard_stop" not in formal_names:
-            gaps.append("formal:runtime_limit_hard_stop")
-        if "startup_close_seek" not in formal_names:
-            gaps.append("formal:startup_close_seek")
-        if "door_action_dispatcher_axis3" not in formal_names:
-            gaps.append("formal:door_action_dispatcher_axis3")
-        if "tests.unit.test_three_axis_door_contract" not in unit:
-            gaps.append("unit:tests.unit.test_three_axis_door_contract")
-        forbidden_icarus = {
-            "intake_solenoid_adapter_tb",
-            "project_adapter_motor_compat_tb",
-            "door_action_dispatcher_axis3_tb",
-            "door_motor_engine_axis3_tb",
-            "startup_close_seek_axis3_tb",
-        }
-        if icarus & forbidden_icarus:
-            gaps.append(f"icarus:obsolete:{sorted(icarus & forbidden_icarus)}")
-        formal_by_name = {entry["name"]: entry for entry in manifest["layers"]["formal"]}
-        for cover_name in (
-            "startup_close_seek",
-            "runtime_limit_hard_stop",
-            "simple_frame_contract",
-            "door_action_dispatcher_axis3",
+            "startup_motor_stop_tb",
         ):
-            if "cover" not in formal_by_name[cover_name]["tasks"]:
-                gaps.append(f"formal:{cover_name}:missing_cover_task")
-        self.assertEqual(gaps, [], "verification manifest gaps: " + "; ".join(gaps))
-
-    def test_dispatcher_formal_covers_z_axis_and_busy_ignore(self):
-        formal = _read("tests/formal/door_action_dispatcher_axis3_formal.v")
-        self.assertIn("cover", formal)
-        self.assertIn("AXIS_COUNT(3)", formal)
-        self.assertIn("z_door_cmd", formal)
-        self.assertIn("motor_busy", formal)
+            self.assertNotIn(banned, icarus)
 
 
 if __name__ == "__main__":

+ 7 - 4
tests/unit/test_project_config.py

@@ -45,8 +45,9 @@ class ProjectConfigTests(unittest.TestCase):
             ["FAN_PWM3", "FAN_PWM1", "FAN_PWM2", "FAN_PWM4"],
         )
         self.assertEqual(project["motors"]["execution"], "overlap")
-        self.assertGreaterEqual(project["motors"]["busy_wait_ms"], 600)
-        self.assertEqual(project["motors"]["fixed_steps"], 450)
+        self.assertEqual(project["motors"]["positioning"]["mode"], "percent_close")
+        self.assertEqual(project["motors"]["positioning"]["percent_max"], 100)
+        self.assertNotIn("fixed_steps", project["motors"])
         self.assertEqual(project["temperature"]["value_count"], 27)
         self.assertEqual(
             project["pins"]["fan_pwm"],
@@ -62,7 +63,7 @@ class ProjectConfigTests(unittest.TestCase):
                 "temperature_ram",
                 "dsp",
                 "shared_pwm_comparators",
-                "shared_motor_executors",
+                "shared_percent_planner",
                 "shared_i2c_readers",
             },
         )
@@ -72,7 +73,7 @@ class ProjectConfigTests(unittest.TestCase):
             all(
                 isinstance(project["resource_policy"][key], int)
                 and project["resource_policy"][key] >= 0
-                for key in ("dsp", "shared_pwm_comparators", "shared_motor_executors", "shared_i2c_readers")
+                for key in ("dsp", "shared_pwm_comparators", "shared_percent_planner", "shared_i2c_readers")
             )
         )
 
@@ -81,7 +82,9 @@ class ProjectConfigTests(unittest.TestCase):
         self.assertEqual(project["protocol"]["commands"], {
             "set_all": 0x01,
             "get_temperature": 0x02,
+            "get_motor_status": 0x03,
             "temperature_data": 0x82,
+            "motor_status_data": 0x83,
         })
         self.assertEqual(project["protocol"]["crc"]["polynomial"], 0x1021)
 

+ 20 - 37
tests/unit/test_project_generation.py

@@ -18,8 +18,8 @@ class ProjectGenerationTests(unittest.TestCase):
             second = Path(directory) / "second"
             generate_project(PROJECT, first)
             generate_project(PROJECT, second)
-            first_files = sorted(path.relative_to(first) for path in first.rglob("*" ) if path.is_file())
-            second_files = sorted(path.relative_to(second) for path in second.rglob("*" ) if path.is_file())
+            first_files = sorted(path.relative_to(first) for path in first.rglob("*") if path.is_file())
+            second_files = sorted(path.relative_to(second) for path in second.rglob("*") if path.is_file())
             self.assertEqual(first_files, second_files)
             for relative in first_files:
                 self.assertEqual(
@@ -29,56 +29,39 @@ class ProjectGenerationTests(unittest.TestCase):
             params = (first / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
             self.assertIn("P4_PTC_COUNT 8", params)
             self.assertIn("P4_FAN_COUNT 4", params)
-            self.assertIn("P4_OUTPUT_CHANNEL_COUNT 12", params)
             self.assertIn("P4_UART_CLKS_PER_BIT 217", params)
-            self.assertIn("P4_TEMP_DEVICE_ADDR_0 7'h49", params)
-            self.assertIn("P4_TEMP_DEVICE_ADDR_1 7'h48", params)
-            self.assertIn("P4_TEMP_DEVICE_ADDR_2 7'h4B", params)
-            self.assertIn("P4_TEMP_REGISTER_8 8'h08", params)
-            self.assertIn("P4_TEMP_MAX_CELSIUS 150", params)
-            self.assertIn("P4_PTC_ACTIVE_HIGH 1", params)
-            self.assertIn("P4_FAN_ACTIVE_HIGH 0", params)
-            self.assertIn("P4_PWM_FREQUENCY_HZ 20", params)
-            self.assertIn("P4_PWM_PHASE_COUNT 100", params)
-            self.assertIn("P4_PWM_SLOT_CLKS 1042", params)
-            self.assertIn("P4_MOTOR_DIR_SETUP_TICKS 2", params)
-            self.assertIn("P4_WATCHDOG_TIMEOUT_TICKS 20000", params)
-            self.assertIn("P4_PTC_DEFAULT_TARGET 8'h00", params)
-            self.assertIn("P4_SET_ALL_PAYLOAD_LENGTH 11", params)
-            self.assertIn("P4_AXIS_COUNT 3", params)
-            self.assertIn("P4_LIMIT_COUNT 6", params)
-            self.assertIn("P4_RUNTIME_LIMIT_USE 1", params)
-            self.assertIn("P4_STARTUP_CLOSE_STEPS 5000", params)
+            self.assertIn("P4_WATCHDOG_TIMEOUT_TICKS 60000", params)
+            self.assertIn("P4_WATCHDOG_FAN_TARGET 8'h0A", params)
+            self.assertIn("P4_CAL_MAX_STEPS 5000", params)
+            self.assertIn("P4_DOOR_PERCENT_MAX 100", params)
+            self.assertIn("P4_CMD_GET_MOTOR_STATUS 8'h03", params)
+            self.assertIn("P4_RSP_MOTOR_STATUS 8'h83", params)
+            self.assertIn("P4_MOTOR_STATUS_PAYLOAD_LENGTH 31", params)
+            self.assertNotIn("P4_FIXED_MOTOR_STEPS", params)
+            self.assertNotIn("P4_STARTUP_BACKOFF_STEPS", params)
             contract = json.loads((first / "generated" / "host-contract.json").read_text(encoding="utf-8"))
             self.assertEqual(contract["commands"]["set_all"]["payload_length"], 11)
+            self.assertIn(
+                str(contract["commands"]["get_motor_status"]["type"]).lower().replace("0x", ""),
+                {"3", "03"},
+            )
             golden = json.loads((first / "generated" / "golden-vectors.json").read_text(encoding="utf-8"))
-            self.assertEqual(golden["set_all_all_zero"], "A55A010B00000000000000000000005873")
-            self.assertEqual(golden["set_all_mixed"], "A55A010B0A141E280019326401020087D5")
+            self.assertEqual(golden["set_all_all_zero_full_open"], "A55A010B00000000000000000000005873")
+            self.assertEqual(golden["set_all_doors_50_percent"], "A55A010B0A141E2800193264323232F65A")
             self.assertEqual(golden["get_temperature"], "A55A02006D7B")
-            self.assertEqual(golden["all_invalid_temperature"], "A55A821B" + "FF" * 27 + "A745")
+            self.assertEqual(golden["get_motor_status"], "A55A03005C48")
             source_manifest = json.loads(
                 (first / "generated" / "td-source-manifest.json").read_text(encoding="utf-8")
             )
             self.assertEqual(source_manifest["sources"], list(ACTIVE_SOURCE_PATHS))
-            self.assertEqual(len(source_manifest["sources"]), len(set(source_manifest["sources"])))
-            self.assertTrue(all((ROOT / source).is_file() for source in source_manifest["sources"]))
-            self.assertIn("src/common/frame_rx.v", source_manifest["sources"])
-            self.assertNotIn("src/rtl/binary921_crc16.v", source_manifest["sources"])
+            self.assertIn("src/modules/door_percent_planner.v", source_manifest["sources"])
+            self.assertNotIn("src/modules/door_motor_engine.v", source_manifest["sources"])
             summary = json.loads((first / "generated" / "project-summary.json").read_text(encoding="utf-8"))
             self.assertEqual(summary["pwm_phase_count"], 100)
-            self.assertEqual(summary["pwm_slot_clks"], 1042)
-            self.assertEqual(summary["pwm_period_clks"], 1_250_400)
             self.assertAlmostEqual(summary["actual_frequency_hz"], 19.993602047, places=9)
-
             adc = (first / "generated" / "prod2u_door_temp.adc").read_text(encoding="ascii")
             assignments = [line for line in adc.splitlines() if line.startswith("set_pin_assignment")]
             self.assertEqual(len(assignments), 30)
-            self.assertTrue(any(line.startswith("set_pin_assignment { ptc_pwm_out[0] } { LOCATION = G16;") for line in assignments))
-            self.assertTrue(any(line.startswith("set_pin_assignment { ptc_pwm_out[7] } { LOCATION = T9;") for line in assignments))
-            self.assertTrue(any(line.startswith("set_pin_assignment { fan_pwm_out[0] } { LOCATION = B1;") for line in assignments))
-            self.assertTrue(any(line.startswith("set_pin_assignment { fan_pwm_out[3] } { LOCATION = A14;") for line in assignments))
-            self.assertTrue(any(line.startswith("set_pin_assignment { z_step } { LOCATION = L14;") for line in assignments))
-            self.assertTrue(any(line.startswith("set_pin_assignment { x_limit_ls } { LOCATION = A5;") for line in assignments))
 
 
 if __name__ == "__main__":

+ 50 - 33
tests/unit/test_protocol.py

@@ -3,13 +3,16 @@ import unittest
 from tools.prod2u_simple_protocol import (
     FrameType,
     ProtocolError,
+    build_get_motor_status,
     build_get_temperature,
     build_set_all,
     build_temperature_data,
     crc16_ccitt_false,
     decode_frame,
+    decode_motor_status_data,
     decode_temperature_data,
     encode_frame,
+    mid_target,
 )
 
 
@@ -17,60 +20,76 @@ class ProtocolTests(unittest.TestCase):
     def test_get_temperature_matches_frozen_hex_vector(self):
         self.assertEqual(build_get_temperature().hex(" ").upper(), "A5 5A 02 00 6D 7B")
 
-    def test_set_all_all_zero_golden_vector(self):
+    def test_get_motor_status_golden(self):
+        self.assertEqual(build_get_motor_status().hex().upper(), "A55A03005C48")
+
+    def test_set_all_all_zero_full_open_golden(self):
         raw = bytes.fromhex("A55A010B00000000000000000000005873")
         frame = decode_frame(raw)
         self.assertEqual(frame.frame_type, FrameType.SET_ALL)
         self.assertEqual(len(frame.payload), 11)
         self.assertEqual(build_set_all([0] * 4, [0] * 4, 0, 0, 0).hex().upper(), raw.hex().upper())
 
-    def test_set_all_mixed_golden_vector(self):
-        raw = bytes.fromhex("A55A010B0A141E280019326401020087D5")
+    def test_set_all_doors_50_percent_golden(self):
+        raw = bytes.fromhex("A55A010B0A141E2800193264323232F65A")
         frame = decode_frame(raw)
-        self.assertEqual(frame.frame_type, FrameType.SET_ALL)
-        self.assertEqual(frame.payload, bytes((10, 20, 30, 40, 0, 25, 50, 100, 1, 2, 0)))
+        self.assertEqual(frame.payload, bytes((10, 20, 30, 40, 0, 25, 50, 100, 50, 50, 50)))
         self.assertEqual(
-            build_set_all((10, 20, 30, 40), (0, 25, 50, 100), 1, 2, 0).hex().upper(),
+            build_set_all((10, 20, 30, 40), (0, 25, 50, 100), 50, 50, 50).hex().upper(),
             raw.hex().upper(),
         )
 
     def test_crc_reference_matches_independent_implementation(self):
-        body = bytes((0x01, 0x0B, 10, 20, 30, 40, 0, 25, 50, 100, 1, 2, 0))
-        self.assertEqual(crc16_ccitt_false(body), 0xD587)
+        body = bytes((0x01, 0x0B, 10, 20, 30, 40, 0, 25, 50, 100, 50, 50, 50))
+        self.assertEqual(crc16_ccitt_false(body), 0x5AF6)
 
     def test_legacy_14_byte_length_is_rejected_on_decode(self):
         legacy = bytes.fromhex("A55A010E00010203040506070A141E280102B2C5")
         with self.assertRaises(ProtocolError):
             decode_frame(legacy)
 
-    def test_set_all_accepts_duty_boundaries_and_rejects_out_of_range_values(self):
-        self.assertEqual(len(build_set_all([0] * 4, [0] * 4, 0, 0, 0)), 17)
-        self.assertEqual(len(build_set_all([100] * 4, [100] * 4, 2, 2, 2)), 17)
-        for values in ([101] + [0] * 3, [-1] + [0] * 3):
-            with self.subTest(values=values[0]):
-                with self.assertRaises(ValueError):
-                    build_set_all(values, [0] * 4, 0, 0, 0)
-        for values in ([101] + [0] * 3, [-1] + [0] * 3):
-            with self.subTest(values=values[0]):
-                with self.assertRaises(ValueError):
-                    build_set_all([0] * 4, values, 0, 0, 0)
-
-    def test_door_commands_are_exactly_zero_one_or_two(self):
-        for command in (0, 1, 2):
-            with self.subTest(command=command):
-                frame = decode_frame(build_set_all([0] * 4, [0] * 4, command, command, command))
-                self.assertEqual(frame.payload[-3:], bytes((command, command, command)))
-        for command in (-1, 3):
-            with self.subTest(command=command):
-                with self.assertRaises(ValueError):
-                    build_set_all([0] * 4, [0] * 4, command, 0, 0)
+    def test_set_all_accepts_duty_and_percent_0_100(self):
+        self.assertEqual(len(build_set_all([0] * 4, [0] * 4, 0, 0, 0),), 17)
+        self.assertEqual(len(build_set_all([100] * 4, [100] * 4, 100, 100, 100)), 17)
+        for bad in (101, -1):
+            with self.assertRaises(ValueError):
+                build_set_all([bad] + [0] * 3, [0] * 4, 0, 0, 0)
+            with self.assertRaises(ValueError):
+                build_set_all([0] * 4, [0] * 4, bad, 0, 0)
+
+    def test_door_percent_range_not_jog_only(self):
+        for percent in (0, 1, 50, 99, 100):
+            frame = decode_frame(build_set_all([0] * 4, [0] * 4, percent, percent, percent))
+            self.assertEqual(frame.payload[-3:], bytes((percent, percent, percent)))
+        for percent in (-1, 101, 255):
+            with self.assertRaises(ValueError):
+                build_set_all([0] * 4, [0] * 4, percent, 0, 0)
 
     def test_temperature_response_is_exactly_33_bytes(self):
         raw = build_temperature_data([0xFF] * 27)
         self.assertEqual(len(raw), 33)
-        self.assertEqual(raw.hex(" ").upper(), "A5 5A 82 1B " + "FF " * 26 + "FF A7 45")
         self.assertEqual(decode_temperature_data(decode_frame(raw)), (0xFF,) * 27)
 
+    def test_motor_status_decode_31_bytes(self):
+        # Global 0x47 = cal XYZ + startup; axes idle/openish zeros except travel 1000
+        payload = bytearray(31)
+        payload[0] = 0x47
+        for base in (1, 11, 21):
+            payload[base] = 2  # IDLE
+            payload[base + 7] = 0xE8
+            payload[base + 8] = 0x03  # travel 1000
+        frame = encode_frame(FrameType.MOTOR_STATUS_DATA, bytes(payload))
+        self.assertEqual(len(frame), 37)
+        status = decode_motor_status_data(decode_frame(frame))
+        self.assertTrue(status.startup_complete)
+        self.assertEqual(int(status.global_status) & 0x07, 0b111)
+        self.assertEqual(status.x.travel_steps, 1000)
+
+    def test_mid_target_half_up(self):
+        self.assertEqual(mid_target(100, 50), 50)
+        self.assertEqual(mid_target(3, 50), 2)
+        self.assertEqual(mid_target(2, 1), 1)
+
     def test_crc_and_length_errors_are_rejected(self):
         raw = bytearray(encode_frame(FrameType.GET_TEMPERATURE, b""))
         raw[-1] ^= 1
@@ -79,11 +98,9 @@ class ProtocolTests(unittest.TestCase):
         with self.assertRaises(ProtocolError):
             decode_frame(bytes(raw[:-1]))
 
-    def test_unknown_type_and_invalid_direction_are_rejected(self):
+    def test_unknown_type_rejected(self):
         with self.assertRaises(ProtocolError):
             decode_frame(encode_frame(0x7F, b""))
-        with self.assertRaises(ValueError):
-            build_set_all([0] * 4, [0] * 4, 3, 0, 0)
 
 
 if __name__ == "__main__":

+ 0 - 84
tests/unit/test_startup_close_seek.py

@@ -1,84 +0,0 @@
-"""Contract tests for the startup close-seek feature (3-axis, close/backoff profile)."""
-
-from __future__ import annotations
-
-import json
-import unittest
-from pathlib import Path
-
-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"
-TOP_PATH = ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v"
-SOURCE_MANIFEST_PATH = ROOT / "src" / "generated" / "td-source-manifest.json"
-
-
-class StartupCloseSeekContractTests(unittest.TestCase):
-    def test_project_json_has_enabled_close_startup(self):
-        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
-        limits = project["limits"]
-        self.assertTrue(limits["functional_use"])
-        self.assertTrue(limits["runtime_use"])
-        startup = limits["startup"]
-        self.assertTrue(startup["enabled"])
-        self.assertEqual(startup["direction_meaning"], "close")
-        self.assertEqual(startup["close_step_count"], 5000)
-        self.assertEqual(startup["backoff_step_count"], 500)
-        self.assertEqual(startup["step_rate_hz"], 1000)
-        self.assertEqual(startup["axis_order"], ["x", "y", "z"])
-        self.assertTrue(startup["limit_stop_during_move"])
-        self.assertEqual(
-            startup["stop_semantics"],
-            "truncate_current_high_pulse_immediately_after_synchronized_limit",
-        )
-        self.assertEqual(startup["additional_rising_edges_after_synchronized_limit"], 0)
-        self.assertTrue(startup["runtime_limit_use"])
-
-    def test_generated_params_match_startup_config(self):
-        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
-        startup = project["limits"]["startup"]
-        params = PARAMS_PATH.read_text(encoding="utf-8")
-        self.assertIn("`define P4_STARTUP_ENABLED 1", params)
-        self.assertIn("`define P4_STARTUP_DIR_MASK 3'b111", params)
-        self.assertIn(f"`define P4_STARTUP_CLOSE_STEPS {startup['close_step_count']}", params)
-        self.assertIn(f"`define P4_STARTUP_BACKOFF_STEPS {startup['backoff_step_count']}", params)
-
-    def test_source_manifest_includes_startup_close_seek(self):
-        manifest = json.loads(SOURCE_MANIFEST_PATH.read_text(encoding="utf-8"))
-        self.assertIn("src/modules/startup_close_seek.v", manifest["sources"])
-
-    def test_top_level_instantiates_startup_close_seek(self):
-        top = TOP_PATH.read_text(encoding="utf-8")
-        self.assertIn("startup_close_seek", top)
-        self.assertIn("u_startup_close_seek", top)
-
-    def test_top_level_gates_host_motor_and_accept_during_startup(self):
-        top = TOP_PATH.read_text(encoding="utf-8")
-        self.assertIn("assign frame_accept_enable = host_frame_accept_enable & startup_done", top)
-        self.assertIn("assign motor_start = startup_done ? host_motor_start : startup_motor_start", top)
-        self.assertIn("assign motor_active_mask = startup_done ? host_motor_active_mask : startup_motor_active_mask", top)
-        self.assertIn("assign motor_dir_mask = startup_done ? host_motor_dir_mask : startup_motor_dir_mask", top)
-        self.assertIn("assign motor_stop_mask = startup_done ? runtime_limit_stop_mask : startup_motor_stop_mask", top)
-        self.assertIn(".motor_stop_mask(startup_motor_stop_mask)", top)
-        self.assertIn(".stop_mask(motor_stop_mask)", top)
-
-    def test_top_level_synchronizes_ls_hs_limit_inputs(self):
-        top = TOP_PATH.read_text(encoding="utf-8")
-        self.assertRegex(top, r"x_limit_ls_sync0\s*<=\s*x_limit_ls")
-        self.assertRegex(top, r"x_limit_hs_sync0\s*<=\s*x_limit_hs")
-        self.assertRegex(top, r"z_limit_ls_sync0\s*<=\s*z_limit_ls")
-        self.assertIn("limit_sync_valid", top)
-        self.assertRegex(top, r"limit_sync_valid_cnt\s*<\s*2'd3")
-
-    def test_startup_module_has_wait_sync_and_close_backoff_states(self):
-        source = (ROOT / "src" / "modules" / "startup_close_seek.v").read_text(encoding="utf-8")
-        for marker in (
-            "ST_WAIT_SYNC", "ST_CLOSE_START", "ST_CLOSE_WAIT", "ST_BACKOFF_START",
-            "limit_sync_valid", "close_limit", "open_limit", "motor_stop_mask",
-            "CLOSE_STEPS", "BACKOFF_STEPS", "AXIS_COUNT",
-        ):
-            self.assertIn(marker, source)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 119
tests/unit/test_startup_mutation.py

@@ -1,119 +0,0 @@
-"""Mutation test: removing WAIT_SYNC must cause startup_close_seek to fail."""
-
-from __future__ import annotations
-
-import re
-import subprocess
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[2]
-SOURCE = ROOT / "src" / "modules" / "startup_close_seek.v"
-
-sys.path.insert(0, str(ROOT / "tools"))
-import prod2u_p4_harness  # type: ignore
-
-
-def mutated_source() -> str:
-    text = SOURCE.read_text(encoding="utf-8")
-    text = re.sub(
-        r"if \(limit_sync_valid\)\s*state\s*<=\s*ST_CHECK;",
-        "state <= ST_CHECK;",
-        text,
-        count=1,
-    )
-    text = re.sub(
-        r"ST_WAIT_SYNC:\s*begin\s*motor_start\s*<=\s*1'b0;\s*if\s*\(limit_sync_valid\)\s*state\s*<=\s*ST_CHECK;\s*end\s*",
-        "",
-        text,
-        count=1,
-    )
-    return text
-
-
-class StartupMutationTests(unittest.TestCase):
-    def test_removing_wait_sync_fails(self):
-        iverilog = prod2u_p4_harness.resolve_tool("iverilog")
-        vvp = prod2u_p4_harness.resolve_tool("vvp")
-        if not iverilog or not vvp:
-            self.skipTest("iverilog/vvp not available")
-
-        with tempfile.TemporaryDirectory() as d:
-            tmp = Path(d)
-            mutated = tmp / "startup_close_seek_mut.v"
-            mutated.write_text(mutated_source(), encoding="utf-8")
-            tb = tmp / "tb.v"
-            tb.write_text(
-                """
-`timescale 1ns/1ps
-module tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg [2:0] limit_ls = 3'b000;
-    reg [2:0] limit_hs = 3'b000;
-    reg limit_sync_valid = 1'b0;
-    wire startup_done;
-    wire motor_start;
-    wire [2:0] motor_active_mask;
-    wire [2:0] motor_dir_mask;
-    wire [2:0] motor_stop_mask;
-    wire [12:0] motor_step_count;
-    reg motor_done = 1'b0;
-
-    always #1 clk = ~clk;
-
-    startup_close_seek #(
-        .CLOSE_STEPS(8),
-        .BACKOFF_STEPS(4),
-        .AXIS_COUNT(3)
-    ) dut (
-        .clk(clk), .rst_n(rst_n),
-        .limit_sync_valid(limit_sync_valid),
-        .close_limit(limit_ls), .open_limit(limit_hs),
-        .startup_done(startup_done), .motor_start(motor_start),
-        .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_done(motor_done)
-    );
-
-    integer i;
-    initial begin
-        repeat (3) @(posedge clk);
-        rst_n = 1'b1;
-        for (i = 0; i < 20; i = i + 1) begin
-            @(posedge clk);
-            if (motor_start) begin
-                $display("MUTATION_DETECTED");
-                $finish;
-            end
-        end
-        $fatal(1, "mutation was not detected");
-    end
-endmodule
-""",
-                encoding="utf-8",
-            )
-            vvp_out = tmp / "a.out"
-            env = prod2u_p4_harness.tool_env()
-            compile_result = subprocess.run(
-                [iverilog, "-g2005-sv", "-s", "tb", "-o", str(vvp_out), str(mutated), str(tb)],
-                cwd=tmp,
-                capture_output=True,
-                text=True,
-                env=env,
-            )
-            self.assertEqual(compile_result.returncode, 0, compile_result.stderr)
-            run_result = subprocess.run(
-                [vvp, str(vvp_out)],
-                cwd=tmp,
-                capture_output=True,
-                text=True,
-                env=env,
-            )
-            self.assertIn("MUTATION_DETECTED", run_result.stdout)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 26 - 20
tests/unit/test_three_axis_door_contract.py

@@ -1,4 +1,4 @@
-"""3-axis door contract: X/Y/Z motors, six limits, no solenoid/motor-compat."""
+"""3-axis door percent contract: X/Y/Z motors, six limits, no solenoid/jog."""
 
 from __future__ import annotations
 
@@ -10,7 +10,7 @@ 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"
 TOP_PATH = ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v"
-DISPATCHER_PATH = ROOT / "src" / "modules" / "door_action_dispatcher.v"
+MOTION_PATH = ROOT / "src" / "modules" / "door_motion_controller.v"
 CONTROLLER_PATH = ROOT / "src" / "project" / "command_controller.v"
 ADAPTER_PATH = ROOT / "src" / "project" / "project_adapter.v"
 
@@ -26,38 +26,44 @@ class ThreeAxisDoorContractTests(unittest.TestCase):
         self.assertEqual(set_all["z_door_offset"], 8)
         self.assertEqual(set_all["exhaust_x_offset"], 9)
         self.assertEqual(set_all["exhaust_y_offset"], 10)
-        self.assertNotIn("intake_actuator", project.get("doors", {}))
+        self.assertEqual(project["motors"]["positioning"]["mode"], "percent_close")
+        self.assertNotIn("fixed_steps", project["motors"])
+        self.assertNotIn("command_values", project["motors"])
 
-    def test_generated_params_three_axis_runtime_limits(self):
+    def test_generated_params_three_axis_percent(self):
         params = PARAMS_PATH.read_text(encoding="utf-8")
         self.assertIn("`define P4_AXIS_COUNT 3", params)
         self.assertIn("`define P4_LIMIT_COUNT 6", params)
         self.assertIn("`define P4_RUNTIME_LIMIT_USE 1", params)
-        self.assertIn("`define P4_STARTUP_CLOSE_STEPS 5000", params)
-        self.assertIn("`define P4_STARTUP_BACKOFF_STEPS 500", params)
+        self.assertIn("`define P4_DOOR_PERCENT_MAX 100", params)
+        self.assertIn("`define P4_CAL_MAX_STEPS 5000", params)
         self.assertIn("`define P4_MOTOR_ENABLE_POLICY_PERMANENT_HIGH 1", params)
+        self.assertIn("`define P4_CMD_GET_MOTOR_STATUS 8'h03", params)
+        self.assertIn("`define P4_RSP_MOTOR_STATUS 8'h83", params)
+        self.assertNotIn("P4_FIXED_MOTOR_STEPS", params)
         self.assertNotIn("P4_INTAKE_ACTUATOR_SOLENOID", params)
-        self.assertNotIn("P4_PROFILE_MOTOR_COMPAT", params)
 
-    def test_dispatcher_maps_byte8_to_z_bit2(self):
-        source = DISPATCHER_PATH.read_text(encoding="utf-8")
-        self.assertIn("z_door_cmd", source)
-        self.assertIn("{z_active, y_active, x_active}", source)
+    def test_motion_snapshot_byte_order_xyz(self):
+        source = MOTION_PATH.read_text(encoding="utf-8")
+        self.assertIn("snap[0]", source)
+        self.assertIn("calibrated_mask", source)
+        self.assertIn("// X @1, Y @11, Z @21", source)
         self.assertNotIn("intake_door_cmd", source)
-        self.assertIn("no new action", source)
 
-    def test_controller_and_adapter_use_z_door_cmd(self):
+    def test_controller_and_adapter_use_door_percent(self):
         controller = CONTROLLER_PATH.read_text(encoding="utf-8")
         adapter = ADAPTER_PATH.read_text(encoding="utf-8")
-        self.assertIn("z_door_cmd", controller)
+        self.assertIn("door_percent_z", controller)
+        self.assertIn("door_percent_x", controller)
+        self.assertIn("door_percent_y", controller)
+        self.assertIn("motor_request_valid", controller)
         self.assertIn("ST_VALIDATE_Z", controller)
-        self.assertIn("Z_DOOR_OFFSET", controller)
+        self.assertIn("CMD_GET_MOTOR_STATUS", controller)
+        self.assertNotIn("z_door_cmd", controller)
         self.assertNotIn("intake_door_cmd", controller)
-        self.assertNotIn("INTAKE_DOOR", controller)
-        self.assertNotIn("ST_VALIDATE_INTAKE", controller)
-        self.assertIn(".z_door_cmd(z_door_cmd)", adapter)
-        self.assertNotIn("intake_door_cmd", adapter)
-        self.assertNotIn("INTAKE_DOOR", adapter)
+        self.assertIn("door_percent_z", adapter)
+        self.assertIn("motor_request_valid", adapter)
+        self.assertNotIn("z_door_cmd", adapter)
 
     def test_top_has_z_axis_and_six_limit_ports(self):
         top = TOP_PATH.read_text(encoding="utf-8")

+ 8 - 20
tests/unit/test_top_step_gate_matches_formal.py

@@ -23,15 +23,7 @@ def _normalize_gate_expr(expr: str) -> str:
     return text
 
 
-def _extract_top_gates(text: str) -> dict[str, str]:
-    pattern = re.compile(
-        r"assign\s+([xyz])_step\s*=\s*([^;]+);",
-        re.MULTILINE,
-    )
-    return {m.group(1): _normalize_gate_expr(m.group(2)) for m in pattern.finditer(text)}
-
-
-def _extract_formal_gates(text: str) -> dict[str, str]:
+def _extract_gates(text: str) -> dict[str, str]:
     pattern = re.compile(
         r"assign\s+gated_step\[(\d)\]\s*=\s*([^;]+);",
         re.MULTILINE,
@@ -47,18 +39,14 @@ class TopStepGateMatchesFormalTests(unittest.TestCase):
     def test_formal_gate_matches_top_structure(self) -> None:
         top = TOP.read_text(encoding="utf-8")
         formal = FORMAL.read_text(encoding="utf-8")
-        top_gates = _extract_top_gates(top)
-        formal_gates = _extract_formal_gates(formal)
-        self.assertEqual(set(top_gates), {"x", "y", "z"})
+        # Top uses generate with gated_step[gi]; expand check via pin assigns + formal.
+        self.assertIn("assign gated_step[gi] = engine_step[gi] & ~selected_limit[gi]", top)
+        self.assertIn("assign x_step = gated_step[0]", top)
+        self.assertIn("assign y_step = gated_step[1]", top)
+        self.assertIn("assign z_step = gated_step[2]", top)
+        formal_gates = _extract_gates(formal)
         self.assertEqual(set(formal_gates), {"x", "y", "z"})
-        for axis in ("x", "y", "z"):
-            self.assertEqual(
-                top_gates[axis],
-                formal_gates[axis],
-                f"axis {axis}: top={top_gates[axis]!r} formal={formal_gates[axis]!r}",
-            )
-        # Canonical shape: engine_step & ~selected_limit
-        for axis, expr in top_gates.items():
+        for axis, expr in formal_gates.items():
             self.assertIn("engine_step&~selected_limit", expr, axis)
 
 

+ 4 - 5
tests/verilator_waivers.vlt

@@ -7,12 +7,11 @@
 // Combinational locals inside crc_bit() are intentional blocking assigns.
 lint_off -rule BLKSEQ -file "*/src/common/crc16_serial.v"
 
-// door_motor_engine uses blocking assigns to step_next as an intra-cycle
+// door_axis_controller uses blocking assigns to step_next as an intra-cycle
 // scratch in the sequential process (truncate/stop mask path); not NBA race.
-lint_off -rule BLKSEQ -file "*/src/modules/door_motor_engine.v"
+lint_off -rule BLKSEQ -file "*/src/modules/door_axis_controller.v"
 
 // Shared integer loop index across always @(*) and always @(posedge) is a
 // classic Verilog pattern; MULTIDRIVENPROC is a false positive for gen-loop ints.
-lint_off -rule MULTIDRIVENPROC -file "*/src/modules/startup_close_seek.v"
-lint_off -rule MULTIDRIVENPROC -file "*/src/modules/door_action_dispatcher.v"
-lint_off -rule MULTIDRIVENPROC -file "*/src/modules/door_motor_engine.v"
+lint_off -rule MULTIDRIVENPROC -file "*/src/modules/door_motion_controller.v"
+lint_off -rule MULTIDRIVENPROC -file "*/src/modules/door_axis_controller.v"

+ 36 - 0
tools/door_percent_planner_ref.py

@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""Reference mid-target helper for Prod2U door-percent positioning.
+
+Contract:
+    mid_target = clamp((travel * percent + 50) // 100, 1, travel - 1)
+"""
+
+from __future__ import annotations
+
+
+def mid_target(travel: int, percent: int) -> int:
+    """Half-up mid-position clamp used by the door-percent planner reference."""
+    if not isinstance(travel, int) or not isinstance(percent, int):
+        raise ValueError("travel and percent must be integers")
+    if travel < 2:
+        raise ValueError("travel must be >= 2 for mid targets")
+    if not 1 <= percent <= 99:
+        raise ValueError("mid percent must be in the range 1..99")
+    return max(1, min(travel - 1, (travel * percent + 50) // 100))
+
+
+__all__ = ["mid_target"]
+
+
+def main() -> None:
+    import argparse
+
+    parser = argparse.ArgumentParser(description="Compute door mid-target position")
+    parser.add_argument("travel", type=int)
+    parser.add_argument("percent", type=int)
+    args = parser.parse_args()
+    print(mid_target(args.travel, args.percent))
+
+
+if __name__ == "__main__":
+    main()

+ 289 - 60
tools/generate_project.py

@@ -15,6 +15,20 @@ from jsonschema import Draft202012Validator
 PROFILE = "prod2u-normal-multiproject-115200-v1"
 SCHEMA_PATH = Path(__file__).resolve().parents[1] / "schemas" / "project.schema.json"
 SOURCE_CLOSURE_PATH = Path(__file__).resolve().parents[1] / "config" / "source_closure.json"
+CAL_COUNTER_WIDTH_BITS = 13
+CAL_COUNTER_MAX = (1 << CAL_COUNTER_WIDTH_BITS) - 1
+FORBIDDEN_MOTOR_KEYS = {
+    "fixed_steps",
+    "busy_wait_ms",
+    "command_values",
+    "heartbeat_value",
+}
+FORBIDDEN_STARTUP_KEYS = {
+    "backoff_step_count",
+    "close_step_count",
+    "direction_value",
+    "direction_meaning",
+}
 
 _TOP_LEVEL_KEYS = {
     "project_id",
@@ -202,23 +216,22 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     _require(door_axes == ["x", "y", "z"], "door_axes must be x,y,z")
 
     motors = _object(payload["motors"], "motors")
+    forbidden_motor = FORBIDDEN_MOTOR_KEYS & set(motors)
+    _require(not forbidden_motor, f"obsolete motors keys present: {sorted(forbidden_motor)}")
     _keys(
         motors,
         {
             "count",
             "order",
             "role",
-            "fixed_steps",
             "execution",
-            "busy_wait_ms",
             "step_rate_hz",
             "step_half_cycles",
             "dir_setup_cycles",
-            "command_values",
-            "heartbeat_value",
             "open_dir_value",
             "close_dir_value",
             "dir_close_level",
+            "positioning",
             "mapping",
             "enable_n",
         },
@@ -227,14 +240,13 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     _integer(motors["count"], "motors.count", minimum=1)
     _require(len(motors["order"]) == motors["count"] and all(isinstance(axis, str) and axis for axis in motors["order"]), "motor order mismatch")
     _require(isinstance(motors["role"], str) and motors["role"], "invalid motor role")
-    _require(motors["execution"] in {"overlap", "serial"}, "invalid motor execution")
-    _integer(motors["busy_wait_ms"], "motors.busy_wait_ms", minimum=0)
-    _integer(motors["fixed_steps"], "motors.fixed_steps", minimum=1)
+    _require(motors["execution"] == "overlap", "motor execution must be overlap")
     _integer(motors["step_rate_hz"], "motors.step_rate_hz", minimum=1)
+    _require(motors["step_rate_hz"] == 1000, "motor step rate must be 1000")
     _integer(motors["step_half_cycles"], "motors.step_half_cycles", minimum=1)
+    _require(motors["step_half_cycles"] == 12500, "motor step half cycles must be 12500")
     _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(motors["heartbeat_value"] in motors["command_values"], "motor heartbeat is not a command")
+    _require(motors["dir_setup_cycles"] == 25000, "motor dir setup cycles must be 25000")
     _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")
@@ -243,7 +255,49 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     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")
-    # Per-axis dir_close_level is the sole authority; mixed 0/1 configs are allowed.
+    positioning = _object(motors["positioning"], "motors.positioning")
+    _keys(
+        positioning,
+        {
+            "mode",
+            "percent_min",
+            "percent_max",
+            "open_endpoint_percent",
+            "close_endpoint_percent",
+            "mid_percent_min",
+            "mid_percent_max",
+            "rounding",
+            "mid_clamp",
+            "latest_wins",
+            "idempotent_same_target",
+            "command_interrupt",
+            "shared_percent_planner",
+            "planner_count",
+            "endpoint_guard_extra_steps",
+        },
+        "motors.positioning",
+    )
+    _require(positioning["mode"] == "percent_close", "positioning mode must be percent_close")
+    _integer(positioning["percent_min"], "motors.positioning.percent_min", minimum=0)
+    _integer(positioning["percent_max"], "motors.positioning.percent_max", minimum=0)
+    _require(positioning["percent_min"] == 0 and positioning["percent_max"] == 100, "percent range must be 0..100")
+    _require(positioning["open_endpoint_percent"] == 0, "open endpoint percent must be 0")
+    _require(positioning["close_endpoint_percent"] == 100, "close endpoint percent must be 100")
+    _require(positioning["mid_percent_min"] == 1, "mid percent min must be 1")
+    _require(positioning["mid_percent_max"] == 99, "mid percent max must be 99")
+    _require(positioning["rounding"] == "half_up", "rounding must be half_up")
+    _require(positioning["mid_clamp"] == "1_to_travel_minus_1", "mid clamp policy mismatch")
+    _require(positioning["latest_wins"] is True, "latest_wins must be true")
+    _require(positioning["idempotent_same_target"] is True, "idempotent_same_target must be true")
+    _require(
+        positioning["command_interrupt"] == "finish_current_high_pulse_then_replan",
+        "command interrupt policy mismatch",
+    )
+    _require(positioning["shared_percent_planner"] is True, "shared_percent_planner must be true")
+    _integer(positioning["planner_count"], "motors.positioning.planner_count", minimum=1)
+    _require(positioning["planner_count"] == 1, "planner_count must be 1")
+    _integer(positioning["endpoint_guard_extra_steps"], "motors.positioning.endpoint_guard_extra_steps", minimum=0)
+    _require(positioning["endpoint_guard_extra_steps"] == 500, "endpoint guard extra steps must be 500")
     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")
     _keys(mapping, {"x", "y", "z"}, "motors.mapping")
@@ -290,25 +344,30 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     # Per-axis limit_active_high / close_limit_is_ls / dir_close_level alone decide
     # generated masks. Mixed-axis configs must not force active_level sync.
     startup = _object(limits["startup"], "limits.startup")
+    forbidden_startup = FORBIDDEN_STARTUP_KEYS & set(startup)
+    _require(not forbidden_startup, f"obsolete limits.startup keys present: {sorted(forbidden_startup)}")
     _keys(
         startup,
         {
             "enabled",
-            "direction_value",
-            "direction_meaning",
-            "close_step_count",
-            "backoff_step_count",
+            "mode",
+            "max_steps",
+            "min_travel_steps",
             "step_rate_hz",
             "axis_order",
+            "final_position",
             "limit_stop_during_move",
             "stop_semantics",
             "additional_rising_edges_after_synchronized_limit",
             "runtime_limit_use",
+            "partial_axis_failure_allowed",
+            "fault_lock_until_reset",
         },
         "limits.startup",
     )
     _require(startup["enabled"] is True, "startup must be enabled")
-    _require(startup["direction_meaning"] == "close", "startup direction must be close")
+    _require(startup["mode"] == "seek_close_then_measure_open", "startup mode must be seek_close_then_measure_open")
+    _require(startup["final_position"] == "open", "startup final position must be open")
     _require(startup["limit_stop_during_move"] is True, "startup limit stop during move must be enabled")
     _require(
         startup["stop_semantics"] == "truncate_current_high_pulse_immediately_after_synchronized_limit",
@@ -316,12 +375,19 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     )
     _require(startup["additional_rising_edges_after_synchronized_limit"] == 0, "additional rising edges after limit must be zero")
     _require(startup["runtime_limit_use"] is True, "startup runtime limit use must be true")
-    _integer(startup["direction_value"], "limits.startup.direction_value", minimum=0)
-    _integer(startup["close_step_count"], "limits.startup.close_step_count", minimum=1)
-    _integer(startup["backoff_step_count"], "limits.startup.backoff_step_count", minimum=0)
+    _require(startup["partial_axis_failure_allowed"] is True, "partial axis failure must be allowed")
+    _require(startup["fault_lock_until_reset"] is True, "fault lock until reset must be true")
+    _integer(startup["max_steps"], "limits.startup.max_steps", minimum=1)
+    _integer(startup["min_travel_steps"], "limits.startup.min_travel_steps", minimum=0)
     _integer(startup["step_rate_hz"], "limits.startup.step_rate_hz", minimum=1)
-    _require(startup["close_step_count"] == 5000, "startup close step count must be 5000")
-    _require(startup["backoff_step_count"] == 500, "startup backoff step count must be 500")
+    _require(startup["max_steps"] == 5000, "startup max_steps must be 5000")
+    _require(startup["min_travel_steps"] >= 2, "min_travel_steps must be >= 2")
+    _require(startup["min_travel_steps"] == 2, "startup min_travel_steps must be 2")
+    _require(startup["step_rate_hz"] == 1000, "startup step rate must be 1000")
+    _require(startup["max_steps"] <= CAL_COUNTER_MAX, "max_steps exceeds calibration counter width")
+    endpoint_guard_max = startup["max_steps"] + positioning["endpoint_guard_extra_steps"]
+    _require(endpoint_guard_max <= CAL_COUNTER_MAX, "endpoint guard max exceeds calibration counter width")
+    _require(endpoint_guard_max == 5500, "endpoint guard max must be 5500")
     _require(len(startup["axis_order"]) == 3 and startup["axis_order"] == ["x", "y", "z"], "startup axis order mismatch")
     expected_limit_names = [
         "x_limit_ls",
@@ -414,7 +480,7 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
             "temperature_ram",
             "dsp",
             "shared_pwm_comparators",
-            "shared_motor_executors",
+            "shared_percent_planner",
             "shared_i2c_readers",
         },
         "resource_policy",
@@ -427,9 +493,24 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
             )
         else:
             _integer(value, f"resource_policy.{key}", minimum=0)
+    _require(resources["dsp"] == 0, "resource_policy.dsp must be 0")
+    _require(resources["shared_percent_planner"] == 1, "resource_policy.shared_percent_planner must be 1")
+    _require(resources["shared_percent_planner"] == positioning["planner_count"], "shared planner count mismatch")
 
     protocol = _object(payload["protocol"], "protocol")
-    _keys(protocol, {"header_hex", "crc", "commands", "set_all", "temperature_data"}, "protocol")
+    _keys(
+        protocol,
+        {
+            "header_hex",
+            "crc",
+            "commands",
+            "set_all",
+            "get_motor_status",
+            "temperature_data",
+            "motor_status_data",
+        },
+        "protocol",
+    )
     _require(isinstance(protocol["header_hex"], str) and protocol["header_hex"], "frame header missing")
     crc = _object(protocol["crc"], "protocol.crc")
     _keys(crc, {"name", "polynomial", "initial", "reflect_input", "reflect_output", "xor_output", "coverage", "wire_order"}, "protocol.crc")
@@ -447,26 +528,39 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
         },
         "CRC contract mismatch",
     )
-    _require(set(protocol["commands"]) == {"set_all", "get_temperature", "temperature_data"}, "protocol command keys mismatch")
-    set_all = _object(protocol["set_all"], "protocol.set_all")
+    commands = _object(protocol["commands"], "protocol.commands")
     _keys(
-        set_all,
-        {
-            "payload_length",
-            "fan_offset",
-            "chamber_ptc_offset",
-            "chamber_ptc_count",
-            "z_door_offset",
-            "exhaust_x_offset",
-            "exhaust_y_offset",
-            "legacy_payload_length_rejected",
-            "duty_min",
-            "duty_max",
-            "door_values",
-            "response",
-        },
-        "protocol.set_all",
+        commands,
+        {"set_all", "get_temperature", "get_motor_status", "temperature_data", "motor_status_data"},
+        "protocol.commands",
     )
+    _require(commands["set_all"] == 1, "SET_ALL command type mismatch")
+    _require(commands["get_temperature"] == 2, "GET_TEMPERATURE command type mismatch")
+    _require(commands["get_motor_status"] == 3, "GET_MOTOR_STATUS command type mismatch")
+    _require(commands["temperature_data"] == 130, "TEMPERATURE_DATA command type mismatch")
+    _require(commands["motor_status_data"] == 131, "MOTOR_STATUS_DATA command type mismatch")
+    command_values = list(commands.values())
+    _require(len(command_values) == len(set(command_values)), "duplicate protocol command types")
+    _require("door_values" not in protocol.get("set_all", {}), "obsolete set_all.door_values present")
+    set_all = _object(protocol["set_all"], "protocol.set_all")
+    set_all_keys = {
+        "payload_length",
+        "fan_offset",
+        "chamber_ptc_offset",
+        "chamber_ptc_count",
+        "z_door_offset",
+        "exhaust_x_offset",
+        "exhaust_y_offset",
+        "legacy_payload_length_rejected",
+        "duty_min",
+        "duty_max",
+        "door_percent_min",
+        "door_percent_max",
+        "response",
+    }
+    optional_set_all = {"door_percent_rejected_example"}
+    _require(set_all_keys <= set(set_all), "protocol.set_all missing required keys")
+    _require(set(set_all) <= (set_all_keys | optional_set_all), "protocol.set_all keys mismatch")
     _require(set_all["fan_offset"] == 0, "SET_ALL FAN offset mismatch")
     _require(set_all["chamber_ptc_offset"] == outputs["fan_count"], "SET_ALL chamber PTC offset mismatch")
     _require(set_all["chamber_ptc_count"] == outputs["chamber_ptc_count"], "SET_ALL chamber PTC count mismatch")
@@ -476,11 +570,32 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     _require(set_all["payload_length"] == set_all["exhaust_y_offset"] + 1, "SET_ALL length mismatch")
     _require(set_all["legacy_payload_length_rejected"] == 14, "legacy payload length marker mismatch")
     _require(set_all["duty_min"] <= set_all["duty_max"], "SET_ALL duty range mismatch")
-    _require(set_all["door_values"] == motors["command_values"], "SET_ALL door values mismatch")
+    _require(set_all["door_percent_min"] == positioning["percent_min"], "SET_ALL door percent min mismatch")
+    _require(set_all["door_percent_max"] == positioning["percent_max"], "SET_ALL door percent max mismatch")
+    _require(set_all["response"] == "none", "SET_ALL response must be none")
+    if "door_percent_rejected_example" in set_all:
+        _integer(set_all["door_percent_rejected_example"], "protocol.set_all.door_percent_rejected_example", minimum=0)
+        _require(
+            set_all["door_percent_rejected_example"] > set_all["door_percent_max"],
+            "door percent rejected example must exceed door_percent_max",
+        )
+    get_motor_status = _object(protocol["get_motor_status"], "protocol.get_motor_status")
+    _keys(get_motor_status, {"payload_length", "response"}, "protocol.get_motor_status")
+    _require(get_motor_status["payload_length"] == 0, "GET_MOTOR_STATUS payload length must be 0")
+    _require(get_motor_status["response"] == "motor_status_data", "GET_MOTOR_STATUS response mismatch")
     temperature_data = _object(protocol["temperature_data"], "protocol.temperature_data")
     _keys(temperature_data, {"payload_length", "frame_length"}, "protocol.temperature_data")
     _require(temperature_data["payload_length"] == temperature["value_count"], "temperature payload length mismatch")
     _require(temperature_data["frame_length"] == temperature_data["payload_length"] + 6, "temperature frame length mismatch")
+    motor_status_data = _object(protocol["motor_status_data"], "protocol.motor_status_data")
+    _keys(motor_status_data, {"payload_length", "frame_length", "layout"}, "protocol.motor_status_data")
+    _require(motor_status_data["payload_length"] == 31, "motor status payload length must be 31")
+    _require(motor_status_data["frame_length"] == 37, "motor status frame length must be 37")
+    _require(
+        motor_status_data["frame_length"] == motor_status_data["payload_length"] + 6,
+        "motor status frame length mismatch",
+    )
+    _require(motor_status_data["layout"] == "host-contract", "motor status layout marker mismatch")
 
     timeouts = _object(payload["timeouts"], "timeouts")
     _keys(timeouts, {"frame_inter_byte_ms", "host_get_response_ms"}, "timeouts")
@@ -488,16 +603,23 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     _integer(timeouts["host_get_response_ms"], "timeouts.host_get_response_ms", minimum=1)
 
     watchdog = _object(payload["watchdog"], "watchdog")
-    _keys(watchdog, {"timeout_seconds", "tick_us", "tick_clks", "timeout_ticks", "target"}, "watchdog")
+    _keys(
+        watchdog,
+        {"timeout_seconds", "tick_us", "tick_clks", "timeout_ticks", "enable_after_startup_complete", "target"},
+        "watchdog",
+    )
     _integer(watchdog["timeout_seconds"], "watchdog.timeout_seconds", minimum=1)
     _integer(watchdog["tick_us"], "watchdog.tick_us", minimum=1)
     _integer(watchdog["tick_clks"], "watchdog.tick_clks", minimum=1)
     _require(watchdog["tick_clks"] == device["clock_hz"] * watchdog["tick_us"] // 1_000_000, "watchdog tick clock mismatch")
     _integer(watchdog["timeout_ticks"], "watchdog.timeout_ticks", minimum=1)
     _require(watchdog["timeout_ticks"] == watchdog["timeout_seconds"] * 1_000_000 // watchdog["tick_us"], "watchdog tick count mismatch")
+    _require(watchdog["timeout_seconds"] == 30, "watchdog timeout_seconds must be 30")
+    _require(watchdog["timeout_ticks"] == 60000, "watchdog timeout_ticks must be 60000")
+    _require(watchdog["enable_after_startup_complete"] is True, "watchdog must enable after startup complete")
     target = _object(watchdog["target"], "watchdog.target")
     _keys(target, {"ptc", "fan"}, "watchdog.target")
-    _require(target == {"ptc": 0, "fan": 20}, "watchdog target mismatch")
+    _require(target == {"ptc": 0, "fan": 10}, "watchdog target mismatch")
 
 
 def load_project(path: Path) -> dict[str, Any]:
@@ -607,20 +729,24 @@ def _frame_hex(frame_type: int, payload: bytes) -> str:
 def _render_params(project: Mapping[str, Any]) -> str:
     outputs = project["outputs"]
     motors = project["motors"]
+    positioning = motors["positioning"]
     limits = project["limits"]
     startup = limits["startup"]
     temperature = project["temperature"]
     uart = project["uart"]
     watchdog = project["watchdog"]
+    protocol = project["protocol"]
+    commands = protocol["commands"]
     axis_count = motors["count"]
     _require(motors["dir_setup_cycles"] % watchdog["tick_clks"] == 0, "motor direction setup is not an integral tick count")
     motor_dir_setup_ticks = motors["dir_setup_cycles"] // watchdog["tick_clks"]
     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 = motors["close_dir_value"]
     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)
+    endpoint_guard_max = startup["max_steps"] + positioning["endpoint_guard_extra_steps"]
     lines = [
         "// Generated from project.json. Do not edit.",
         f"`define P4_AXIS_COUNT {axis_count}",
@@ -641,22 +767,35 @@ def _render_params(project: Mapping[str, Any]) -> str:
         f"`define P4_PWM_PHASE_COUNT {outputs['pwm_phase_count']}",
         f"`define P4_PWM_FREQUENCY_HZ {outputs['pwm_frequency_hz']}",
         f"`define P4_PWM_SLOT_CLKS {outputs['pwm_slot_clks']}",
-        f"`define P4_SET_ALL_PAYLOAD_LENGTH {project['protocol']['set_all']['payload_length']}",
+        f"`define P4_CMD_SET_ALL 8'h{commands['set_all']:02X}",
+        f"`define P4_CMD_GET_TEMPERATURE 8'h{commands['get_temperature']:02X}",
+        f"`define P4_CMD_GET_MOTOR_STATUS 8'h{commands['get_motor_status']:02X}",
+        f"`define P4_CMD_TEMPERATURE_DATA 8'h{commands['temperature_data']:02X}",
+        f"`define P4_CMD_MOTOR_STATUS_DATA 8'h{commands['motor_status_data']:02X}",
+        f"`define P4_RSP_TEMPERATURE 8'h{commands['temperature_data']:02X}",
+        f"`define P4_RSP_MOTOR_STATUS 8'h{commands['motor_status_data']:02X}",
+        f"`define P4_SET_ALL_PAYLOAD_LENGTH {protocol['set_all']['payload_length']}",
         f"`define P4_CHAMBER_PTC_COUNT {outputs['chamber_ptc_count']}",
-        f"`define P4_SET_ALL_FAN_OFFSET {project['protocol']['set_all']['fan_offset']}",
-        f"`define P4_SET_ALL_CHAMBER_PTC_OFFSET {project['protocol']['set_all']['chamber_ptc_offset']}",
-        f"`define P4_SET_ALL_Z_DOOR_OFFSET {project['protocol']['set_all']['z_door_offset']}",
-        f"`define P4_SET_ALL_EXHAUST_X_OFFSET {project['protocol']['set_all']['exhaust_x_offset']}",
-        f"`define P4_SET_ALL_EXHAUST_Y_OFFSET {project['protocol']['set_all']['exhaust_y_offset']}",
+        f"`define P4_SET_ALL_FAN_OFFSET {protocol['set_all']['fan_offset']}",
+        f"`define P4_SET_ALL_CHAMBER_PTC_OFFSET {protocol['set_all']['chamber_ptc_offset']}",
+        f"`define P4_SET_ALL_Z_DOOR_OFFSET {protocol['set_all']['z_door_offset']}",
+        f"`define P4_SET_ALL_EXHAUST_X_OFFSET {protocol['set_all']['exhaust_x_offset']}",
+        f"`define P4_SET_ALL_EXHAUST_Y_OFFSET {protocol['set_all']['exhaust_y_offset']}",
+        f"`define P4_DOOR_PERCENT_MIN {positioning['percent_min']}",
+        f"`define P4_DOOR_PERCENT_MAX {positioning['percent_max']}",
+        f"`define P4_OPEN_ENDPOINT_PERCENT {positioning['open_endpoint_percent']}",
+        f"`define P4_CLOSE_ENDPOINT_PERCENT {positioning['close_endpoint_percent']}",
+        f"`define P4_MID_PERCENT_MIN {positioning['mid_percent_min']}",
+        f"`define P4_MID_PERCENT_MAX {positioning['mid_percent_max']}",
+        f"`define P4_MOTOR_STATUS_PAYLOAD_LENGTH {protocol['motor_status_data']['payload_length']}",
+        f"`define P4_MOTOR_STATUS_FRAME_LENGTH {protocol['motor_status_data']['frame_length']}",
         f"`define P4_MOTOR_OPEN_DIR 1'b{motors['open_dir_value']}",
         f"`define P4_MOTOR_CLOSE_DIR 1'b{motors['close_dir_value']}",
         f"`define P4_FRAME_INTER_BYTE_TIMEOUT_CYCLES {frame_inter_byte_timeout_cycles}",
-        f"`define P4_FIXED_MOTOR_STEPS {motors['fixed_steps']}",
         f"`define P4_MOTOR_STEP_RATE_HZ {motors['step_rate_hz']}",
         f"`define P4_MOTOR_STEP_HALF_CYCLES {motors['step_half_cycles']}",
         f"`define P4_MOTOR_DIR_SETUP_CYCLES {motors['dir_setup_cycles']}",
         f"`define P4_MOTOR_DIR_SETUP_TICKS {motor_dir_setup_ticks}",
-        f"`define P4_MOTOR_HEARTBEAT_COMMAND 2'd{motors['heartbeat_value']}",
         f"`define P4_TEMPERATURE_COUNT {temperature['value_count']}",
         f"`define P4_TEMPERATURE_COUNT_BYTE 8'h{temperature['value_count']:02X}",
         f"`define P4_TEMPERATURE_FRAME_LENGTH {temperature['value_count'] + 6}",
@@ -669,14 +808,30 @@ def _render_params(project: Mapping[str, Any]) -> str:
         f"`define P4_WATCHDOG_TICK_US {watchdog['tick_us']}",
         f"`define P4_WATCHDOG_TICK_CLKS {watchdog['tick_clks']}",
         f"`define P4_WATCHDOG_TIMEOUT_TICKS {watchdog['timeout_ticks']}",
+        f"`define P4_WATCHDOG_ENABLE_AFTER_STARTUP {1 if watchdog['enable_after_startup_complete'] else 0}",
         f"`define P4_WATCHDOG_PTC_TARGET 8'h{watchdog['target']['ptc']:02X}",
         f"`define P4_WATCHDOG_FAN_TARGET 8'h{watchdog['target']['fan']:02X}",
         f"`define P4_STARTUP_ENABLED {1 if startup['enabled'] else 0}",
         f"`define P4_STARTUP_DIR_MASK {startup_dir_mask}",
-        f"`define P4_STARTUP_CLOSE_STEPS {startup['close_step_count']}",
-        f"`define P4_STARTUP_BACKOFF_STEPS {startup['backoff_step_count']}",
+        f"`define P4_CAL_MAX_STEPS {startup['max_steps']}",
+        f"`define P4_CAL_MIN_TRAVEL {startup['min_travel_steps']}",
+        f"`define P4_ENDPOINT_GUARD_EXTRA {positioning['endpoint_guard_extra_steps']}",
+        f"`define P4_ENDPOINT_GUARD_MAX {endpoint_guard_max}",
         f"`define P4_STARTUP_STEP_RATE_HZ {startup['step_rate_hz']}",
         f"`define P4_MOTOR_ENABLE_POLICY_PERMANENT_HIGH {1 if motors['enable_n']['policy'] == 'permanent_high' else 0}",
+        "`define P4_STATE_CAL_SEEK_CLOSE 8'd0",
+        "`define P4_STATE_CAL_MEASURE_OPEN 8'd1",
+        "`define P4_STATE_IDLE 8'd2",
+        "`define P4_STATE_MOVE_OPEN 8'd3",
+        "`define P4_STATE_MOVE_CLOSE 8'd4",
+        "`define P4_STATE_WAIT_REPLAN 8'd5",
+        "`define P4_STATE_FAULT 8'd6",
+        "`define P4_FAULT_NONE 8'd0",
+        "`define P4_FAULT_BOTH_LIMITS_ACTIVE 8'd1",
+        "`define P4_FAULT_CAL_CLOSE_TIMEOUT 8'd2",
+        "`define P4_FAULT_CAL_OPEN_TIMEOUT 8'd3",
+        "`define P4_FAULT_INVALID_ZERO_OR_TINY_TRAVEL 8'd4",
+        "`define P4_FAULT_ENDPOINT_TIMEOUT 8'd5",
     ]
     lines.extend(
         f"`define P4_TEMP_DEVICE_ADDR_{index} 7'h{address:02X}"
@@ -710,6 +865,53 @@ def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
         _render_params(project), encoding="ascii", newline="\n"
     )
     summary = project_summary(project_path)
+    positioning = project["motors"]["positioning"]
+    motor_status_layout = {
+        "byte0_global": {
+            "bit0_2": "calibrated_mask_xyz",
+            "bit3_5": "fault_mask_xyz",
+            "bit6": "startup_complete",
+            "bit7": "watchdog_tripped",
+        },
+        "per_axis_bytes": 10,
+        "axis_order": ["x", "y", "z"],
+        "axis_fields": [
+            "state",
+            "flags",
+            "requested_percent",
+            "current_position_le16",
+            "target_position_le16",
+            "travel_steps_le16",
+            "fault_code",
+        ],
+        "states": {
+            "CAL_SEEK_CLOSE": 0,
+            "CAL_MEASURE_OPEN": 1,
+            "IDLE": 2,
+            "MOVE_OPEN": 3,
+            "MOVE_CLOSE": 4,
+            "WAIT_REPLAN": 5,
+            "FAULT": 6,
+        },
+        "flags": {
+            "open_limit": 0,
+            "close_limit": 1,
+            "calibrated": 2,
+            "moving": 3,
+            "endpoint_mode": 4,
+            "target_valid": 5,
+            "replan_pending": 6,
+            "reserved": 7,
+        },
+        "fault_codes": {
+            "NONE": 0,
+            "BOTH_LIMITS_ACTIVE": 1,
+            "CAL_CLOSE_TIMEOUT": 2,
+            "CAL_OPEN_TIMEOUT": 3,
+            "INVALID_ZERO_OR_TINY_TRAVEL": 4,
+            "ENDPOINT_TIMEOUT": 5,
+        },
+    }
     contract = {
         "schema": "prod2u-simple-host-contract-v1",
         "project_id": project["project_id"],
@@ -725,7 +927,14 @@ def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
                 "payload_length": summary["set_all_payload_len"],
                 "response": "none",
                 "duty_range": [0, 100],
-                "door_values": [0, 1, 2],
+                "door_percent_range": [positioning["percent_min"], positioning["percent_max"]],
+                "door_percent_semantics": {
+                    "0": "full_open_endpoint",
+                    "1_to_99": "mid_percent_close",
+                    "100": "full_close_endpoint",
+                    "all_zero_frame": "fan_ptc_zero_and_all_doors_full_open_not_heartbeat",
+                    "0x65": "rejected_out_of_range",
+                },
                 "field_order": [
                     "fan_chamber_1",
                     "fan_chamber_2",
@@ -735,17 +944,24 @@ def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
                     "ptc_chamber_2",
                     "ptc_chamber_3",
                     "ptc_chamber_4",
-                    "door_z",
-                    "door_x",
-                    "door_y",
+                    "door_z_percent",
+                    "door_x_percent",
+                    "door_y_percent",
                 ],
             },
             "get_temperature": {"type": "0x02", "payload_length": 0, "response": "TEMPERATURE_DATA"},
+            "get_motor_status": {"type": "0x03", "payload_length": 0, "response": "MOTOR_STATUS_DATA"},
             "temperature_data": {
                 "type": "0x82",
                 "payload_length": summary["temperature_payload_len"],
                 "frame_length": summary["temperature_frame_len"],
             },
+            "motor_status_data": {
+                "type": "0x83",
+                "payload_length": project["protocol"]["motor_status_data"]["payload_length"],
+                "frame_length": project["protocol"]["motor_status_data"]["frame_length"],
+                "layout": motor_status_layout,
+            },
         },
         "outputs": project["outputs"],
         "motors": project["motors"],
@@ -755,14 +971,27 @@ def generate_project(project_path: Path, output_root: Path) -> dict[str, Any]:
     }
     _write_json(output / "host-contract.json", contract)
     _write_json(output / "project-summary.json", summary)
+    # Representative status: startup_complete + all calibrated, idle at open, travel=1000.
+    status_axis = bytes((0x02, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE8, 0x03, 0x00))
+    status_payload = bytes((0x47,)) + status_axis * 3
     _write_json(
         output / "golden-vectors.json",
         {
-            "set_all_all_zero": _frame_hex(0x01, bytes(11)),
-            "set_all_mixed": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 1, 2, 0))),
+            "set_all_all_zero_full_open": _frame_hex(0x01, bytes(11)),
+            "set_all_doors_0_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 0, 0, 0))),
+            "set_all_doors_50_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 50, 50, 50))),
+            "set_all_doors_100_percent": _frame_hex(0x01, bytes((10, 20, 30, 40, 0, 25, 50, 100, 100, 100, 100))),
+            "set_all_door_0x65_rejected": "65",
             "set_all_legacy_14_rejected": "0E",
             "get_temperature": _frame_hex(0x02, b""),
+            "get_motor_status": _frame_hex(0x03, b""),
+            "motor_status_data_example": _frame_hex(0x83, status_payload),
             "all_invalid_temperature": _frame_hex(0x82, bytes([0xFF] * project["temperature"]["value_count"])),
+            "notes": {
+                "set_all_all_zero_full_open": "Legal SET_ALL: FAN/PTC 0 and doors 0/0/0 = full open; not a jog heartbeat no-op.",
+                "set_all_door_0x65_rejected": "Door percent 0x65 (101) is out of 0..100 and must be rejected.",
+                "get_motor_status": "Exact request frame A55A03005C48.",
+            },
         },
     )
     source_payload = {

+ 8 - 0
tools/prod2u_p4_harness.py

@@ -1455,6 +1455,14 @@ def _run_cocotb(
                 parent = str(Path(resolved).parent)
                 if parent not in path_parts and "oss-cad-suite" not in parent:
                     path_parts.append(parent)
+            # Prefer /usr/local wrappers so VPI spawn keeps iverilog without OSS CAD bin
+            # (OSS CAD bin would resurrect tabbypy3 as sys.executable).
+            for fallback in (Path("/usr/local/bin") / name, Path("/usr/bin") / name):
+                if fallback.is_file() and os.access(fallback, os.X_OK):
+                    parent = str(fallback.parent)
+                    if parent not in path_parts:
+                        path_parts.append(parent)
+                    break
         for part in cocotb_env.get("PATH", "").split(os.pathsep):
             if not part or part in path_parts:
                 continue

+ 223 - 34
tools/prod2u_simple_protocol.py

@@ -1,40 +1,101 @@
 #!/usr/bin/env python3
-"""Reference model for the Prod2U door-temperature 11-byte SET_ALL contract."""
+"""Reference model for the Prod2U door-percent SET_ALL / status contract.
+
+Reads ``projects/prod2u-door-temp/project.json`` when present, but stays resilient
+if another agent is mid-edit: door fields are always percent 0..100, and frame
+types ``0x03`` / ``0x83`` are always accepted even when ``project.json`` still
+lists the legacy jog-only command table.
+"""
 
 from __future__ import annotations
 
 from dataclasses import dataclass
-from enum import IntEnum
+from enum import IntEnum, IntFlag
 import json
 from pathlib import Path
 from typing import Iterable, Sequence
 
-
 _PROJECT_PATH = Path(__file__).resolve().parents[1] / "projects" / "prod2u-door-temp" / "project.json"
-_PROJECT = json.loads(_PROJECT_PATH.read_text(encoding="utf-8"))
-_OUTPUTS = _PROJECT["outputs"]
-_PROTOCOL = _PROJECT["protocol"]
-_SET_ALL = _PROTOCOL["set_all"]
-_CRC = _PROTOCOL["crc"]
-_COMMANDS = _PROTOCOL["commands"]
-
-FRAME_HEADER = bytes.fromhex(_PROTOCOL["header_hex"])
-CHAMBER_PTC_COUNT = _OUTPUTS["chamber_ptc_count"]
-FAN_COUNT = len(_OUTPUTS["fan_channels"])
-TEMPERATURE_COUNT = _PROJECT["temperature"]["value_count"]
-SET_ALL_PAYLOAD_LENGTH = _SET_ALL["payload_length"]
-LEGACY_SET_ALL_PAYLOAD_LENGTH = _SET_ALL["legacy_payload_length_rejected"]
-DUTY_MIN = _SET_ALL["duty_min"]
-DUTY_MAX = _SET_ALL["duty_max"]
-DOOR_COMMANDS = tuple(_SET_ALL["door_values"])
-CRC_POLYNOMIAL = _CRC["polynomial"]
-CRC_INITIAL = _CRC["initial"]
+
+try:
+    _PROJECT = json.loads(_PROJECT_PATH.read_text(encoding="utf-8"))
+except (OSError, json.JSONDecodeError):
+    _PROJECT = {}
+
+_OUTPUTS = _PROJECT.get("outputs", {})
+_PROTOCOL = _PROJECT.get("protocol", {})
+_SET_ALL = _PROTOCOL.get("set_all", {})
+_CRC = _PROTOCOL.get("crc", {})
+_COMMANDS = _PROTOCOL.get("commands", {})
+_TEMPERATURE = _PROJECT.get("temperature", {})
+
+FRAME_HEADER = bytes.fromhex(_PROTOCOL.get("header_hex", "A55A"))
+CHAMBER_PTC_COUNT = int(_OUTPUTS.get("chamber_ptc_count", _SET_ALL.get("chamber_ptc_count", 4)))
+FAN_COUNT = len(_OUTPUTS.get("fan_channels", [0, 1, 2, 3])) or 4
+TEMPERATURE_COUNT = int(_TEMPERATURE.get("value_count", 27))
+SET_ALL_PAYLOAD_LENGTH = int(_SET_ALL.get("payload_length", 11))
+LEGACY_SET_ALL_PAYLOAD_LENGTH = int(_SET_ALL.get("legacy_payload_length_rejected", 14))
+DUTY_MIN = int(_SET_ALL.get("duty_min", 0))
+DUTY_MAX = int(_SET_ALL.get("duty_max", 100))
+DOOR_PERCENT_MIN = 0
+DOOR_PERCENT_MAX = 100
+MOTOR_STATUS_PAYLOAD_LENGTH = 31
+MOTOR_STATUS_FRAME_LENGTH = MOTOR_STATUS_PAYLOAD_LENGTH + 6
+AXIS_STATUS_BYTES = 10
+CRC_POLYNOMIAL = int(_CRC.get("polynomial", 4129))
+CRC_INITIAL = int(_CRC.get("initial", 65535))
+
+# Golden GET_MOTOR_STATUS request (empty payload).
+GET_MOTOR_STATUS_GOLDEN = bytes.fromhex("A55A03005C48")
 
 
 class FrameType(IntEnum):
-    SET_ALL = _COMMANDS["set_all"]
-    GET_TEMPERATURE = _COMMANDS["get_temperature"]
-    TEMPERATURE_DATA = _COMMANDS["temperature_data"]
+    SET_ALL = int(_COMMANDS.get("set_all", 0x01))
+    GET_TEMPERATURE = int(_COMMANDS.get("get_temperature", 0x02))
+    GET_MOTOR_STATUS = int(_COMMANDS.get("get_motor_status", 0x03))
+    TEMPERATURE_DATA = int(_COMMANDS.get("temperature_data", 0x82))
+    MOTOR_STATUS_DATA = int(_COMMANDS.get("motor_status_data", 0x83))
+
+
+class AxisState(IntEnum):
+    CAL_SEEK_CLOSE = 0
+    CAL_MEASURE_OPEN = 1
+    IDLE = 2
+    MOVE_OPEN = 3
+    MOVE_CLOSE = 4
+    WAIT_REPLAN = 5
+    FAULT = 6
+
+
+class AxisFlags(IntFlag):
+    OPEN_LIMIT = 0x01
+    CLOSE_LIMIT = 0x02
+    CALIBRATED = 0x04
+    MOVING = 0x08
+    ENDPOINT_MODE = 0x10
+    TARGET_VALID = 0x20
+    REPLAN_PENDING = 0x40
+    RESERVED = 0x80
+
+
+class FaultCode(IntEnum):
+    NONE = 0
+    BOTH_LIMITS_ACTIVE = 1
+    CAL_CLOSE_TIMEOUT = 2
+    CAL_OPEN_TIMEOUT = 3
+    INVALID_ZERO_OR_TINY_TRAVEL = 4
+    ENDPOINT_TIMEOUT = 5
+
+
+class GlobalStatusBits(IntFlag):
+    X_CALIBRATED = 0x01
+    Y_CALIBRATED = 0x02
+    Z_CALIBRATED = 0x04
+    X_FAULT = 0x08
+    Y_FAULT = 0x10
+    Z_FAULT = 0x20
+    STARTUP_COMPLETE = 0x40
+    WATCHDOG_TRIPPED = 0x80
 
 
 class ProtocolError(ValueError):
@@ -47,6 +108,44 @@ class Frame:
     payload: bytes
 
 
+@dataclass(frozen=True)
+class AxisMotorStatus:
+    state: AxisState
+    flags: AxisFlags
+    requested_percent: int
+    current_position: int
+    target_position: int
+    travel_steps: int
+    fault_code: FaultCode
+
+
+@dataclass(frozen=True)
+class MotorStatus:
+    global_status: GlobalStatusBits
+    x: AxisMotorStatus
+    y: AxisMotorStatus
+    z: AxisMotorStatus
+
+    @property
+    def startup_complete(self) -> bool:
+        return bool(self.global_status & GlobalStatusBits.STARTUP_COMPLETE)
+
+    @property
+    def watchdog_tripped(self) -> bool:
+        return bool(self.global_status & GlobalStatusBits.WATCHDOG_TRIPPED)
+
+
+def mid_target(travel: int, percent: int) -> int:
+    """Half-up mid-position clamp; same contract as ``door_percent_planner_ref``."""
+    if not isinstance(travel, int) or not isinstance(percent, int):
+        raise ValueError("travel and percent must be integers")
+    if travel < 2:
+        raise ValueError("travel must be >= 2 for mid targets")
+    if not 1 <= percent <= 99:
+        raise ValueError("mid percent must be in the range 1..99")
+    return max(1, min(travel - 1, (travel * percent + 50) // 100))
+
+
 def crc16_ccitt_false(data: bytes | bytearray | Iterable[int]) -> int:
     crc = CRC_INITIAL
     for value in data:
@@ -67,7 +166,9 @@ def _expected_length(frame_type: FrameType) -> int:
     return {
         FrameType.SET_ALL: SET_ALL_PAYLOAD_LENGTH,
         FrameType.GET_TEMPERATURE: 0,
+        FrameType.GET_MOTOR_STATUS: 0,
         FrameType.TEMPERATURE_DATA: TEMPERATURE_COUNT,
+        FrameType.MOTOR_STATUS_DATA: MOTOR_STATUS_PAYLOAD_LENGTH,
     }[frame_type]
 
 
@@ -121,25 +222,25 @@ def _checked_temperature_bytes(values: Iterable[int]) -> bytes:
     return bytes(items)
 
 
-def _checked_door_command(value: int, name: str) -> int:
-    if value not in DOOR_COMMANDS:
-        raise ValueError(f"{name} must be one of {DOOR_COMMANDS}")
+def _checked_door_percent(value: int, name: str) -> int:
+    if not isinstance(value, int) or not DOOR_PERCENT_MIN <= value <= DOOR_PERCENT_MAX:
+        raise ValueError(f"{name} must be in the range {DOOR_PERCENT_MIN}..{DOOR_PERCENT_MAX}")
     return value
 
 
 def build_set_all(
     fan: Iterable[int],
     chamber_ptc: Iterable[int],
-    intake_door: int,
-    exhaust_x: int,
-    exhaust_y: int,
+    z_percent: int,
+    x_percent: int,
+    y_percent: int,
 ) -> bytes:
-    intake_door = _checked_door_command(intake_door, "intake door command")
-    exhaust_x = _checked_door_command(exhaust_x, "exhaust x command")
-    exhaust_y = _checked_door_command(exhaust_y, "exhaust y command")
+    z_percent = _checked_door_percent(z_percent, "z_percent")
+    x_percent = _checked_door_percent(x_percent, "x_percent")
+    y_percent = _checked_door_percent(y_percent, "y_percent")
     payload = _checked_duty_bytes(fan, FAN_COUNT, "fan")
     payload += _checked_duty_bytes(chamber_ptc, CHAMBER_PTC_COUNT, "chamber ptc")
-    payload += bytes((intake_door, exhaust_x, exhaust_y))
+    payload += bytes((z_percent, x_percent, y_percent))
     return encode_frame(FrameType.SET_ALL, payload)
 
 
@@ -147,6 +248,16 @@ def build_get_temperature() -> bytes:
     return encode_frame(FrameType.GET_TEMPERATURE, b"")
 
 
+def build_get_motor_status() -> bytes:
+    frame = encode_frame(FrameType.GET_MOTOR_STATUS, b"")
+    if frame != GET_MOTOR_STATUS_GOLDEN:
+        raise ProtocolError(
+            f"GET_MOTOR_STATUS golden mismatch: got {frame.hex(' ').upper()}, "
+            f"expected {GET_MOTOR_STATUS_GOLDEN.hex(' ').upper()}"
+        )
+    return frame
+
+
 def build_temperature_data(values: Iterable[int]) -> bytes:
     return encode_frame(FrameType.TEMPERATURE_DATA, _checked_temperature_bytes(values))
 
@@ -155,3 +266,81 @@ def decode_temperature_data(frame: Frame) -> tuple[int, ...]:
     if frame.frame_type is not FrameType.TEMPERATURE_DATA:
         raise ProtocolError("frame is not TEMPERATURE_DATA")
     return tuple(frame.payload)
+
+
+def _u16_le(payload: bytes, offset: int) -> int:
+    return int.from_bytes(payload[offset : offset + 2], "little")
+
+
+def _parse_axis_status(raw: bytes) -> AxisMotorStatus:
+    if len(raw) != AXIS_STATUS_BYTES:
+        raise ProtocolError(f"axis status must be {AXIS_STATUS_BYTES} bytes")
+    try:
+        state = AxisState(raw[0])
+    except ValueError as exc:
+        raise ProtocolError(f"unsupported axis state: 0x{raw[0]:02X}") from exc
+    flags = AxisFlags(raw[1])
+    if flags & AxisFlags.RESERVED:
+        raise ProtocolError("axis flags reserved bit must be 0")
+    requested = raw[2]
+    if not DOOR_PERCENT_MIN <= requested <= DOOR_PERCENT_MAX:
+        raise ProtocolError(f"requested_percent out of range: {requested}")
+    try:
+        fault = FaultCode(raw[9])
+    except ValueError as exc:
+        raise ProtocolError(f"unsupported fault_code: 0x{raw[9]:02X}") from exc
+    return AxisMotorStatus(
+        state=state,
+        flags=flags,
+        requested_percent=requested,
+        current_position=_u16_le(raw, 3),
+        target_position=_u16_le(raw, 5),
+        travel_steps=_u16_le(raw, 7),
+        fault_code=fault,
+    )
+
+
+def decode_motor_status_data(frame: Frame | bytes | bytearray) -> MotorStatus:
+    if isinstance(frame, (bytes, bytearray)):
+        frame = decode_frame(frame)
+    if frame.frame_type is not FrameType.MOTOR_STATUS_DATA:
+        raise ProtocolError("frame is not MOTOR_STATUS_DATA")
+    payload = frame.payload
+    if len(payload) != MOTOR_STATUS_PAYLOAD_LENGTH:
+        raise ProtocolError(f"MOTOR_STATUS_DATA payload must be {MOTOR_STATUS_PAYLOAD_LENGTH} bytes")
+    return MotorStatus(
+        global_status=GlobalStatusBits(payload[0]),
+        x=_parse_axis_status(payload[1:11]),
+        y=_parse_axis_status(payload[11:21]),
+        z=_parse_axis_status(payload[21:31]),
+    )
+
+
+def build_motor_status_data(
+    global_status: int,
+    x: AxisMotorStatus | Sequence[int] | bytes,
+    y: AxisMotorStatus | Sequence[int] | bytes,
+    z: AxisMotorStatus | Sequence[int] | bytes,
+) -> bytes:
+    """Encode a 31-byte MOTOR_STATUS_DATA frame (host/sim helper)."""
+
+    def _axis_bytes(axis: AxisMotorStatus | Sequence[int] | bytes) -> bytes:
+        if isinstance(axis, AxisMotorStatus):
+            if axis.flags & AxisFlags.RESERVED:
+                raise ValueError("axis flags reserved bit must be 0")
+            return bytes(
+                (
+                    int(axis.state) & 0xFF,
+                    int(axis.flags) & 0xFF,
+                    int(axis.requested_percent) & 0xFF,
+                )
+            ) + int(axis.current_position).to_bytes(2, "little") + int(axis.target_position).to_bytes(
+                2, "little"
+            ) + int(axis.travel_steps).to_bytes(2, "little") + bytes((int(axis.fault_code) & 0xFF,))
+        raw = bytes(axis)
+        if len(raw) != AXIS_STATUS_BYTES:
+            raise ValueError(f"axis status must be {AXIS_STATUS_BYTES} bytes")
+        return raw
+
+    payload = bytes((int(global_status) & 0xFF,)) + _axis_bytes(x) + _axis_bytes(y) + _axis_bytes(z)
+    return encode_frame(FrameType.MOTOR_STATUS_DATA, payload)

+ 1 - 1
tools/test_profiles.py

@@ -113,7 +113,7 @@ def structure_required_paths(profile: str | None = None) -> tuple[str, ...]:
         "src/common/frame_rx.v",
         "src/common/frame_tx.v",
         "src/common/crc16_serial.v",
-        "src/modules/door_motor_engine.v",
+        "src/modules/door_motion_controller.v",
         "src/modules/temperature_reader.v",
         "src/project/project_adapter.v",
         "src/top/prod2u_p4_normal_v3_top.v",