ソースを参照

feat(prod2u): add profile 4 fan tach control

Codex 4 ヶ月 前
親
コミット
831164b495
57 ファイル変更、13482 行追加、185 行削除
  1. 57 0
      constraints/prod2u_fan_tach_binary921_v2.adc
  2. 55 0
      docs/prod2u-p4-program-sram-runbook.zh-CN.md
  3. 63 0
      docs/prod2u-p4-start-here.zh-CN.md
  4. 2 0
      requirements/prod2u-p4-requirements.in
  5. 3 0
      requirements/prod2u-p4-requirements.lock
  6. 279 0
      schemas/prod2u_p4_campaign.schema.json
  7. 227 0
      schemas/prod2u_p4_evidence.schema.json
  8. 170 0
      schemas/prod2u_p4_final_gate.schema.json
  9. 93 0
      schemas/prod2u_p4_qualification.schema.json
  10. 85 0
      schemas/prod2u_p4_td_build_receipt.schema.json
  11. 89 5
      schemas/prod2u_program_sram_receipt.schema.json
  12. 9 34
      src/rtl/binary921_frame_tx.v
  13. 95 0
      src/rtl/prod2u_fan_pwm_bank.v
  14. 735 0
      src/rtl/prod2u_fan_tach_binary921_v2_core.v
  15. 82 0
      src/rtl/prod2u_fan_tach_capture8.v
  16. 246 0
      src/rtl/prod2u_p4_host_rx.v
  17. 114 0
      src/rtl/prod2u_p4_tx_scheduler.v
  18. 289 0
      src/top/prod2u_fan_tach_binary921_v2_normal_top.v
  19. 211 0
      src/top/prod2u_fan_tach_binary921_v2_trace_top.v
  20. 16 0
      td/phy/prod2u_fan_tach_binary921_v2_normal.tcl
  21. 16 0
      td/phy/prod2u_fan_tach_binary921_v2_trace.tcl
  22. 25 0
      td/prod2u_fan_tach_binary921_v2_normal.prj
  23. 25 0
      td/prod2u_fan_tach_binary921_v2_trace.prj
  24. 23 0
      td/syn/prod2u_fan_tach_binary921_v2_normal.tcl
  25. 23 0
      td/syn/prod2u_fan_tach_binary921_v2_trace.tcl
  26. 15 0
      tests/formal/prod2u_fan_data_path.sby
  27. 69 0
      tests/formal/prod2u_fan_data_path_formal.v
  28. 167 0
      tests/sim/prod2u_fan_pwm_bank_tb.v
  29. 358 0
      tests/sim/prod2u_fan_tach_binary921_v2_core_tb.v
  30. 83 0
      tests/sim/prod2u_fan_tach_capture8_tb.v
  31. 305 0
      tests/sim/prod2u_p4_host_rx_tb.v
  32. 201 0
      tests/sim/prod2u_p4_tx_scheduler_tb.v
  33. 59 0
      tests/unit/test_pid_harness.py
  34. 23 0
      tests/unit/test_pin_inventory.py
  35. 24 0
      tests/unit/test_prod2u_contract.py
  36. 1122 0
      tests/unit/test_prod2u_p4_cli_campaign.py
  37. 200 0
      tests/unit/test_prod2u_p4_cli_identity.py
  38. 394 0
      tests/unit/test_prod2u_p4_evidence_binding.py
  39. 297 0
      tests/unit/test_prod2u_p4_integration.py
  40. 443 0
      tests/unit/test_prod2u_p4_package.py
  41. 333 0
      tests/unit/test_prod2u_p4_protocol.py
  42. 183 0
      tests/unit/test_prod2u_p4_qualification.py
  43. 325 0
      tests/unit/test_prod2u_p4_validate_contract.py
  44. 345 0
      tests/unit/test_prod2u_programmer_process_audit.py
  45. 106 28
      tests/unit/test_prod2u_programmer_runtime.py
  46. 317 0
      tests/unit/test_prod2u_validator.py
  47. 11 1
      tests/unit/test_uart_receipts.py
  48. 460 0
      tools/package_prod2u_p4.ps1
  49. 166 10
      tools/pid_harness.py
  50. 26 2
      tools/pin_inventory.py
  51. 252 12
      tools/prod2u.ps1
  52. 401 0
      tools/prod2u_p4_campaign.py
  53. 1535 0
      tools/prod2u_p4_cli.py
  54. 353 0
      tools/prod2u_p4_collector.py
  55. 583 0
      tools/prod2u_p4_protocol.py
  56. 704 0
      tools/prod2u_p4_validate.py
  57. 590 93
      tools/prod2u_programmer.py

+ 57 - 0
constraints/prod2u_fan_tach_binary921_v2.adc

@@ -0,0 +1,57 @@
+# Prod2U Profile 4 production-board constraints.
+# UART1 is out of scope and held idle: TX=L10, RX=M9.
+# Combined Host+Debug RS232 UART2: TX=M10, RX=N11, divider 27 at 25 MHz.
+# SRAM-only image. No programming or flash command is present in this file.
+set_pin_assignment { sys_clk } { LOCATION = J1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[0] } { LOCATION = H16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[1] } { LOCATION = H15; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[2] } { LOCATION = J16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[3] } { LOCATION = J15; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[4] } { LOCATION = K16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[5] } { LOCATION = K15; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[6] } { LOCATION = L16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { led[7] } { LOCATION = L15; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { bmc_uart_rx } { LOCATION = M9; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { bmc_uart_tx } { LOCATION = L10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { host_uart_rx } { LOCATION = N11; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { host_uart_tx } { LOCATION = M10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[0] } { LOCATION = D2; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[1] } { LOCATION = D3; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[2] } { LOCATION = E6; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[3] } { LOCATION = D6; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[4] } { LOCATION = C1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[5] } { LOCATION = C2; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[6] } { LOCATION = B3; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_fg_in[7] } { LOCATION = B13; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_install_in[0] } { LOCATION = N10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_install_in[1] } { LOCATION = M11; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_install_in[2] } { LOCATION = P12; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_install_in[3] } { LOCATION = R11; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_pwm_out[0] } { LOCATION = C4; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_pwm_out[1] } { LOCATION = B5; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_pwm_out[2] } { LOCATION = B1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { fan_pwm_out[3] } { LOCATION = A14; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[0] } { LOCATION = F16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[1] } { LOCATION = G16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[2] } { LOCATION = T4; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[3] } { LOCATION = R5; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[4] } { LOCATION = T6; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[5] } { LOCATION = R7; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[6] } { LOCATION = M1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[7] } { LOCATION = N1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[8] } { LOCATION = P1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[9] } { LOCATION = R1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[10] } { LOCATION = T2; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[11] } { LOCATION = R3; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[12] } { LOCATION = P16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[13] } { LOCATION = R16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[14] } { LOCATION = M16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[15] } { LOCATION = N16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[16] } { LOCATION = P8; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[17] } { LOCATION = P7; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[18] } { LOCATION = T9; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[19] } { LOCATION = P9; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[20] } { LOCATION = P10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[21] } { LOCATION = R10; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[22] } { LOCATION = T13; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
+set_pin_assignment { ptc_pwm_out[23] } { LOCATION = T12; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }

ファイルの差分が大きいため隠しています
+ 55 - 0
docs/prod2u-p4-program-sram-runbook.zh-CN.md


+ 63 - 0
docs/prod2u-p4-start-here.zh-CN.md

@@ -0,0 +1,63 @@
+# Prod2U Profile 4 FAN/TACH 交付包
+
+本包是 Profile 4 `prod2u-fan-tach-binary921-v2` 的不可变交付物,包含独立的 `normal.bit` 和 `trace.bit`,以及各自的 TD receipt 和 source manifest。包名为 `prod2u-p4-fantach-<UTC timestamp>`;包外的 `venv`、现场 `runtime` 和 `evidence` 不属于 hash inventory,不能写回包内。
+
+## 先确认接线
+
+- 仅使用生产板 `CON78` 的真 RS232 接口,Windows 端口固定为 `COM5`,`921600 8N1`。
+- 必须使用 **USB-RS232** 适配器。板 `pin1` 是 TX,接适配器 RX;板 `pin2` 是 RX,接适配器 TX;板 `pin3/4` 接适配器 GND。
+- `CON78` 经板载 RS232 收发器转换,**USB-TTL 禁止使用**,也不要向连接器供 VCC。
+- JTAG 由包内 `accept` 命令自动调用 BitWriter CLI,且只允许 `PROGRAM_SRAM @ 200kHz`。保持板卡供电,**no power cycle**、单次尝试、零自动重试,不使用 flash 或任何非易失操作。
+- 图中电气针序来自 [CON77/CON78 RS232 原理图截图](images/prod2u-con77-con78-rs232-schematic.png)。它不能替代实物 pin1 标记、连接器资料或万用表连续性确认。
+
+## 离线自检
+
+在包根目录执行。该检查不打开 COM、JTAG 或风扇/PTC 负载,也不会安装驱动。
+
+```powershell
+$env:PYTHONDONTWRITEBYTECODE = "1"
+python -B .\prod2u_p4_cli.py selftest
+```
+
+先比对 `manifest.json` 和 `sha256-inventory.json`,再执行上述自检。`requirements.lock` 是 hash-locked 的离线依赖清单,`wheelhouse` 只提供与该清单相符的真实 wheel;在包外创建 venv 后才可安装。不得从网络补齐、不替换或伪造 wheel。
+
+包内还必须存在 `protocol-junit.xml`、`rtl-sim.json`、`formal.json` 和 `static.json`。`accept` 会在打开 COM5 或 AL-Link 前,把它们与两份 source manifest、两份 TD receipt、package manifest/inventory 一起生成 `prod2u-p4-static-qualification-v1`。`source / protocol / rtl / formal / td_normal / td_trace / package` 七层必须全部为 `pass`,且 artifact SHA256 必须与每轮 evidence binding 一致;缺失、失败或错配都会在硬件动作前停止。
+
+## 现场范围
+
+本 Profile 的 BMC 为 `out_of_scope`,因此不需要 BMC receipt、BMC 工具或 BMC 串口接线。`normal` 与 `trace` 是独立 TD build identity,normal/trace bit、TD receipt 和 source manifest 任一 hash 或 identity 不匹配时,必须停止,不得混用。
+
+硬件验证按 `FAN3` 的 `CON25` 路径进行:`PWM3=B1`,反馈 `FG5=C1` 和 `FG6=C2`。每轮自动执行 `0/20/40/60/80/100%`,每档丢弃前 2 个完整 1 秒窗口并保留后 5 个窗口。Profile 4 的任务是记录 PWM 设置与两个 FG 输入的可检测/缺失/间歇状态及其关联;它不等同于转速标定、风量、噪声或完整 thermal performance 通过。
+
+`SET_FAN P` 的正式含义是 CON25 风扇 PWM 连接器侧高电平占空比为 `P%`。生产板 FAN 路径使用 NPN 下拉:CPLD `B1` 输出高电平时晶体管导通并把 CON25 PWM 线拉低,因此 CPLD 原始高电平占空比必须为 `100-P`,经过板级反相后连接器侧才是 `P%`。这里的百分比是控制请求和机械趋势语义,不是已标定的绝对 RPM 百分比。
+
+`PTC1-6` 每轮按 1 到 6 逐路执行:`10%` 保持 `2s`,收到提交 ACK 后归零,再进入下一路。每轮随后真实等待 watchdog 超时、读取 timeout 状态并发送 `DISABLE`。PTC measurement 保持 `not_run`,不能声称真实温升、功率、热保护或 PID 闭环通过。
+
+## 自动验收
+
+关闭占用 COM5、AL-Link 或 TD/BitWriter 的其他程序,然后从包根目录执行。证据目录必须在包外,`CampaignId` 必须从未使用过:
+
+```powershell
+$m = Get-Content .\manifest.json -Raw -Encoding UTF8 | ConvertFrom-Json
+$EvidenceRoot = Join-Path (Split-Path -Parent (Get-Location)) "prod2u-p4-evidence"
+$CampaignId = "P4-$(Get-Date -Format yyyyMMdd-HHmmss)"
+
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\prod2u.ps1 accept `
+  -Profile profile4 `
+  -TdRoot "C:\Anlogic\TD_Release_2026.1_SP1.198.412" `
+  -OutputDir $EvidenceRoot `
+  -CampaignId $CampaignId `
+  -DutId "PROD2U-BOARD-01" `
+  -TraceBuildId $m.variants.trace.source_manifest.build_id `
+  -TraceBitstream .\trace.bit `
+  -TraceSha256 $m.variants.trace.bitstream.sha256 `
+  -TraceTdReceipt .\trace-td.json `
+  -TraceSourceManifest .\trace-source-manifest.json `
+  -NormalBuildId $m.variants.normal.source_manifest.build_id `
+  -NormalBitstream .\normal.bit `
+  -NormalSha256 $m.variants.normal.bitstream.sha256 `
+  -NormalTdReceipt .\normal-td.json `
+  -NormalSourceManifest .\normal-source-manifest.json
+```
+
+固定顺序是 Trace 5 轮,再 Normal 5 轮;每轮只下载一次且任一失败立即停止。第 10 轮完成后板上保留 Normal 固件,并确认输出处于 `DISABLE` 回退状态。详细边界见 [PROGRAM_SRAM runbook](prod2u-p4-program-sram-runbook.zh-CN.md)。

+ 2 - 0
requirements/prod2u-p4-requirements.in

@@ -0,0 +1,2 @@
+# Runtime serial transport used by the Profile 4 collector on an explicit COM port.
+pyserial==3.5

+ 3 - 0
requirements/prod2u-p4-requirements.lock

@@ -0,0 +1,3 @@
+# Generated from prod2u-p4-requirements.in against the bundled wheel.
+pyserial==3.5 \
+    --hash=sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0

+ 279 - 0
schemas/prod2u_p4_campaign.schema.json

@@ -0,0 +1,279 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-p4-campaign-v2",
+  "title": "Prod2U P4 ten-round offline campaign v2",
+  "type": "object",
+  "required": ["schema", "campaign_id", "campaign_identity", "bmc", "qualification", "rounds", "evidence_bindings"],
+  "properties": {
+    "schema": {"const": "prod2u-p4-campaign-v2"},
+    "campaign_id": {"type": "string", "minLength": 1},
+    "campaign_identity": {
+      "allOf": [
+        {"$ref": "#/$defs/identity"},
+        {"required": ["planned_rounds"], "properties": {"planned_rounds": {"const": 10}}}
+      ]
+    },
+    "bmc": {"$ref": "#/$defs/bmc"},
+    "qualification": {"$ref": "#/$defs/staticQualification"},
+    "layers": {"$ref": "#/$defs/layers"},
+    "rounds": {"type": "array", "minItems": 10, "maxItems": 10, "items": {"$ref": "#/$defs/round"}},
+    "evidence_bindings": {
+      "type": "array",
+      "minItems": 10,
+      "maxItems": 10,
+      "items": {
+        "type": "object",
+        "required": ["round", "evidence_binding"],
+        "properties": {
+          "round": {"type": "integer", "minimum": 1, "maximum": 10},
+          "evidence_binding": {"$ref": "#/$defs/evidenceBinding"}
+        },
+        "additionalProperties": true
+      }
+    }
+  },
+  "additionalProperties": true,
+  "$defs": {
+    "identity": {
+      "type": "object",
+      "required": ["dut_id", "build_id", "bitstream_sha256", "profile"],
+      "properties": {
+        "dut_id": {"type": "string", "minLength": 1},
+        "build_id": {"type": "string", "minLength": 1},
+        "bitstream_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "variant": {"enum": ["trace", "normal"]},
+        "profile": {"type": "string", "minLength": 1},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "planned_rounds": {"type": "integer", "minimum": 1}
+      },
+      "additionalProperties": true
+    },
+    "bmc": {
+      "type": "object",
+      "required": ["status", "reason"],
+      "properties": {
+        "status": {"const": "out_of_scope"},
+        "reason": {"type": "string", "minLength": 1}
+      },
+      "additionalProperties": true
+    },
+    "layerStatus": {"enum": ["pass", "fail", "blocked", "not_run"]},
+    "layers": {
+      "type": "object",
+      "required": ["required", "optional"],
+      "properties": {
+        "required": {
+          "type": "object",
+          "required": ["program_sram", "fresh_ready", "host_ack", "pwm_state", "fan3_tach_trend", "timeout_fallback", "disable", "ptc_command_path"],
+          "properties": {
+            "program_sram": {"$ref": "#/$defs/layerStatus"},
+            "fresh_ready": {"$ref": "#/$defs/layerStatus"},
+            "host_ack": {"$ref": "#/$defs/layerStatus"},
+            "pwm_state": {"$ref": "#/$defs/layerStatus"},
+            "fan3_tach_trend": {"$ref": "#/$defs/layerStatus"},
+            "timeout_fallback": {"$ref": "#/$defs/layerStatus"},
+            "disable": {"$ref": "#/$defs/layerStatus"},
+            "ptc_command_path": {"$ref": "#/$defs/layerStatus"}
+          },
+          "additionalProperties": {"$ref": "#/$defs/layerStatus"}
+        },
+        "optional": {"type": "object", "additionalProperties": {"$ref": "#/$defs/layerStatus"}}
+      },
+      "additionalProperties": true
+    },
+    "round": {
+      "type": "object",
+      "required": ["round", "identity", "layers", "fan", "windows", "raw_samples", "correlation", "rpm", "ptc", "evidence_binding"],
+      "properties": {
+        "round": {"type": "integer", "minimum": 1, "maximum": 10},
+        "identity": {"$ref": "#/$defs/identity"},
+        "layers": {"$ref": "#/$defs/layers"},
+        "fan": {
+          "type": "object",
+          "required": ["FAN3"],
+          "properties": {
+            "FAN3": {
+              "type": "object",
+              "required": ["FG5", "FG6"],
+              "properties": {
+                "FG5": {"enum": ["detected", "absent", "intermittent"]},
+                "FG6": {"enum": ["detected", "absent", "intermittent"]}
+              },
+              "anyOf": [
+                {"properties": {"FG5": {"const": "detected"}}, "required": ["FG5"]},
+                {"properties": {"FG6": {"const": "detected"}}, "required": ["FG6"]}
+              ],
+              "additionalProperties": true
+            }
+          },
+          "additionalProperties": true
+        },
+        "windows": {"type": "array", "minItems": 42, "maxItems": 42, "items": {"$ref": "#/$defs/window"}},
+        "raw_samples": {"$ref": "#/$defs/rawSamples"},
+        "correlation": {"$ref": "#/$defs/correlation"},
+        "rpm": {"$ref": "#/$defs/rpm"},
+        "ptc": {"$ref": "#/$defs/ptc"},
+        "evidence_binding": {"$ref": "#/$defs/evidenceBinding"}
+      },
+      "additionalProperties": true
+    },
+    "window": {
+      "type": "object",
+      "required": ["index", "start_s", "end_s", "continuous", "snapshot_seq", "overflow_mask"],
+      "properties": {
+        "index": {"type": "integer", "minimum": 0},
+        "start_s": {"type": "number"},
+        "end_s": {"type": "number"},
+        "continuous": {"const": true},
+        "snapshot_seq": {"type": "integer", "minimum": 0, "maximum": 4294967295},
+        "overflow_mask": {"type": "integer", "minimum": 0, "maximum": 255}
+      },
+      "additionalProperties": true
+    },
+    "fanSample": {
+      "type": "object",
+      "required": ["window_edges", "rpm"],
+      "properties": {
+        "window_edges": {"type": "integer", "minimum": 0},
+        "rpm": {"type": "number", "minimum": 0}
+      },
+      "additionalProperties": true
+    },
+    "rawSample": {
+      "type": "object",
+      "required": ["fan_setting_percent", "snapshot_seq", "overflow_mask", "FG5", "FG6"],
+      "properties": {
+        "fan_setting_percent": {"enum": [0, 20, 40, 60, 80, 100]},
+        "snapshot_seq": {"type": "integer", "minimum": 0, "maximum": 4294967295},
+        "overflow_mask": {"type": "integer", "minimum": 0, "maximum": 255},
+        "FG5": {"$ref": "#/$defs/fanSample"},
+        "FG6": {"$ref": "#/$defs/fanSample"}
+      },
+      "additionalProperties": true
+    },
+    "rawSamples": {
+      "type": "array",
+      "minItems": 30,
+      "maxItems": 30,
+      "items": {"$ref": "#/$defs/rawSample"}
+    },
+    "correlation": {
+      "type": "object",
+      "required": ["spearman_rho", "low_mean_rpm", "high_mean_rpm", "high_significantly_higher", "samples"],
+      "properties": {
+        "spearman_rho": {"type": "number", "minimum": -1, "maximum": 1},
+        "low_mean_rpm": {"type": "number", "minimum": 0},
+        "high_mean_rpm": {"type": "number", "minimum": 0},
+        "high_significantly_higher": {"const": true},
+        "samples": {
+          "type": "array",
+          "minItems": 6,
+          "maxItems": 6,
+          "items": {
+            "type": "object",
+            "required": ["fan_setting_percent", "rpm"],
+            "properties": {
+              "fan_setting_percent": {"type": "number"},
+              "rpm": {"type": "number", "minimum": 0}
+            },
+            "additionalProperties": true
+          }
+        }
+      },
+      "additionalProperties": true
+    },
+    "rpm": {
+      "type": "object",
+      "required": ["status", "reason"],
+      "properties": {"status": {"const": "not_qualified"}, "reason": {"type": "string", "minLength": 1}},
+      "additionalProperties": true
+    },
+    "ptc": {
+      "type": "object",
+      "required": ["actuation", "measurement"],
+      "properties": {"actuation": {"const": true}, "measurement": {"const": "not_run"}},
+      "additionalProperties": true
+    },
+    "artifactBinding": {
+      "type": "object",
+      "required": ["path", "sha256"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "status": {"type": "string"}
+      },
+      "additionalProperties": true
+    },
+    "staticQualificationLayer": {
+      "type": "object",
+      "required": ["status", "artifacts"],
+      "properties": {
+        "status": {"const": "pass"},
+        "artifacts": {"type": "object", "minProperties": 1, "additionalProperties": {"$ref": "#/$defs/artifactBinding"}}
+      },
+      "additionalProperties": true
+    },
+    "staticQualification": {
+      "type": "object",
+      "required": ["schema", "status", "profile", "profile_id", "layers", "variants", "failures"],
+      "properties": {
+        "schema": {"const": "prod2u-p4-static-qualification-v1"},
+        "status": {"const": "pass"},
+        "profile": {"const": "prod2u-fan-tach-binary921-v2"},
+        "profile_id": {"const": 4},
+        "layers": {
+          "type": "object",
+          "required": ["source", "protocol", "rtl", "formal", "td_normal", "td_trace", "package"],
+          "properties": {
+            "source": {"$ref": "#/$defs/staticQualificationLayer"},
+            "protocol": {"$ref": "#/$defs/staticQualificationLayer"},
+            "rtl": {"$ref": "#/$defs/staticQualificationLayer"},
+            "formal": {"$ref": "#/$defs/staticQualificationLayer"},
+            "td_normal": {"$ref": "#/$defs/staticQualificationLayer"},
+            "td_trace": {"$ref": "#/$defs/staticQualificationLayer"},
+            "package": {"$ref": "#/$defs/staticQualificationLayer"}
+          },
+          "additionalProperties": false
+        },
+        "variants": {"type": "object"},
+        "failures": {"type": "array", "maxItems": 0, "items": {"type": "string"}}
+      },
+      "additionalProperties": true
+    },
+    "receiptBinding": {
+      "allOf": [
+        {"$ref": "#/$defs/artifactBinding"},
+        {"required": ["status"], "properties": {"status": {"const": "pass"}}}
+      ]
+    },
+    "bindingIdentity": {
+      "type": "object",
+      "required": ["dut_id", "build_id", "bitstream_sha256", "variant", "profile", "source_manifest_sha256"],
+      "properties": {
+        "dut_id": {"type": "string", "minLength": 1},
+        "build_id": {"type": "string", "minLength": 1},
+        "bitstream_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "variant": {"enum": ["trace", "normal"]},
+        "profile": {"type": "string", "minLength": 1},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "evidenceBinding": {
+      "type": "object",
+      "required": ["programmer_receipt", "pre_program_raw", "combined_rx_raw", "raw_transcript", "td_receipt", "source_manifest", "package_manifest", "package_inventory", "identity"],
+      "properties": {
+        "programmer_receipt": {"$ref": "#/$defs/receiptBinding"},
+        "pre_program_raw": {"$ref": "#/$defs/artifactBinding"},
+        "combined_rx_raw": {"$ref": "#/$defs/artifactBinding"},
+        "raw_transcript": {"$ref": "#/$defs/artifactBinding"},
+        "td_receipt": {"$ref": "#/$defs/artifactBinding"},
+        "source_manifest": {"$ref": "#/$defs/artifactBinding"},
+        "package_manifest": {"$ref": "#/$defs/artifactBinding"},
+        "package_inventory": {"$ref": "#/$defs/artifactBinding"},
+        "identity": {"$ref": "#/$defs/bindingIdentity"}
+      },
+      "additionalProperties": true
+    }
+  }
+}

+ 227 - 0
schemas/prod2u_p4_evidence.schema.json

@@ -0,0 +1,227 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-p4-evidence-v2",
+  "title": "Prod2U P4 offline evidence v2",
+  "type": "object",
+  "required": ["schema", "evidence_id", "campaign_id", "campaign_identity", "round", "identity", "bmc", "layers", "fan", "windows", "raw_samples", "correlation", "rpm", "ptc", "evidence_binding"],
+  "properties": {
+    "schema": {"const": "prod2u-p4-evidence-v2"},
+    "evidence_id": {"type": "string", "minLength": 1},
+    "campaign_id": {"type": "string", "minLength": 1},
+    "campaign_identity": {"$ref": "#/$defs/identity"},
+    "round": {"type": "integer", "minimum": 1, "maximum": 10},
+    "identity": {"$ref": "#/$defs/identity"},
+    "bmc": {"$ref": "#/$defs/bmc"},
+    "layers": {"$ref": "#/$defs/layers"},
+    "fan": {"$ref": "#/$defs/fan"},
+    "windows": {"$ref": "#/$defs/windows"},
+    "raw_samples": {"$ref": "#/$defs/rawSamples"},
+    "correlation": {"$ref": "#/$defs/correlation"},
+    "rpm": {"$ref": "#/$defs/rpm"},
+    "ptc": {"$ref": "#/$defs/ptc"},
+    "evidence_binding": {"$ref": "#/$defs/evidenceBinding"}
+  },
+  "additionalProperties": true,
+  "$defs": {
+    "identity": {
+      "type": "object",
+      "required": ["dut_id", "build_id", "bitstream_sha256", "profile"],
+      "properties": {
+        "dut_id": {"type": "string", "minLength": 1},
+        "build_id": {"type": "string", "minLength": 1},
+        "bitstream_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "variant": {"enum": ["trace", "normal"]},
+        "profile": {"type": "string", "minLength": 1},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "planned_rounds": {"const": 10}
+      },
+      "additionalProperties": true
+    },
+    "bmc": {
+      "type": "object",
+      "required": ["status", "reason"],
+      "properties": {
+        "status": {"const": "out_of_scope"},
+        "reason": {"type": "string", "minLength": 1}
+      },
+      "additionalProperties": true
+    },
+    "layerStatus": {"enum": ["pass", "fail", "blocked", "not_run"]},
+    "layers": {
+      "type": "object",
+      "required": ["required", "optional"],
+      "properties": {
+        "required": {
+          "type": "object",
+          "required": ["program_sram", "fresh_ready", "host_ack", "pwm_state", "fan3_tach_trend", "timeout_fallback", "disable", "ptc_command_path"],
+          "properties": {
+            "program_sram": {"$ref": "#/$defs/layerStatus"},
+            "fresh_ready": {"$ref": "#/$defs/layerStatus"},
+            "host_ack": {"$ref": "#/$defs/layerStatus"},
+            "pwm_state": {"$ref": "#/$defs/layerStatus"},
+            "fan3_tach_trend": {"$ref": "#/$defs/layerStatus"},
+            "timeout_fallback": {"$ref": "#/$defs/layerStatus"},
+            "disable": {"$ref": "#/$defs/layerStatus"},
+            "ptc_command_path": {"$ref": "#/$defs/layerStatus"}
+          },
+          "additionalProperties": {"$ref": "#/$defs/layerStatus"}
+        },
+        "optional": {
+          "type": "object",
+          "additionalProperties": {"$ref": "#/$defs/layerStatus"}
+        }
+      },
+      "additionalProperties": true
+    },
+    "fanStatus": {"enum": ["detected", "absent", "intermittent"]},
+    "fan": {
+      "type": "object",
+      "required": ["FAN3"],
+      "properties": {
+        "FAN3": {
+          "type": "object",
+          "required": ["FG5", "FG6"],
+          "properties": {
+            "FG5": {"$ref": "#/$defs/fanStatus"},
+            "FG6": {"$ref": "#/$defs/fanStatus"}
+          },
+          "anyOf": [
+            {"properties": {"FG5": {"const": "detected"}}, "required": ["FG5"]},
+            {"properties": {"FG6": {"const": "detected"}}, "required": ["FG6"]}
+          ],
+          "additionalProperties": true
+        }
+      },
+      "additionalProperties": true
+    },
+    "window": {
+      "type": "object",
+      "required": ["index", "start_s", "end_s", "continuous", "snapshot_seq", "overflow_mask"],
+      "properties": {
+        "index": {"type": "integer", "minimum": 0},
+        "start_s": {"type": "number"},
+        "end_s": {"type": "number"},
+        "continuous": {"const": true},
+        "snapshot_seq": {"type": "integer", "minimum": 0, "maximum": 4294967295},
+        "overflow_mask": {"type": "integer", "minimum": 0, "maximum": 255}
+      },
+      "additionalProperties": true
+    },
+    "windows": {"type": "array", "minItems": 42, "maxItems": 42, "items": {"$ref": "#/$defs/window"}},
+    "fanSample": {
+      "type": "object",
+      "required": ["window_edges", "rpm"],
+      "properties": {
+        "window_edges": {"type": "integer", "minimum": 0},
+        "rpm": {"type": "number", "minimum": 0}
+      },
+      "additionalProperties": true
+    },
+    "rawSample": {
+      "type": "object",
+      "required": ["fan_setting_percent", "snapshot_seq", "overflow_mask", "FG5", "FG6"],
+      "properties": {
+        "fan_setting_percent": {"enum": [0, 20, 40, 60, 80, 100]},
+        "snapshot_seq": {"type": "integer", "minimum": 0, "maximum": 4294967295},
+        "overflow_mask": {"type": "integer", "minimum": 0, "maximum": 255},
+        "FG5": {"$ref": "#/$defs/fanSample"},
+        "FG6": {"$ref": "#/$defs/fanSample"}
+      },
+      "additionalProperties": true
+    },
+    "rawSamples": {
+      "type": "array",
+      "minItems": 30,
+      "maxItems": 30,
+      "items": {"$ref": "#/$defs/rawSample"}
+    },
+    "correlation": {
+      "type": "object",
+      "required": ["spearman_rho", "low_mean_rpm", "high_mean_rpm", "high_significantly_higher", "samples"],
+      "properties": {
+        "spearman_rho": {"type": "number", "minimum": -1, "maximum": 1},
+        "low_mean_rpm": {"type": "number", "minimum": 0},
+        "high_mean_rpm": {"type": "number", "minimum": 0},
+        "high_significantly_higher": {"const": true},
+        "samples": {
+          "type": "array",
+          "minItems": 6,
+          "maxItems": 6,
+          "items": {
+            "type": "object",
+            "required": ["fan_setting_percent", "rpm"],
+            "properties": {
+              "fan_setting_percent": {"type": "number"},
+              "rpm": {"type": "number", "minimum": 0}
+            },
+            "additionalProperties": true
+          }
+        }
+      },
+      "additionalProperties": true
+    },
+    "rpm": {
+      "type": "object",
+      "required": ["status", "reason"],
+      "properties": {
+        "status": {"const": "not_qualified"},
+        "reason": {"type": "string", "minLength": 1}
+      },
+      "additionalProperties": true
+    },
+    "ptc": {
+      "type": "object",
+      "required": ["actuation", "measurement"],
+      "properties": {
+        "actuation": {"const": true},
+        "measurement": {"const": "not_run"}
+      },
+      "additionalProperties": true
+    },
+    "artifactBinding": {
+      "type": "object",
+      "required": ["path", "sha256"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "status": {"type": "string"}
+      },
+      "additionalProperties": true
+    },
+    "receiptBinding": {
+      "allOf": [
+        {"$ref": "#/$defs/artifactBinding"},
+        {"required": ["status"], "properties": {"status": {"const": "pass"}}}
+      ]
+    },
+    "bindingIdentity": {
+      "type": "object",
+      "required": ["dut_id", "build_id", "bitstream_sha256", "variant", "profile", "source_manifest_sha256"],
+      "properties": {
+        "dut_id": {"type": "string", "minLength": 1},
+        "build_id": {"type": "string", "minLength": 1},
+        "bitstream_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "variant": {"enum": ["trace", "normal"]},
+        "profile": {"type": "string", "minLength": 1},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "evidenceBinding": {
+      "type": "object",
+      "required": ["programmer_receipt", "pre_program_raw", "combined_rx_raw", "raw_transcript", "td_receipt", "source_manifest", "package_manifest", "package_inventory", "identity"],
+      "properties": {
+        "programmer_receipt": {"$ref": "#/$defs/receiptBinding"},
+        "pre_program_raw": {"$ref": "#/$defs/artifactBinding"},
+        "combined_rx_raw": {"$ref": "#/$defs/artifactBinding"},
+        "raw_transcript": {"$ref": "#/$defs/artifactBinding"},
+        "td_receipt": {"$ref": "#/$defs/artifactBinding"},
+        "source_manifest": {"$ref": "#/$defs/artifactBinding"},
+        "package_manifest": {"$ref": "#/$defs/artifactBinding"},
+        "package_inventory": {"$ref": "#/$defs/artifactBinding"},
+        "identity": {"$ref": "#/$defs/bindingIdentity"}
+      },
+      "additionalProperties": true
+    }
+  }
+}

+ 170 - 0
schemas/prod2u_p4_final_gate.schema.json

@@ -0,0 +1,170 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-p4-final-gate-v2",
+  "title": "Prod2U P4 offline final gate v2",
+  "type": "object",
+  "required": ["schema", "status", "campaign_id", "campaign_identity", "bmc", "qualification", "layers", "round_count", "evidence_bindings", "failures"],
+  "properties": {
+    "schema": {"const": "prod2u-p4-final-gate-v2"},
+    "status": {"enum": ["pass", "fail", "blocked"]},
+    "campaign_id": {"type": "string", "minLength": 1},
+    "bmc": {"$ref": "#/$defs/bmc"},
+    "qualification": {"$ref": "#/$defs/staticQualification"},
+    "layers": {"$ref": "#/$defs/layers"},
+    "round_count": {"const": 10},
+    "evidence_bindings": {
+      "type": "array",
+      "minItems": 10,
+      "maxItems": 10,
+      "items": {
+        "type": "object",
+        "required": ["round", "evidence_binding"],
+        "properties": {
+          "round": {"type": "integer", "minimum": 1, "maximum": 10},
+          "evidence_binding": {"$ref": "#/$defs/evidenceBinding"}
+        },
+        "additionalProperties": true
+      }
+    },
+    "failures": {"type": "array", "items": {"type": "string"}},
+    "campaign_identity": {"$ref": "#/$defs/identity"},
+    "summary": {"type": "object"}
+  },
+  "allOf": [
+    {
+      "if": {"properties": {"status": {"const": "pass"}}, "required": ["status"]},
+      "then": {
+        "properties": {
+          "failures": {"maxItems": 0},
+          "layers": {"properties": {"required": {"additionalProperties": {"const": "pass"}}}}
+        }
+      }
+    }
+  ],
+  "additionalProperties": true,
+  "$defs": {
+    "identity": {
+      "type": "object",
+      "required": ["dut_id", "build_id", "bitstream_sha256", "profile"],
+      "properties": {
+        "dut_id": {"type": "string", "minLength": 1},
+        "build_id": {"type": "string", "minLength": 1},
+        "bitstream_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "variant": {"enum": ["trace", "normal"]},
+        "profile": {"type": "string", "minLength": 1}
+      },
+      "additionalProperties": true
+    },
+    "bmc": {
+      "type": "object",
+      "required": ["status", "reason"],
+      "properties": {"status": {"const": "out_of_scope"}, "reason": {"type": "string", "minLength": 1}},
+      "additionalProperties": true
+    },
+    "layerStatus": {"enum": ["pass", "fail", "blocked", "not_run"]},
+    "layers": {
+      "type": "object",
+      "required": ["required", "optional"],
+      "properties": {
+        "required": {
+          "type": "object",
+          "required": ["program_sram", "fresh_ready", "host_ack", "pwm_state", "fan3_tach_trend", "timeout_fallback", "disable", "ptc_command_path"],
+          "properties": {
+            "program_sram": {"$ref": "#/$defs/layerStatus"},
+            "fresh_ready": {"$ref": "#/$defs/layerStatus"},
+            "host_ack": {"$ref": "#/$defs/layerStatus"},
+            "pwm_state": {"$ref": "#/$defs/layerStatus"},
+            "fan3_tach_trend": {"$ref": "#/$defs/layerStatus"},
+            "timeout_fallback": {"$ref": "#/$defs/layerStatus"},
+            "disable": {"$ref": "#/$defs/layerStatus"},
+            "ptc_command_path": {"$ref": "#/$defs/layerStatus"}
+          },
+          "additionalProperties": {"$ref": "#/$defs/layerStatus"}
+        },
+        "optional": {"type": "object", "additionalProperties": {"$ref": "#/$defs/layerStatus"}}
+      },
+      "additionalProperties": true
+    },
+    "artifactBinding": {
+      "type": "object",
+      "required": ["path", "sha256"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "status": {"type": "string"}
+      },
+      "additionalProperties": true
+    },
+    "staticQualificationLayer": {
+      "type": "object",
+      "required": ["status", "artifacts"],
+      "properties": {
+        "status": {"const": "pass"},
+        "artifacts": {"type": "object", "minProperties": 1, "additionalProperties": {"$ref": "#/$defs/artifactBinding"}}
+      },
+      "additionalProperties": true
+    },
+    "staticQualification": {
+      "type": "object",
+      "required": ["schema", "status", "profile", "profile_id", "layers", "variants", "failures"],
+      "properties": {
+        "schema": {"const": "prod2u-p4-static-qualification-v1"},
+        "status": {"const": "pass"},
+        "profile": {"const": "prod2u-fan-tach-binary921-v2"},
+        "profile_id": {"const": 4},
+        "layers": {
+          "type": "object",
+          "required": ["source", "protocol", "rtl", "formal", "td_normal", "td_trace", "package"],
+          "properties": {
+            "source": {"$ref": "#/$defs/staticQualificationLayer"},
+            "protocol": {"$ref": "#/$defs/staticQualificationLayer"},
+            "rtl": {"$ref": "#/$defs/staticQualificationLayer"},
+            "formal": {"$ref": "#/$defs/staticQualificationLayer"},
+            "td_normal": {"$ref": "#/$defs/staticQualificationLayer"},
+            "td_trace": {"$ref": "#/$defs/staticQualificationLayer"},
+            "package": {"$ref": "#/$defs/staticQualificationLayer"}
+          },
+          "additionalProperties": false
+        },
+        "variants": {"type": "object"},
+        "failures": {"type": "array", "maxItems": 0, "items": {"type": "string"}}
+      },
+      "additionalProperties": true
+    },
+    "receiptBinding": {
+      "allOf": [
+        {"$ref": "#/$defs/artifactBinding"},
+        {"required": ["status"], "properties": {"status": {"const": "pass"}}}
+      ]
+    },
+    "bindingIdentity": {
+      "type": "object",
+      "required": ["dut_id", "build_id", "bitstream_sha256", "variant", "profile", "source_manifest_sha256"],
+      "properties": {
+        "dut_id": {"type": "string", "minLength": 1},
+        "build_id": {"type": "string", "minLength": 1},
+        "bitstream_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "variant": {"enum": ["trace", "normal"]},
+        "profile": {"type": "string", "minLength": 1},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "evidenceBinding": {
+      "type": "object",
+      "required": ["programmer_receipt", "pre_program_raw", "combined_rx_raw", "raw_transcript", "td_receipt", "source_manifest", "package_manifest", "package_inventory", "identity"],
+      "properties": {
+        "programmer_receipt": {"$ref": "#/$defs/receiptBinding"},
+        "pre_program_raw": {"$ref": "#/$defs/artifactBinding"},
+        "combined_rx_raw": {"$ref": "#/$defs/artifactBinding"},
+        "raw_transcript": {"$ref": "#/$defs/artifactBinding"},
+        "td_receipt": {"$ref": "#/$defs/artifactBinding"},
+        "source_manifest": {"$ref": "#/$defs/artifactBinding"},
+        "package_manifest": {"$ref": "#/$defs/artifactBinding"},
+        "package_inventory": {"$ref": "#/$defs/artifactBinding"},
+        "identity": {"$ref": "#/$defs/bindingIdentity"}
+      },
+      "additionalProperties": true
+    }
+  }
+}

+ 93 - 0
schemas/prod2u_p4_qualification.schema.json

@@ -0,0 +1,93 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-p4-static-qualification-v1",
+  "title": "Prod2U P4 static qualification v1",
+  "type": "object",
+  "required": ["schema", "status", "profile", "profile_id", "layers", "variants", "failures"],
+  "properties": {
+    "schema": {"const": "prod2u-p4-static-qualification-v1"},
+    "status": {"const": "pass"},
+    "profile": {"const": "prod2u-fan-tach-binary921-v2"},
+    "profile_id": {"const": 4},
+    "layers": {
+      "type": "object",
+      "required": ["source", "protocol", "rtl", "formal", "td_normal", "td_trace", "package"],
+      "properties": {
+        "source": {"$ref": "#/$defs/sourceLayer"},
+        "protocol": {"$ref": "#/$defs/protocolLayer"},
+        "rtl": {"$ref": "#/$defs/rtlLayer"},
+        "formal": {"$ref": "#/$defs/formalLayer"},
+        "td_normal": {"$ref": "#/$defs/tdNormalLayer"},
+        "td_trace": {"$ref": "#/$defs/tdTraceLayer"},
+        "package": {"$ref": "#/$defs/packageLayer"}
+      },
+      "additionalProperties": false
+    },
+    "variants": {"type": "object"},
+    "failures": {"type": "array", "maxItems": 0, "items": {"type": "string"}}
+  },
+  "additionalProperties": true,
+  "$defs": {
+    "artifactBinding": {
+      "type": "object",
+      "required": ["path", "sha256"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "declared_sha256": {"type": ["string", "null"], "pattern": "^[0-9a-fA-F]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "layerBase": {
+      "type": "object",
+      "required": ["status", "artifacts"],
+      "properties": {
+        "status": {"const": "pass"},
+        "artifacts": {"type": "object", "additionalProperties": {"$ref": "#/$defs/artifactBinding"}}
+      },
+      "additionalProperties": true
+    },
+    "sourceLayer": {
+      "allOf": [
+        {"$ref": "#/$defs/layerBase"},
+        {"properties": {"artifacts": {"required": ["normal_source_manifest", "trace_source_manifest"]}}}
+      ]
+    },
+    "protocolLayer": {
+      "allOf": [
+        {"$ref": "#/$defs/layerBase"},
+        {"properties": {"artifacts": {"required": ["protocol_junit"]}}}
+      ]
+    },
+    "rtlLayer": {
+      "allOf": [
+        {"$ref": "#/$defs/layerBase"},
+        {"properties": {"artifacts": {"required": ["rtl_sim_receipt"]}}}
+      ]
+    },
+    "formalLayer": {
+      "allOf": [
+        {"$ref": "#/$defs/layerBase"},
+        {"properties": {"artifacts": {"required": ["formal_receipt"]}}}
+      ]
+    },
+    "tdNormalLayer": {
+      "allOf": [
+        {"$ref": "#/$defs/layerBase"},
+        {"properties": {"artifacts": {"required": ["normal_td_receipt"]}}}
+      ]
+    },
+    "tdTraceLayer": {
+      "allOf": [
+        {"$ref": "#/$defs/layerBase"},
+        {"properties": {"artifacts": {"required": ["trace_td_receipt"]}}}
+      ]
+    },
+    "packageLayer": {
+      "allOf": [
+        {"$ref": "#/$defs/layerBase"},
+        {"properties": {"artifacts": {"required": ["package_manifest", "package_inventory", "static_receipt"]}}}
+      ]
+    }
+  }
+}

+ 85 - 0
schemas/prod2u_p4_td_build_receipt.schema.json

@@ -0,0 +1,85 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-p4-td-build-receipt-v1",
+  "title": "Prod2U Profile 4 TD build receipt",
+  "type": "object",
+  "required": [
+    "schema",
+    "status",
+    "top",
+    "top_module",
+    "pin_profile",
+    "build_id",
+    "source_manifest_sha256",
+    "build_identity",
+    "bitstream",
+    "resources",
+    "timing",
+    "timing_gate",
+    "syn",
+    "phy"
+  ],
+  "properties": {
+    "schema": {"const": "prod2u-td-build-receipt-v1"},
+    "status": {"const": "pass"},
+    "pin_profile": {"const": "prod2u-fan-tach-binary921-v2"},
+    "build_id": {"type": "string", "pattern": "^[0-9A-F]{8}$"},
+    "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
+    "build_identity": {
+      "type": "object",
+      "required": ["status", "build_id", "source_manifest_sha256", "staged_manifest_sha256"],
+      "properties": {
+        "status": {"const": "pass"},
+        "build_id": {"type": "string", "pattern": "^[0-9A-F]{8}$"},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
+        "staged_manifest_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "bitstream": {
+      "type": "object",
+      "required": ["path", "size", "sha256"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "size": {"type": "integer", "minimum": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "resources": {"type": "object"},
+    "timing": {"type": "object"},
+    "timing_gate": {
+      "type": "object",
+      "required": ["status"],
+      "properties": {"status": {"const": "pass"}},
+      "additionalProperties": true
+    },
+    "syn": {
+      "type": "object",
+      "required": ["returncode", "log_has_error"],
+      "properties": {"returncode": {"const": 0}, "log_has_error": {"const": false}},
+      "additionalProperties": true
+    },
+    "phy": {
+      "type": "object",
+      "required": ["returncode", "log_has_error"],
+      "properties": {"returncode": {"const": 0}, "log_has_error": {"const": false}},
+      "additionalProperties": true
+    }
+  },
+  "oneOf": [
+    {
+      "properties": {
+        "top": {"const": "prod2u_fan_tach_binary921_v2_normal"},
+        "top_module": {"const": "prod2u_fan_tach_binary921_v2_normal_top"}
+      }
+    },
+    {
+      "properties": {
+        "top": {"const": "prod2u_fan_tach_binary921_v2_trace"},
+        "top_module": {"const": "prod2u_fan_tach_binary921_v2_trace_top"}
+      }
+    }
+  ],
+  "additionalProperties": true
+}

+ 89 - 5
schemas/prod2u_program_sram_receipt.schema.json

@@ -125,14 +125,45 @@
     },
     },
     "process_cleanup": {
     "process_cleanup": {
       "type": "object",
       "type": "object",
-      "required": ["status", "td_root", "graceful_close_requested", "forced_terminated", "wait_seconds", "remaining"],
+      "required": [
+        "status",
+        "td_root",
+        "identity_audit_completed_before_action",
+        "ownership_policy",
+        "discovered_processes",
+        "harness_owned_processes",
+        "blocking_processes",
+        "graceful_close_requested",
+        "forced_terminated",
+        "wait_seconds",
+        "remaining",
+        "post_action_audit_completed",
+        "post_action_discovered_processes",
+        "post_action_harness_owned_processes",
+        "post_action_blocking_processes",
+        "residual_processes",
+        "post_action_errors",
+        "errors"
+      ],
       "properties": {
       "properties": {
-        "status": {"const": "pass"},
+        "status": {"enum": ["pass", "fail"]},
         "td_root": {"type": "string", "minLength": 1},
         "td_root": {"type": "string", "minLength": 1},
-        "graceful_close_requested": {"type": "array", "items": {"type": "string"}},
-        "forced_terminated": {"type": "array", "items": {"type": "string"}},
+        "identity_audit_completed_before_action": {"const": true},
+        "ownership_policy": {"$ref": "#/$defs/processOwnershipPolicy"},
+        "discovered_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
+        "harness_owned_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
+        "blocking_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
+        "graceful_close_requested": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
+        "forced_terminated": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
         "wait_seconds": {"const": 5.0},
         "wait_seconds": {"const": 5.0},
-        "remaining": {"type": "array", "maxItems": 0}
+        "remaining": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
+        "post_action_audit_completed": {"const": true},
+        "post_action_discovered_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
+        "post_action_harness_owned_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
+        "post_action_blocking_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
+        "residual_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
+        "post_action_errors": {"type": "array", "items": {"type": "string"}, "maxItems": 0},
+        "errors": {"type": "array", "items": {"type": "string"}, "maxItems": 0}
       },
       },
       "additionalProperties": true
       "additionalProperties": true
     },
     },
@@ -216,12 +247,65 @@
               "real_ptc_fan_action_attempted": {"const": false},
               "real_ptc_fan_action_attempted": {"const": false},
               "external_programming_command_executed": {"const": true}
               "external_programming_command_executed": {"const": true}
             }
             }
+          },
+          "process_cleanup": {
+            "properties": {
+              "status": {"const": "pass"},
+              "identity_audit_completed_before_action": {"const": true},
+              "blocking_processes": {"maxItems": 0},
+              "remaining": {"maxItems": 0},
+              "post_action_audit_completed": {"const": true},
+              "residual_processes": {"maxItems": 0},
+              "post_action_errors": {"maxItems": 0},
+              "errors": {"maxItems": 0}
+            }
           }
           }
         }
         }
       }
       }
     }
     }
   ],
   ],
   "$defs": {
   "$defs": {
+    "processIdentity": {
+      "type": "object",
+      "required": ["pid", "name", "path", "user", "session_id", "parent_pid", "command_line", "start_time", "exe_sha256"],
+      "properties": {
+        "pid": {"type": "integer", "minimum": 1},
+        "name": {"enum": ["td.exe", "td_commands_prompt.exe", "bw.exe", "bw_commands_prompt.exe", "hwserver.exe"]},
+        "path": {"type": "string", "minLength": 1},
+        "user": {"type": "string", "minLength": 1},
+        "session_id": {"type": "integer", "minimum": 0},
+        "parent_pid": {"type": "integer", "minimum": 0},
+        "command_line": {"type": "string", "minLength": 1},
+        "start_time": {"type": "string", "minLength": 1},
+        "exe_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
+      },
+      "additionalProperties": false
+    },
+    "processOwnershipPolicy": {
+      "type": "object",
+      "required": ["owner", "session_id", "parent_pid", "approved_binaries", "command_line"],
+      "properties": {
+        "owner": {"type": "string", "minLength": 1},
+        "session_id": {"type": "integer", "minimum": 0},
+        "parent_pid": {"type": "integer", "minimum": 1},
+        "approved_binaries": {
+          "type": "array",
+          "minItems": 1,
+          "items": {
+            "type": "object",
+            "required": ["name", "path", "exe_sha256"],
+            "properties": {
+              "name": {"enum": ["bw_commands_prompt.exe"]},
+              "path": {"type": "string", "minLength": 1},
+              "exe_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
+            },
+            "additionalProperties": false
+          }
+        },
+        "command_line": {"type": "string", "minLength": 1}
+      },
+      "additionalProperties": false
+    },
     "nonEmptySha256": {
     "nonEmptySha256": {
       "type": "string",
       "type": "string",
       "pattern": "^[0-9a-f]{64}$",
       "pattern": "^[0-9a-f]{64}$",

+ 9 - 34
src/rtl/binary921_frame_tx.v

@@ -1,7 +1,9 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module binary921_frame_tx #(
 module binary921_frame_tx #(
-    parameter integer MAX_PAYLOAD_BYTES = 64
+    parameter integer MAX_PAYLOAD_BYTES = 64,
+    parameter integer LATCH_PAYLOAD = 1,
+    parameter [7:0] VERSION = 8'h01
 ) (
 ) (
     input  wire                         clk,
     input  wire                         clk,
     input  wire                         rst_n,
     input  wire                         rst_n,
@@ -20,13 +22,10 @@ module binary921_frame_tx #(
 );
 );
     localparam [7:0] MAGIC0 = 8'ha5;
     localparam [7:0] MAGIC0 = 8'ha5;
     localparam [7:0] MAGIC1 = 8'h5a;
     localparam [7:0] MAGIC1 = 8'h5a;
-    localparam [7:0] VERSION = 8'h01;
-
     reg [7:0] byte_index;
     reg [7:0] byte_index;
     reg [7:0] total_bytes;
     reg [7:0] total_bytes;
     reg [15:0] crc;
     reg [15:0] crc;
     wire [15:0] crc_next;
     wire [15:0] crc_next;
-    reg [7:0] send_byte;
     reg [15:0] crc_after_accept;
     reg [15:0] crc_after_accept;
     reg [7:0] next_byte_index;
     reg [7:0] next_byte_index;
     reg [7:0] next_send_byte;
     reg [7:0] next_send_byte;
@@ -39,45 +38,21 @@ module binary921_frame_tx #(
 
 
     binary921_crc16 u_crc (
     binary921_crc16 u_crc (
         .crc_in(crc),
         .crc_in(crc),
-        .data(send_byte),
+        .data(tx_data),
         .crc_out(crc_next)
         .crc_out(crc_next)
     );
     );
 
 
     function [7:0] payload_byte;
     function [7:0] payload_byte;
         input [7:0] index;
         input [7:0] index;
         begin
         begin
-            payload_byte = latched_payload[(index * 8) +: 8];
+            if (LATCH_PAYLOAD != 0) begin
+                payload_byte = latched_payload[(index * 8) +: 8];
+            end else begin
+                payload_byte = payload[(index * 8) +: 8];
+            end
         end
         end
     endfunction
     endfunction
 
 
-    always @* begin
-        case (byte_index)
-            8'd0: send_byte = MAGIC0;
-            8'd1: send_byte = MAGIC1;
-            8'd2: send_byte = VERSION;
-            8'd3: send_byte = latched_profile_id;
-            8'd4: send_byte = latched_frame_type;
-            8'd5: send_byte = latched_frame_seq[7:0];
-            8'd6: send_byte = latched_frame_seq[15:8];
-            8'd7: send_byte = latched_frame_seq[23:16];
-            8'd8: send_byte = latched_frame_seq[31:24];
-            8'd9: send_byte = latched_timestamp_tick[7:0];
-            8'd10: send_byte = latched_timestamp_tick[15:8];
-            8'd11: send_byte = latched_timestamp_tick[23:16];
-            8'd12: send_byte = latched_timestamp_tick[31:24];
-            8'd13: send_byte = latched_payload_len;
-            default: begin
-                if (byte_index < (8'd14 + latched_payload_len)) begin
-                    send_byte = payload_byte(byte_index - 8'd14);
-                end else if (byte_index == (8'd14 + latched_payload_len)) begin
-                    send_byte = crc[7:0];
-                end else begin
-                    send_byte = crc[15:8];
-                end
-            end
-        endcase
-    end
-
     always @* begin
     always @* begin
         crc_after_accept = crc;
         crc_after_accept = crc;
         if (byte_index >= 8'd2 && byte_index < (8'd14 + latched_payload_len)) begin
         if (byte_index >= 8'd2 && byte_index < (8'd14 + latched_payload_len)) begin

+ 95 - 0
src/rtl/prod2u_fan_pwm_bank.v

@@ -0,0 +1,95 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_pwm_bank #(
+    parameter integer FAN_COUNT = 4,
+    parameter integer PWM_PERIOD_TICKS = 1000,
+    parameter integer PWM_COUNTER_WIDTH = 10,
+    parameter [6:0] STARTUP_PERCENT = 7'd30,
+    parameter [6:0] FALLBACK_PERCENT = 7'd30
+) (
+    input  wire                         clk,
+    input  wire                         rst_n,
+    input  wire                         startup_active,
+    input  wire [FAN_COUNT-1:0]         disable_mask,
+    input  wire [FAN_COUNT-1:0]         fallback,
+    input  wire [FAN_COUNT-1:0]         requested_enable,
+    input  wire [FAN_COUNT*7-1:0]       requested_percent,
+    output reg  [FAN_COUNT-1:0]         active_enable,
+    output reg  [FAN_COUNT*7-1:0]       active_percent,
+    output reg  [FAN_COUNT-1:0]         fan_pwm_raw,
+    output reg                          commit_pulse
+);
+    reg [PWM_COUNTER_WIDTH-1:0] pwm_tick;
+    integer i;
+
+    generate
+        if (!(((PWM_PERIOD_TICKS == 1000) && (PWM_COUNTER_WIDTH >= 10)) ||
+              ((PWM_PERIOD_TICKS == 100) && (PWM_COUNTER_WIDTH >= 7)))) begin : g_supported_fan_period_required
+            prod2u_fan_pwm_period_must_be_100_or_1000_ticks u_period_error();
+        end
+    endgenerate
+
+    function [PWM_COUNTER_WIDTH-1:0] raw_ticks_from_connector_percent;
+        input [6:0] connector_percent;
+        reg [PWM_COUNTER_WIDTH-1:0] raw_percent_ticks;
+        begin
+            // A high CPLD output turns on the board NPN and pulls the fan PWM line low.
+            // SET_FAN P is connector-high duty, so the pre-inversion CPLD duty is 100-P.
+            raw_percent_ticks = {{(PWM_COUNTER_WIDTH-7){1'b0}}, (7'd100 - connector_percent)};
+            if (PWM_PERIOD_TICKS == 1000) begin
+                raw_ticks_from_connector_percent = (raw_percent_ticks << 3) + (raw_percent_ticks << 1);
+            end else begin
+                raw_ticks_from_connector_percent = raw_percent_ticks;
+            end
+        end
+    endfunction
+
+    always @(*) begin
+        fan_pwm_raw = {FAN_COUNT{1'b0}};
+        for (i = 0; i < FAN_COUNT; i = i + 1) begin
+            if (active_enable[i]) begin
+                fan_pwm_raw[i] = pwm_tick <
+                    raw_ticks_from_connector_percent(active_percent[(i*7) +: 7]);
+            end
+        end
+    end
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            pwm_tick <= {PWM_COUNTER_WIDTH{1'b0}};
+            active_enable <= {FAN_COUNT{1'b0}};
+            active_percent <= {FAN_COUNT*7{1'b0}};
+            commit_pulse <= 1'b0;
+        end else begin
+            commit_pulse <= 1'b0;
+            if (pwm_tick == PWM_PERIOD_TICKS - 1) begin
+                pwm_tick <= {PWM_COUNTER_WIDTH{1'b0}};
+                commit_pulse <= 1'b1;
+                for (i = 0; i < FAN_COUNT; i = i + 1) begin
+                    if (disable_mask[i]) begin
+                        active_enable[i] <= 1'b0;
+                        active_percent[(i*7) +: 7] <= 7'd0;
+                    end else if (fallback[i]) begin
+                        active_enable[i] <= 1'b1;
+                        active_percent[(i*7) +: 7] <= FALLBACK_PERCENT;
+                    end else if (startup_active) begin
+                        active_enable[i] <= 1'b1;
+                        active_percent[(i*7) +: 7] <= STARTUP_PERCENT;
+                    end else if (requested_enable[i]) begin
+                        active_enable[i] <= 1'b1;
+                        if (requested_percent[(i*7) +: 7] > 7'd100) begin
+                            active_percent[(i*7) +: 7] <= 7'd100;
+                        end else begin
+                            active_percent[(i*7) +: 7] <= requested_percent[(i*7) +: 7];
+                        end
+                    end else begin
+                        active_enable[i] <= 1'b0;
+                        active_percent[(i*7) +: 7] <= 7'd0;
+                    end
+                end
+            end else begin
+                pwm_tick <= pwm_tick + 1'b1;
+            end
+        end
+    end
+endmodule

+ 735 - 0
src/rtl/prod2u_fan_tach_binary921_v2_core.v

@@ -0,0 +1,735 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_tach_binary921_v2_core #(
+    parameter [7:0] PROFILE_ID = 8'd4,
+    parameter integer TRACE_MODE = 0,
+    parameter [7:0] VARIANT_ID = 8'd0,
+    parameter [31:0] BUILD_ID = 32'h00000000,
+    parameter integer STARTUP_DELAY_TICKS = 250000,
+    parameter integer HOST_TIMEOUT_TICKS = 125000000,
+    parameter integer PTC_PWM_PERIOD_TICKS = 2500000,
+    parameter integer FAN_PWM_PERIOD_TICKS = 1000,
+    parameter integer TACH_WINDOW_TICKS = 25000000,
+    parameter integer TRACE_PERIOD_TICKS = 2500000,
+    parameter integer TRACE_STABILITY_GUARD_TICKS = 50000,
+    parameter integer READY_REPEAT_COUNT = 3
+) (
+    input  wire         clk,
+    input  wire         rst_n,
+
+    input  wire         command_valid,
+    output wire         command_ready,
+    input  wire [31:0]  command_seq,
+    input  wire [7:0]   command_id,
+    input  wire [7:0]   command_channel,
+    input  wire [7:0]   command_value,
+    input  wire [7:0]   command_flags,
+    input  wire [1:0]   command_result,
+
+    output reg          ack_valid,
+    input  wire         ack_ready,
+    output reg  [7:0]   ack_frame_type,
+    output reg  [31:0]  ack_seq,
+    output reg  [31:0]  ack_timestamp_tick,
+    output reg  [7:0]   ack_payload_len,
+    output reg  [63:0]  ack_payload,
+
+    output reg          response_valid,
+    input  wire         response_ready,
+    output reg  [7:0]   response_frame_type,
+    output reg  [31:0]  response_seq,
+    output reg  [31:0]  response_timestamp_tick,
+    output reg  [7:0]   response_payload_len,
+    output reg  [223:0] response_payload,
+
+    output reg          trace_valid,
+    input  wire         trace_ready,
+    output reg  [7:0]   trace_frame_type,
+    output reg  [31:0]  trace_seq,
+    output reg  [31:0]  trace_timestamp_tick,
+    output reg  [7:0]   trace_payload_len,
+    output wire [511:0] trace_payload,
+
+    output reg  [23:0]  ptc_pwm_out,
+    output wire [3:0]   fan_pwm_out,
+    input  wire [7:0]   fan_fg_in,
+    input  wire [3:0]   fan_install_in,
+    input  wire [31:0]  parser_error_count,
+    input  wire [31:0]  scheduler_trace_drop_count,
+    output reg  [167:0] ptc_active_percent,
+    output wire [27:0]  fan_active_percent,
+    output reg          timeout_active,
+    output wire [31:0]  tach_snapshot_seq
+);
+    localparam [7:0] FT_READY = 8'h01;
+    localparam [7:0] FT_HOST_ACK = 8'h06;
+    localparam [7:0] FT_FAN_TELEMETRY = 8'h0d;
+    localparam [7:0] FT_STATUS_RESPONSE = 8'h0e;
+    localparam [7:0] FT_TRACE_SNAPSHOT = 8'h0f;
+
+    localparam [7:0] CMD_SET_PTC = 8'h20;
+    localparam [7:0] CMD_SET_FAN = 8'h21;
+    localparam [7:0] CMD_GET_SENSOR = 8'h22;
+    localparam [7:0] CMD_GET_MAP = 8'h23;
+    localparam [7:0] CMD_GET_STATUS = 8'h24;
+    localparam [7:0] CMD_SET_PID_REQUESTED = 8'h25;
+    localparam [7:0] CMD_DISABLE = 8'h26;
+    localparam [7:0] CMD_GET_FAN_TELEMETRY = 8'h27;
+
+    localparam [7:0] STATUS_OK = 8'h00;
+    localparam [7:0] STATUS_UNSUPPORTED_IN_PROFILE = 8'h01;
+    localparam [7:0] STATUS_BAD_FLAGS = 8'h02;
+    localparam [7:0] STATUS_BAD_LENGTH = 8'h03;
+    localparam [7:0] STATUS_BAD_CHANNEL = 8'h04;
+    localparam [7:0] STATUS_BAD_VALUE = 8'h05;
+    localparam [7:0] STATUS_SEQ_CONFLICT = 8'h06;
+    localparam [7:0] STATUS_SEQ_JUMP = 8'h07;
+    localparam [7:0] STATUS_QUEUE_FULL = 8'h08;
+
+    localparam [1:0] RESULT_NEW = 2'd0;
+    localparam [1:0] RESULT_DUPLICATE = 2'd1;
+
+    localparam [2:0] COMMAND_IDLE = 3'd0;
+    localparam [2:0] COMMAND_WAIT_FAN = 3'd1;
+    localparam [2:0] COMMAND_WAIT_PTC = 3'd2;
+    localparam [2:0] COMMAND_WAIT_DISABLE = 3'd3;
+
+    localparam integer PTC_STEP_TICKS_CALC = PTC_PWM_PERIOD_TICKS / 100;
+    localparam integer PTC_STEP_TICKS = (PTC_STEP_TICKS_CALC > 0) ? PTC_STEP_TICKS_CALC : 1;
+    localparam integer STARTUP_COUNTER_WIDTH = 18;
+    localparam integer WATCHDOG_COUNTER_WIDTH = 27;
+    localparam integer PTC_STEP_COUNTER_WIDTH = 15;
+    localparam integer TRACE_PERIOD_COUNTER_WIDTH = 22;
+    localparam [STARTUP_COUNTER_WIDTH-1:0] STARTUP_DELAY_COUNT = STARTUP_DELAY_TICKS;
+    localparam [WATCHDOG_COUNTER_WIDTH-1:0] HOST_TIMEOUT_COUNT = HOST_TIMEOUT_TICKS;
+    localparam [PTC_STEP_COUNTER_WIDTH-1:0] PTC_STEP_COUNT = PTC_STEP_TICKS;
+    localparam [TRACE_PERIOD_COUNTER_WIDTH-1:0] TRACE_PERIOD_COUNT = TRACE_PERIOD_TICKS;
+    localparam [31:0] CAPABILITY_FLAGS =
+        32'h0000000f | ((TRACE_MODE != 0) ? 32'h00000010 : 32'h00000000);
+
+    reg [31:0] tick;
+    reg [STARTUP_COUNTER_WIDTH-1:0] startup_counter;
+    reg [7:0] ready_queued_count;
+    reg first_ready_sent;
+    reg startup_active;
+
+    reg [WATCHDOG_COUNTER_WIDTH-1:0] watchdog_counter;
+    reg disabled_latched;
+    reg [15:0] command_count;
+    reg [7:0] last_command_status;
+
+    reg [23:0] ptc_requested_enable;
+    reg [6:0] ptc_requested [0:23];
+    reg [23:0] ptc_active_enable;
+    reg [6:0] ptc_active [0:23];
+    reg [PTC_STEP_COUNTER_WIDTH-1:0] ptc_step_tick;
+    reg [6:0] ptc_phase;
+    reg ptc_commit_pulse;
+
+    reg [3:0] fan_requested_enable;
+    reg [27:0] fan_requested_percent;
+    wire [3:0] fan_active_enable;
+    wire [27:0] fan_active_percent_wire;
+    wire fan_commit_pulse;
+    wire [3:0] fan_fallback_mask;
+
+    wire [127:0] tach_sample_edges;
+    wire [7:0] tach_sample_overflow;
+    wire [31:0] tach_sample_seq;
+    wire [31:0] tach_sample_ticks;
+    wire [24:0] tach_window_tick;
+
+    reg [2:0] command_state;
+    reg [31:0] pending_seq;
+    reg [7:0] pending_command;
+    reg pending_fan_seen;
+    reg pending_ptc_seen;
+
+    reg cache_valid;
+    reg [31:0] cache_seq;
+    reg [31:0] cache_command_word;
+    reg [63:0] cache_ack_payload;
+    reg cache_has_response;
+    reg [7:0] cache_response_type;
+    reg [7:0] cache_response_len;
+
+    reg [TRACE_PERIOD_COUNTER_WIDTH-1:0] trace_period_counter;
+    reg [31:0] trace_output_seq;
+    reg [31:0] local_trace_drop_count;
+    reg [31:0] trace_parser_error_snapshot;
+    reg [3:0] trace_install_snapshot;
+    reg [511:0] trace_payload_comb;
+    reg [511:0] payload_temp;
+    reg [63:0] ack_temp;
+    integer i;
+    integer trace_i;
+
+    wire fallback_active = startup_active || timeout_active || disabled_latched;
+    wire command_needs_response =
+        (command_id == CMD_GET_STATUS) || (command_id == CMD_GET_FAN_TELEMETRY) ||
+        ((command_result == RESULT_DUPLICATE) && cache_has_response);
+    wire [31:0] watchdog_counter_32 = {{(32-WATCHDOG_COUNTER_WIDTH){1'b0}}, watchdog_counter};
+    wire [31:0] watchdog_ticks_remaining =
+        timeout_active ? 32'd0 :
+        ((watchdog_counter >= HOST_TIMEOUT_COUNT) ? 32'd0 : (HOST_TIMEOUT_TICKS - watchdog_counter_32));
+    wire trace_snapshot_window_safe =
+        (TACH_WINDOW_TICKS <= TRACE_STABILITY_GUARD_TICKS) ? 1'b1 :
+        (tach_window_tick < (TACH_WINDOW_TICKS - TRACE_STABILITY_GUARD_TICKS));
+    wire trace_snapshot_watchdog_safe = timeout_active || disabled_latched ||
+        (watchdog_ticks_remaining > TRACE_STABILITY_GUARD_TICKS);
+    wire trace_snapshot_safe = trace_snapshot_window_safe && trace_snapshot_watchdog_safe;
+
+    assign fan_fallback_mask = {4{fallback_active}};
+    assign fan_active_percent = fan_active_percent_wire;
+    assign tach_snapshot_seq = tach_sample_seq;
+    assign trace_payload = trace_payload_comb;
+    assign command_ready = rst_n && first_ready_sent && (command_state == COMMAND_IDLE) &&
+                           !ack_valid && ((TRACE_MODE == 0) || !trace_valid) &&
+                           !(command_valid && command_needs_response && response_valid);
+
+    generate
+        if ((STARTUP_DELAY_TICKS < 1) || (STARTUP_DELAY_TICKS > 262143)) begin : g_startup_counter_width_error
+            prod2u_p4_startup_delay_exceeds_counter_width u_startup_counter_width_error();
+        end
+        if ((HOST_TIMEOUT_TICKS < 1) || (HOST_TIMEOUT_TICKS > 134217727)) begin : g_watchdog_counter_width_error
+            prod2u_p4_host_timeout_exceeds_counter_width u_watchdog_counter_width_error();
+        end
+        if ((PTC_STEP_TICKS < 1) || (PTC_STEP_TICKS > 32767)) begin : g_ptc_step_counter_width_error
+            prod2u_p4_ptc_step_exceeds_counter_width u_ptc_step_counter_width_error();
+        end
+        if ((TRACE_PERIOD_TICKS < 1) || (TRACE_PERIOD_TICKS > 4194303)) begin : g_trace_period_counter_width_error
+            prod2u_p4_trace_period_exceeds_counter_width u_trace_period_counter_width_error();
+        end
+    endgenerate
+
+    prod2u_fan_pwm_bank #(
+        .PWM_PERIOD_TICKS(FAN_PWM_PERIOD_TICKS),
+        .PWM_COUNTER_WIDTH(10)
+    ) u_fan_pwm (
+        .clk(clk),
+        .rst_n(rst_n),
+        .startup_active(startup_active),
+        .disable_mask(4'd0),
+        .fallback(fan_fallback_mask),
+        .requested_enable(fan_requested_enable),
+        .requested_percent(fan_requested_percent),
+        .active_enable(fan_active_enable),
+        .active_percent(fan_active_percent_wire),
+        .fan_pwm_raw(fan_pwm_out),
+        .commit_pulse(fan_commit_pulse)
+    );
+
+    prod2u_fan_tach_capture8 #(
+        .WINDOW_TICKS(TACH_WINDOW_TICKS),
+        .WINDOW_COUNTER_WIDTH(25)
+    ) u_fan_tach (
+        .clk(clk),
+        .rst_n(rst_n),
+        .tach_in(fan_fg_in),
+        .sample_edges(tach_sample_edges),
+        .sample_overflow(tach_sample_overflow),
+        .sample_seq(tach_sample_seq),
+        .sample_ticks(tach_sample_ticks),
+        .window_tick_value(tach_window_tick)
+    );
+
+    always @(*) begin
+        ptc_pwm_out = 24'd0;
+        ptc_active_percent = 168'd0;
+        for (i = 0; i < 24; i = i + 1) begin
+            ptc_active_percent[(i*7) +: 7] = ptc_active[i];
+            if (ptc_active_enable[i] && (ptc_phase < ptc_active[i])) begin
+                ptc_pwm_out[i] = 1'b1;
+            end
+        end
+    end
+
+    always @(*) begin
+        trace_payload_comb = 512'd0;
+        trace_payload_comb[7:0] = VARIANT_ID;
+        trace_payload_comb[15:8] = {5'd0, (TRACE_MODE != 0), disabled_latched, timeout_active};
+        trace_payload_comb[31:16] = command_count;
+        trace_payload_comb[63:32] = tach_sample_seq;
+        trace_payload_comb[71:64] = tach_sample_overflow;
+        trace_payload_comb[79:72] = {4'd0, trace_install_snapshot};
+        for (trace_i = 0; trace_i < 8; trace_i = trace_i + 1) begin
+            trace_payload_comb[((10 + (trace_i*2))*8) +: 16] =
+                tach_sample_edges[(trace_i*16) +: 16];
+        end
+        trace_payload_comb[(26*8) +: 8] = {1'b0, fan_active_percent_wire[6:0]};
+        trace_payload_comb[(27*8) +: 8] = {1'b0, fan_active_percent_wire[13:7]};
+        trace_payload_comb[(28*8) +: 8] = {1'b0, fan_active_percent_wire[20:14]};
+        trace_payload_comb[(29*8) +: 8] = {1'b0, fan_active_percent_wire[27:21]};
+        for (trace_i = 0; trace_i < 24; trace_i = trace_i + 1) begin
+            trace_payload_comb[((30 + trace_i)*8) +: 8] = {1'b0, ptc_active[trace_i]};
+        end
+        trace_payload_comb[(54*8) +: 32] = trace_parser_error_snapshot;
+        trace_payload_comb[(58*8) +: 32] = scheduler_trace_drop_count + local_trace_drop_count;
+    end
+
+    function [15:0] state_hash16;
+        input [7:0] status_value;
+        begin
+            state_hash16 = {8'd0, status_value} ^
+                           {9'd0, fan_active_percent_wire[6:0]} ^
+                           {9'd0, fan_active_percent_wire[27:21]} ^
+                           {9'd0, ptc_active[0]} ^
+                           {9'd0, ptc_active[23]} ^
+                           {14'd0, disabled_latched, timeout_active};
+        end
+    endfunction
+
+    function [63:0] make_ack_payload;
+        input ok_value;
+        input [7:0] command_value_in;
+        input [7:0] status_value;
+        input [7:0] detail_value;
+        input [7:0] response_type_value;
+        input [7:0] result_flags_value;
+        reg [15:0] hash_value;
+        begin
+            hash_value = state_hash16(status_value);
+            make_ack_payload[7:0] = {7'd0, ok_value};
+            make_ack_payload[15:8] = command_value_in;
+            make_ack_payload[23:16] = status_value;
+            make_ack_payload[31:24] = detail_value;
+            make_ack_payload[39:32] = hash_value[7:0];
+            make_ack_payload[47:40] = hash_value[15:8];
+            make_ack_payload[55:48] = response_type_value;
+            make_ack_payload[63:56] = result_flags_value;
+        end
+    endfunction
+
+    task queue_ack_value;
+        input [31:0] seq_value;
+        input [7:0] command_value_in;
+        input [7:0] status_value;
+        input [7:0] detail_value;
+        input [7:0] response_type_value;
+        input [7:0] result_flags_value;
+        input ok_value;
+        input cache_value;
+        begin
+            ack_temp = make_ack_payload(
+                ok_value,
+                command_value_in,
+                status_value,
+                detail_value,
+                response_type_value,
+                result_flags_value
+            );
+            ack_valid <= 1'b1;
+            ack_frame_type <= FT_HOST_ACK;
+            ack_seq <= seq_value;
+            ack_timestamp_tick <= tick;
+            ack_payload_len <= 8'd8;
+            ack_payload <= ack_temp;
+            last_command_status <= status_value;
+            if (cache_value) begin
+                cache_valid <= 1'b1;
+                cache_seq <= seq_value;
+                cache_command_word <= {command_value_in, command_channel, command_value, command_flags};
+                cache_ack_payload <= ack_temp;
+            end
+        end
+    endtask
+
+    task queue_ready;
+        input [7:0] announcement_seq;
+        begin
+            payload_temp = 512'd0;
+            payload_temp[31:0] = BUILD_ID;
+            payload_temp[39:32] = VARIANT_ID;
+            payload_temp[47:40] = 8'h01;
+            payload_temp[55:48] = announcement_seq;
+            payload_temp[63:56] = 8'd0;
+            payload_temp[95:64] = CAPABILITY_FLAGS;
+            response_valid <= 1'b1;
+            response_frame_type <= FT_READY;
+            response_seq <= {24'd0, announcement_seq};
+            response_timestamp_tick <= tick;
+            response_payload_len <= 8'd12;
+            response_payload <= payload_temp;
+        end
+    endtask
+
+    task queue_status_response;
+        input [31:0] seq_value;
+        input cache_value;
+        begin
+            payload_temp = 512'd0;
+            payload_temp[7:0] = STATUS_OK;
+            payload_temp[15:8] = last_command_status;
+            payload_temp[23:16] = {5'd0, (TRACE_MODE != 0), disabled_latched, timeout_active};
+            payload_temp[31:24] = VARIANT_ID;
+            payload_temp[47:32] = command_count;
+            payload_temp[63:48] = 16'd0;
+            payload_temp[95:64] = watchdog_ticks_remaining;
+            payload_temp[127:96] = tach_sample_seq;
+            payload_temp[159:128] = scheduler_trace_drop_count + local_trace_drop_count;
+            payload_temp[191:160] = parser_error_count;
+            response_valid <= 1'b1;
+            response_frame_type <= FT_STATUS_RESPONSE;
+            response_seq <= seq_value;
+            response_timestamp_tick <= tick;
+            response_payload_len <= 8'd24;
+            response_payload <= payload_temp;
+            if (cache_value) begin
+                cache_has_response <= 1'b1;
+                cache_response_type <= FT_STATUS_RESPONSE;
+                cache_response_len <= 8'd24;
+            end
+        end
+    endtask
+
+    task queue_fan_telemetry;
+        input [31:0] seq_value;
+        input cache_value;
+        integer channel_index;
+        begin
+            payload_temp = 512'd0;
+            payload_temp[31:0] = tach_sample_seq;
+            payload_temp[63:32] = tach_sample_ticks;
+            payload_temp[71:64] = tach_sample_overflow;
+            payload_temp[79:72] = {4'd0, fan_install_in};
+            payload_temp[95:80] = 16'd0;
+            for (channel_index = 0; channel_index < 8; channel_index = channel_index + 1) begin
+                payload_temp[((12 + (channel_index*2))*8) +: 16] =
+                    tach_sample_edges[(channel_index*16) +: 16];
+            end
+            response_valid <= 1'b1;
+            response_frame_type <= FT_FAN_TELEMETRY;
+            response_seq <= seq_value;
+            response_timestamp_tick <= tick;
+            response_payload_len <= 8'd28;
+            response_payload <= payload_temp;
+            if (cache_value) begin
+                cache_has_response <= 1'b1;
+                cache_response_type <= FT_FAN_TELEMETRY;
+                cache_response_len <= 8'd28;
+            end
+        end
+    endtask
+
+    task queue_trace_snapshot;
+        begin
+            trace_parser_error_snapshot <= parser_error_count;
+            trace_install_snapshot <= fan_install_in;
+            trace_output_seq <= trace_output_seq + 32'd1;
+            trace_valid <= 1'b1;
+            trace_frame_type <= FT_TRACE_SNAPSHOT;
+            trace_seq <= trace_output_seq + 32'd1;
+            trace_timestamp_tick <= tick;
+            trace_payload_len <= 8'd64;
+        end
+    endtask
+
+    task set_fan_request;
+        input [7:0] channel_value;
+        input [6:0] percent_value;
+        begin
+            case (channel_value)
+                8'd1: fan_requested_percent[6:0] <= percent_value;
+                8'd2: fan_requested_percent[13:7] <= percent_value;
+                8'd3: fan_requested_percent[20:14] <= percent_value;
+                8'd4: fan_requested_percent[27:21] <= percent_value;
+                default: begin
+                end
+            endcase
+        end
+    endtask
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            ptc_step_tick <= {PTC_STEP_COUNTER_WIDTH{1'b0}};
+            ptc_phase <= 7'd0;
+            ptc_commit_pulse <= 1'b0;
+            ptc_active_enable <= 24'd0;
+            for (i = 0; i < 24; i = i + 1) begin
+                ptc_active[i] <= 7'd0;
+            end
+        end else begin
+            ptc_commit_pulse <= 1'b0;
+            if (ptc_step_tick == PTC_STEP_COUNT - 1'b1) begin
+                ptc_step_tick <= {PTC_STEP_COUNTER_WIDTH{1'b0}};
+                if (ptc_phase == 7'd99) begin
+                    ptc_phase <= 7'd0;
+                    ptc_commit_pulse <= 1'b1;
+                    for (i = 0; i < 24; i = i + 1) begin
+                        if (fallback_active || !ptc_requested_enable[i]) begin
+                            ptc_active_enable[i] <= 1'b0;
+                            ptc_active[i] <= 7'd0;
+                        end else begin
+                            ptc_active_enable[i] <= 1'b1;
+                            ptc_active[i] <= ptc_requested[i];
+                        end
+                    end
+                end else begin
+                    ptc_phase <= ptc_phase + 7'd1;
+                end
+            end else begin
+                ptc_step_tick <= ptc_step_tick + 1'b1;
+            end
+        end
+    end
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            tick <= 32'd0;
+            startup_counter <= {STARTUP_COUNTER_WIDTH{1'b0}};
+            ready_queued_count <= 8'd0;
+            first_ready_sent <= 1'b0;
+            startup_active <= 1'b1;
+            watchdog_counter <= {WATCHDOG_COUNTER_WIDTH{1'b0}};
+            timeout_active <= 1'b0;
+            disabled_latched <= 1'b0;
+            command_count <= 16'd0;
+            last_command_status <= STATUS_OK;
+            ptc_requested_enable <= 24'd0;
+            fan_requested_enable <= 4'hf;
+            fan_requested_percent <= {4{7'd30}};
+            command_state <= COMMAND_IDLE;
+            pending_seq <= 32'd0;
+            pending_command <= 8'd0;
+            pending_fan_seen <= 1'b0;
+            pending_ptc_seen <= 1'b0;
+            cache_valid <= 1'b0;
+            cache_seq <= 32'd0;
+            cache_command_word <= 32'd0;
+            cache_ack_payload <= 64'd0;
+            cache_has_response <= 1'b0;
+            cache_response_type <= 8'd0;
+            cache_response_len <= 8'd0;
+            ack_valid <= 1'b0;
+            ack_frame_type <= FT_HOST_ACK;
+            ack_seq <= 32'd0;
+            ack_timestamp_tick <= 32'd0;
+            ack_payload_len <= 8'd0;
+            ack_payload <= 64'd0;
+            response_valid <= 1'b0;
+            response_frame_type <= 8'd0;
+            response_seq <= 32'd0;
+            response_timestamp_tick <= 32'd0;
+            response_payload_len <= 8'd0;
+            response_payload <= 224'd0;
+            trace_valid <= 1'b0;
+            trace_frame_type <= FT_TRACE_SNAPSHOT;
+            trace_seq <= 32'd0;
+            trace_timestamp_tick <= 32'd0;
+            trace_payload_len <= 8'd0;
+            trace_period_counter <= {TRACE_PERIOD_COUNTER_WIDTH{1'b0}};
+            trace_output_seq <= 32'd0;
+            local_trace_drop_count <= 32'd0;
+            trace_parser_error_snapshot <= 32'd0;
+            trace_install_snapshot <= 4'd0;
+            for (i = 0; i < 24; i = i + 1) begin
+                ptc_requested[i] <= 7'd0;
+            end
+        end else begin
+            tick <= tick + 32'd1;
+
+            if (ack_valid && ack_ready) begin
+                ack_valid <= 1'b0;
+            end
+            if (response_valid && response_ready) begin
+                if (response_frame_type == FT_READY) begin
+                    first_ready_sent <= 1'b1;
+                end
+                response_valid <= 1'b0;
+            end
+            if (trace_valid && trace_ready) begin
+                trace_valid <= 1'b0;
+            end
+
+            if (startup_counter < STARTUP_DELAY_COUNT) begin
+                startup_counter <= startup_counter + 1'b1;
+                startup_active <= 1'b1;
+            end else begin
+                startup_active <= 1'b0;
+                if ((ready_queued_count < READY_REPEAT_COUNT) && !response_valid) begin
+                    queue_ready(ready_queued_count);
+                    ready_queued_count <= ready_queued_count + 8'd1;
+                end
+            end
+
+            if (!timeout_active && !disabled_latched) begin
+                if (watchdog_counter >= HOST_TIMEOUT_COUNT - 1'b1) begin
+                    watchdog_counter <= HOST_TIMEOUT_COUNT;
+                    timeout_active <= 1'b1;
+                end else begin
+                    watchdog_counter <= watchdog_counter + 1'b1;
+                end
+            end
+
+            if (TRACE_MODE != 0) begin
+                if (trace_period_counter >= TRACE_PERIOD_COUNT - 1'b1) begin
+                    if (!trace_valid && trace_snapshot_safe &&
+                        (command_state == COMMAND_IDLE) && !command_valid &&
+                        !ack_valid && !response_valid) begin
+                        trace_period_counter <= {TRACE_PERIOD_COUNTER_WIDTH{1'b0}};
+                        queue_trace_snapshot();
+                    end else if (trace_valid) begin
+                        trace_period_counter <= {TRACE_PERIOD_COUNTER_WIDTH{1'b0}};
+                        if (local_trace_drop_count != 32'hffffffff) begin
+                            local_trace_drop_count <= local_trace_drop_count + 32'd1;
+                        end
+                    end else begin
+                        trace_period_counter <= TRACE_PERIOD_COUNT - 1'b1;
+                    end
+                end else begin
+                    trace_period_counter <= trace_period_counter + 1'b1;
+                end
+            end else begin
+                trace_period_counter <= {TRACE_PERIOD_COUNTER_WIDTH{1'b0}};
+            end
+
+            if (command_state == COMMAND_WAIT_FAN) begin
+                if (fan_commit_pulse && !ack_valid) begin
+                    queue_ack_value(pending_seq, pending_command, STATUS_OK, 8'd0, 8'd0, 8'h01, 1'b1, 1'b1);
+                    cache_has_response <= 1'b0;
+                    command_state <= COMMAND_IDLE;
+                    if ((TRACE_MODE != 0) && !trace_valid && trace_snapshot_safe) begin
+                        queue_trace_snapshot();
+                    end
+                end
+            end else if (command_state == COMMAND_WAIT_PTC) begin
+                if (ptc_commit_pulse && !ack_valid) begin
+                    queue_ack_value(pending_seq, pending_command, STATUS_OK, 8'd0, 8'd0, 8'h01, 1'b1, 1'b1);
+                    cache_has_response <= 1'b0;
+                    command_state <= COMMAND_IDLE;
+                    if ((TRACE_MODE != 0) && !trace_valid && trace_snapshot_safe) begin
+                        queue_trace_snapshot();
+                    end
+                end
+            end else if (command_state == COMMAND_WAIT_DISABLE) begin
+                if (fan_commit_pulse) begin
+                    pending_fan_seen <= 1'b1;
+                end
+                if (ptc_commit_pulse) begin
+                    pending_ptc_seen <= 1'b1;
+                end
+                if ((pending_fan_seen || fan_commit_pulse) &&
+                    (pending_ptc_seen || ptc_commit_pulse) && !ack_valid) begin
+                    queue_ack_value(pending_seq, pending_command, STATUS_OK, 8'd0, 8'd0, 8'h01, 1'b1, 1'b1);
+                    cache_has_response <= 1'b0;
+                    command_state <= COMMAND_IDLE;
+                    pending_fan_seen <= 1'b0;
+                    pending_ptc_seen <= 1'b0;
+                    if ((TRACE_MODE != 0) && !trace_valid && trace_snapshot_safe) begin
+                        queue_trace_snapshot();
+                    end
+                end
+            end
+
+            if (command_valid && command_ready) begin
+                if (command_result == RESULT_DUPLICATE) begin
+                    if (cache_valid && (cache_seq == command_seq) &&
+                        (cache_command_word == {command_id, command_channel, command_value, command_flags})) begin
+                        ack_valid <= 1'b1;
+                        ack_frame_type <= FT_HOST_ACK;
+                        ack_seq <= command_seq;
+                        ack_timestamp_tick <= tick;
+                        ack_payload_len <= 8'd8;
+                        ack_payload <= cache_ack_payload | 64'h0200000000000000;
+                        if (cache_has_response) begin
+                            response_valid <= 1'b1;
+                            response_frame_type <= cache_response_type;
+                            response_seq <= command_seq;
+                            response_timestamp_tick <= tick;
+                            response_payload_len <= cache_response_len;
+                        end
+                        if ((command_id == CMD_GET_STATUS) || (command_id == CMD_GET_FAN_TELEMETRY)) begin
+                            if (!timeout_active) begin
+                                watchdog_counter <= {WATCHDOG_COUNTER_WIDTH{1'b0}};
+                            end
+                        end
+                    end else begin
+                        queue_ack_value(command_seq, command_id, STATUS_SEQ_CONFLICT, 8'd0, 8'd0, 8'd0, 1'b0, 1'b0);
+                    end
+                end else if (command_result != RESULT_NEW) begin
+                    queue_ack_value(command_seq, command_id, STATUS_SEQ_CONFLICT, 8'd0, 8'd0, 8'd0, 1'b0, 1'b0);
+                end else begin
+                    command_count <= command_count + 16'd1;
+                    cache_has_response <= 1'b0;
+                    if (command_flags != 8'd0) begin
+                        queue_ack_value(command_seq, command_id, STATUS_BAD_FLAGS, command_flags, 8'd0, 8'd0, 1'b0, 1'b1);
+                    end else if (command_id == CMD_SET_FAN) begin
+                        if ((command_channel < 8'd1) || (command_channel > 8'd4)) begin
+                            queue_ack_value(command_seq, command_id, STATUS_BAD_CHANNEL, command_channel, 8'd0, 8'd0, 1'b0, 1'b1);
+                        end else if (command_value > 8'd100) begin
+                            queue_ack_value(command_seq, command_id, STATUS_BAD_VALUE, command_value, 8'd0, 8'd0, 1'b0, 1'b1);
+                        end else begin
+                            set_fan_request(command_channel, command_value[6:0]);
+                            fan_requested_enable <= 4'hf;
+                            timeout_active <= 1'b0;
+                            disabled_latched <= 1'b0;
+                            watchdog_counter <= {WATCHDOG_COUNTER_WIDTH{1'b0}};
+                            pending_seq <= command_seq;
+                            pending_command <= command_id;
+                            command_state <= COMMAND_WAIT_FAN;
+                        end
+                    end else if (command_id == CMD_SET_PTC) begin
+                        if ((command_channel < 8'd1) || (command_channel > 8'd24)) begin
+                            queue_ack_value(command_seq, command_id, STATUS_BAD_CHANNEL, command_channel, 8'd0, 8'd0, 1'b0, 1'b1);
+                        end else if (command_value > 8'd100) begin
+                            queue_ack_value(command_seq, command_id, STATUS_BAD_VALUE, command_value, 8'd0, 8'd0, 1'b0, 1'b1);
+                        end else begin
+                            ptc_requested_enable[command_channel - 1'b1] <= 1'b1;
+                            ptc_requested[command_channel - 1'b1] <= command_value[6:0];
+                            timeout_active <= 1'b0;
+                            disabled_latched <= 1'b0;
+                            watchdog_counter <= {WATCHDOG_COUNTER_WIDTH{1'b0}};
+                            pending_seq <= command_seq;
+                            pending_command <= command_id;
+                            command_state <= COMMAND_WAIT_PTC;
+                        end
+                    end else if (command_id == CMD_DISABLE) begin
+                        if ((command_channel != 8'd0) || (command_value != 8'd0)) begin
+                            queue_ack_value(command_seq, command_id, STATUS_BAD_VALUE, command_value, 8'd0, 8'd0, 1'b0, 1'b1);
+                        end else begin
+                            disabled_latched <= 1'b1;
+                            timeout_active <= 1'b0;
+                            watchdog_counter <= {WATCHDOG_COUNTER_WIDTH{1'b0}};
+                            ptc_requested_enable <= 24'd0;
+                            fan_requested_enable <= 4'hf;
+                            fan_requested_percent <= {4{7'd30}};
+                            pending_seq <= command_seq;
+                            pending_command <= command_id;
+                            pending_fan_seen <= 1'b0;
+                            pending_ptc_seen <= 1'b0;
+                            command_state <= COMMAND_WAIT_DISABLE;
+                        end
+                    end else if (command_id == CMD_GET_FAN_TELEMETRY) begin
+                        if ((command_channel != 8'd0) || (command_value != 8'd0)) begin
+                            queue_ack_value(command_seq, command_id, STATUS_BAD_VALUE, command_value, 8'd0, 8'd0, 1'b0, 1'b1);
+                        end else begin
+                            queue_fan_telemetry(command_seq, 1'b1);
+                            queue_ack_value(command_seq, command_id, STATUS_OK, 8'd0, FT_FAN_TELEMETRY, 8'h08, 1'b1, 1'b1);
+                            if (!timeout_active) begin
+                                watchdog_counter <= {WATCHDOG_COUNTER_WIDTH{1'b0}};
+                            end
+                        end
+                    end else if (command_id == CMD_GET_STATUS) begin
+                        if ((command_channel != 8'd0) || (command_value != 8'd0)) begin
+                            queue_ack_value(command_seq, command_id, STATUS_BAD_VALUE, command_value, 8'd0, 8'd0, 1'b0, 1'b1);
+                        end else begin
+                            queue_status_response(command_seq, 1'b1);
+                            queue_ack_value(command_seq, command_id, STATUS_OK, 8'd0, FT_STATUS_RESPONSE, 8'h08, 1'b1, 1'b1);
+                            if (!timeout_active) begin
+                                watchdog_counter <= {WATCHDOG_COUNTER_WIDTH{1'b0}};
+                            end
+                        end
+                    end else if ((command_id == CMD_GET_SENSOR) || (command_id == CMD_GET_MAP) ||
+                                 (command_id == CMD_SET_PID_REQUESTED)) begin
+                        queue_ack_value(command_seq, command_id, STATUS_UNSUPPORTED_IN_PROFILE, 8'd0, 8'd0, 8'd0, 1'b0, 1'b1);
+                    end else begin
+                        queue_ack_value(command_seq, command_id, STATUS_UNSUPPORTED_IN_PROFILE, 8'd0, 8'd0, 8'd0, 1'b0, 1'b1);
+                    end
+                end
+            end
+        end
+    end
+
+    wire unused_fan_enable = ^fan_active_enable;
+    wire unused_profile = ^PROFILE_ID;
+endmodule

+ 82 - 0
src/rtl/prod2u_fan_tach_capture8.v

@@ -0,0 +1,82 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_tach_capture8 #(
+    parameter integer FAN_COUNT = 8,
+    parameter integer WINDOW_TICKS = 25000000,
+    parameter integer WINDOW_COUNTER_WIDTH = 25,
+    parameter integer EDGE_COUNTER_WIDTH = 16
+) (
+    input  wire                         clk,
+    input  wire                         rst_n,
+    input  wire [FAN_COUNT-1:0]         tach_in,
+    output reg  [FAN_COUNT*16-1:0]      sample_edges,
+    output reg  [FAN_COUNT-1:0]         sample_overflow,
+    output reg  [31:0]                  sample_seq,
+    output wire [31:0]                  sample_ticks,
+    output wire [WINDOW_COUNTER_WIDTH-1:0] window_tick_value
+);
+    reg [FAN_COUNT-1:0] tach_meta;
+    reg [FAN_COUNT-1:0] tach_sync;
+    reg [FAN_COUNT-1:0] tach_sync_prev;
+    reg [WINDOW_COUNTER_WIDTH-1:0] window_tick;
+    localparam [EDGE_COUNTER_WIDTH-1:0] EDGE_MAX = {EDGE_COUNTER_WIDTH{1'b1}};
+    reg [EDGE_COUNTER_WIDTH-1:0] window_edges [0:FAN_COUNT-1];
+    reg [FAN_COUNT-1:0] window_overflow;
+    wire [FAN_COUNT-1:0] rising_edge = tach_sync & ~tach_sync_prev;
+    integer i;
+
+    assign window_tick_value = window_tick;
+    assign sample_ticks = WINDOW_TICKS;
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            tach_meta <= {FAN_COUNT{1'b0}};
+            tach_sync <= {FAN_COUNT{1'b0}};
+            tach_sync_prev <= {FAN_COUNT{1'b0}};
+            window_tick <= {WINDOW_COUNTER_WIDTH{1'b0}};
+            sample_edges <= {FAN_COUNT*16{1'b0}};
+            sample_overflow <= {FAN_COUNT{1'b0}};
+            sample_seq <= 32'd0;
+            window_overflow <= {FAN_COUNT{1'b0}};
+            for (i = 0; i < FAN_COUNT; i = i + 1) begin
+                window_edges[i] <= {EDGE_COUNTER_WIDTH{1'b0}};
+            end
+        end else begin
+            tach_meta <= tach_in;
+            tach_sync <= tach_meta;
+            tach_sync_prev <= tach_sync;
+
+            if (window_tick == WINDOW_TICKS - 1) begin
+                window_tick <= {WINDOW_COUNTER_WIDTH{1'b0}};
+                sample_seq <= sample_seq + 32'd1;
+                for (i = 0; i < FAN_COUNT; i = i + 1) begin
+                    if (rising_edge[i]) begin
+                        if (window_edges[i] == EDGE_MAX) begin
+                            sample_edges[(i*16) +: 16] <= {{(16-EDGE_COUNTER_WIDTH){1'b0}}, EDGE_MAX};
+                            sample_overflow[i] <= 1'b1;
+                        end else begin
+                            sample_edges[(i*16) +: 16] <= {{(16-EDGE_COUNTER_WIDTH){1'b0}}, (window_edges[i] + 1'b1)};
+                            sample_overflow[i] <= window_overflow[i];
+                        end
+                    end else begin
+                        sample_edges[(i*16) +: 16] <= {{(16-EDGE_COUNTER_WIDTH){1'b0}}, window_edges[i]};
+                        sample_overflow[i] <= window_overflow[i];
+                    end
+                    window_edges[i] <= {EDGE_COUNTER_WIDTH{1'b0}};
+                    window_overflow[i] <= 1'b0;
+                end
+            end else begin
+                window_tick <= window_tick + 1'b1;
+                for (i = 0; i < FAN_COUNT; i = i + 1) begin
+                    if (rising_edge[i]) begin
+                        if (window_edges[i] == EDGE_MAX) begin
+                            window_overflow[i] <= 1'b1;
+                        end else begin
+                            window_edges[i] <= window_edges[i] + 1'b1;
+                        end
+                    end
+                end
+            end
+        end
+    end
+endmodule

+ 246 - 0
src/rtl/prod2u_p4_host_rx.v

@@ -0,0 +1,246 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_host_rx #(
+    parameter integer CLK_HZ = 25000000,
+    parameter integer INTER_BYTE_TIMEOUT_MS = 2
+) (
+    input  wire        clk,
+    input  wire        rst_n,
+    input  wire        rx_valid,
+    output wire        rx_ready,
+    input  wire [7:0]  rx_data,
+    output reg         command_valid,
+    input  wire        command_ready,
+    output reg  [31:0] command_seq,
+    output reg  [7:0]  command_id,
+    output reg  [7:0]  command_channel,
+    output reg  [7:0]  command_value,
+    output reg  [7:0]  command_flags,
+    output reg  [1:0]  command_result,
+    output reg  [15:0] crc_error_count,
+    output reg  [15:0] timeout_count,
+    output reg  [15:0] format_error_count
+);
+    localparam [7:0] MAGIC0 = 8'ha5;
+    localparam [7:0] MAGIC1 = 8'h5a;
+    localparam [7:0] VERSION = 8'h02;
+    localparam [7:0] PROFILE_ID = 8'h04;
+    localparam [7:0] HOST_CMD_TYPE = 8'h05;
+    localparam [7:0] COMMAND_LENGTH = 8'h04;
+
+    localparam [1:0] RESULT_NEW = 2'd0;
+    localparam [1:0] RESULT_DUPLICATE = 2'd1;
+    localparam [1:0] RESULT_CONFLICT = 2'd2;
+
+    localparam [2:0] ST_MAGIC0 = 3'd0;
+    localparam [2:0] ST_MAGIC1 = 3'd1;
+    localparam [2:0] ST_BODY = 3'd2;
+    localparam [2:0] ST_CRC_LO = 3'd3;
+    localparam [2:0] ST_CRC_HI = 3'd4;
+
+    localparam integer TIMEOUT_CYCLES_CALC = (CLK_HZ / 1000) * INTER_BYTE_TIMEOUT_MS;
+    localparam integer TIMEOUT_CYCLES = (TIMEOUT_CYCLES_CALC > 0) ? TIMEOUT_CYCLES_CALC : 1;
+
+    generate
+        if (TIMEOUT_CYCLES > 65535) begin : g_timeout_width_exceeded
+            prod2u_p4_host_rx_timeout_must_fit_16_bits u_timeout_width_error();
+        end
+    endgenerate
+
+    reg [2:0] state;
+    reg [4:0] body_index;
+    reg [15:0] timeout_counter;
+    reg [15:0] crc;
+    wire [15:0] crc_next;
+    reg [7:0] received_crc_lo;
+    reg [31:0] candidate_seq;
+    reg [7:0] candidate_id;
+    reg [7:0] candidate_channel;
+    reg [7:0] candidate_value;
+    reg [7:0] candidate_flags;
+    wire [31:0] candidate_command;
+    reg have_last_command;
+    reg [31:0] last_seq;
+    reg [31:0] last_command;
+
+    assign rx_ready = rst_n && !command_valid;
+    assign candidate_command = {
+        candidate_id,
+        candidate_channel,
+        candidate_value,
+        candidate_flags
+    };
+
+    binary921_crc16 u_crc (
+        .crc_in(crc),
+        .data(rx_data),
+        .crc_out(crc_next)
+    );
+
+    function [15:0] saturating_increment16;
+        input [15:0] value;
+        begin
+            if (value == 16'hffff) begin
+                saturating_increment16 = value;
+            end else begin
+                saturating_increment16 = value + 16'd1;
+            end
+        end
+    endfunction
+
+    task reset_parser_from_byte;
+        input [7:0] value;
+        begin
+            if (value == MAGIC0) begin
+                state <= ST_MAGIC1;
+            end else begin
+                state <= ST_MAGIC0;
+            end
+            body_index <= 5'd0;
+            timeout_counter <= 16'd0;
+            crc <= 16'hffff;
+        end
+    endtask
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            state <= ST_MAGIC0;
+            body_index <= 5'd0;
+            timeout_counter <= 16'd0;
+            crc <= 16'hffff;
+            received_crc_lo <= 8'd0;
+            candidate_seq <= 32'd0;
+            candidate_id <= 8'd0;
+            candidate_channel <= 8'd0;
+            candidate_value <= 8'd0;
+            candidate_flags <= 8'd0;
+            command_valid <= 1'b0;
+            command_seq <= 32'd0;
+            command_id <= 8'd0;
+            command_channel <= 8'd0;
+            command_value <= 8'd0;
+            command_flags <= 8'd0;
+            command_result <= RESULT_NEW;
+            crc_error_count <= 16'd0;
+            timeout_count <= 16'd0;
+            format_error_count <= 16'd0;
+            have_last_command <= 1'b0;
+            last_seq <= 32'd0;
+            last_command <= 32'd0;
+        end else begin
+            if (command_valid && command_ready) begin
+                command_valid <= 1'b0;
+            end
+
+            if (rx_valid && rx_ready) begin
+                timeout_counter <= 16'd0;
+                case (state)
+                    ST_MAGIC0: begin
+                        if (rx_data == MAGIC0) begin
+                            state <= ST_MAGIC1;
+                        end
+                    end
+
+                    ST_MAGIC1: begin
+                        if (rx_data == MAGIC1) begin
+                            state <= ST_BODY;
+                            body_index <= 5'd0;
+                            crc <= 16'hffff;
+                        end else if (rx_data != MAGIC0) begin
+                            state <= ST_MAGIC0;
+                        end
+                    end
+
+                    ST_BODY: begin
+                        if ((body_index == 5'd0 && rx_data != VERSION) ||
+                            (body_index == 5'd1 && rx_data != PROFILE_ID) ||
+                            (body_index == 5'd2 && rx_data != HOST_CMD_TYPE) ||
+                            (body_index == 5'd11 && rx_data != COMMAND_LENGTH)) begin
+                            format_error_count <= saturating_increment16(format_error_count);
+                            reset_parser_from_byte(rx_data);
+                        end else begin
+                            crc <= crc_next;
+                            case (body_index)
+                                5'd3: candidate_seq[7:0] <= rx_data;
+                                5'd4: candidate_seq[15:8] <= rx_data;
+                                5'd5: candidate_seq[23:16] <= rx_data;
+                                5'd6: candidate_seq[31:24] <= rx_data;
+                                5'd12: candidate_id <= rx_data;
+                                5'd13: candidate_channel <= rx_data;
+                                5'd14: candidate_value <= rx_data;
+                                5'd15: candidate_flags <= rx_data;
+                                default: begin
+                                end
+                            endcase
+                            if (body_index == 5'd15) begin
+                                state <= ST_CRC_LO;
+                                body_index <= 5'd0;
+                            end else begin
+                                body_index <= body_index + 5'd1;
+                            end
+                        end
+                    end
+
+                    ST_CRC_LO: begin
+                        received_crc_lo <= rx_data;
+                        state <= ST_CRC_HI;
+                    end
+
+                    ST_CRC_HI: begin
+                        if ({rx_data, received_crc_lo} != crc) begin
+                            crc_error_count <= saturating_increment16(crc_error_count);
+                            reset_parser_from_byte(rx_data);
+                        end else begin
+                            command_valid <= 1'b1;
+                            command_seq <= candidate_seq;
+                            command_id <= candidate_id;
+                            command_channel <= candidate_channel;
+                            command_value <= candidate_value;
+                            command_flags <= candidate_flags;
+
+                            if (!have_last_command) begin
+                                command_result <= RESULT_NEW;
+                                have_last_command <= 1'b1;
+                                last_seq <= candidate_seq;
+                                last_command <= candidate_command;
+                            end else if (candidate_seq == last_seq) begin
+                                if (candidate_command == last_command) begin
+                                    command_result <= RESULT_DUPLICATE;
+                                end else begin
+                                    command_result <= RESULT_CONFLICT;
+                                end
+                            end else if (candidate_seq == (last_seq + 32'd1)) begin
+                                command_result <= RESULT_NEW;
+                                last_seq <= candidate_seq;
+                                last_command <= candidate_command;
+                            end else begin
+                                command_result <= RESULT_CONFLICT;
+                            end
+
+                            state <= ST_MAGIC0;
+                            body_index <= 5'd0;
+                            timeout_counter <= 16'd0;
+                            crc <= 16'hffff;
+                        end
+                    end
+
+                    default: begin
+                        state <= ST_MAGIC0;
+                    end
+                endcase
+            end else if (state != ST_MAGIC0) begin
+                if (timeout_counter >= (TIMEOUT_CYCLES - 1)) begin
+                    state <= ST_MAGIC0;
+                    body_index <= 5'd0;
+                    timeout_counter <= 16'd0;
+                    crc <= 16'hffff;
+                    timeout_count <= saturating_increment16(timeout_count);
+                end else begin
+                    timeout_counter <= timeout_counter + 16'd1;
+                end
+            end else begin
+                timeout_counter <= 16'd0;
+            end
+        end
+    end
+endmodule

+ 114 - 0
src/rtl/prod2u_p4_tx_scheduler.v

@@ -0,0 +1,114 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_tx_scheduler #(
+    parameter integer MAX_PAYLOAD_BYTES = 64
+) (
+    input  wire                              clk,
+    input  wire                              rst_n,
+
+    input  wire                              ack_valid,
+    output wire                              ack_ready,
+    input  wire [7:0]                        ack_frame_type,
+    input  wire [31:0]                       ack_seq,
+    input  wire [31:0]                       ack_timestamp_tick,
+    input  wire [7:0]                        ack_payload_len,
+    input  wire [(MAX_PAYLOAD_BYTES*8)-1:0]  ack_payload,
+
+    input  wire                              response_valid,
+    output wire                              response_ready,
+    input  wire [7:0]                        response_frame_type,
+    input  wire [31:0]                       response_seq,
+    input  wire [31:0]                       response_timestamp_tick,
+    input  wire [7:0]                        response_payload_len,
+    input  wire [(MAX_PAYLOAD_BYTES*8)-1:0]  response_payload,
+
+    input  wire                              trace_valid,
+    output wire                              trace_ready,
+    input  wire [7:0]                        trace_frame_type,
+    input  wire [31:0]                       trace_seq,
+    input  wire [31:0]                       trace_timestamp_tick,
+    input  wire [7:0]                        trace_payload_len,
+    input  wire [(MAX_PAYLOAD_BYTES*8)-1:0]  trace_payload,
+
+    output wire                              frame_valid,
+    input  wire                              frame_ready,
+    output reg  [1:0]                        frame_source,
+    output wire [7:0]                        frame_type,
+    output wire [31:0]                       frame_seq,
+    output wire [31:0]                       frame_timestamp_tick,
+    output wire [7:0]                        frame_payload_len,
+    output wire [(MAX_PAYLOAD_BYTES*8)-1:0]  frame_payload,
+    output reg  [31:0]                       trace_drop_count
+);
+    localparam [1:0] SOURCE_ACK = 2'd0;
+    localparam [1:0] SOURCE_RESPONSE = 2'd1;
+    localparam [1:0] SOURCE_TRACE = 2'd2;
+
+    reg active_valid;
+    reg trace_oversize_consumed;
+    wire trace_oversize = trace_valid && (trace_payload_len > MAX_PAYLOAD_BYTES);
+
+    assign frame_valid = active_valid;
+    assign ack_ready = rst_n && active_valid && (frame_source == SOURCE_ACK) && frame_ready;
+    assign response_ready = rst_n && active_valid && (frame_source == SOURCE_RESPONSE) && frame_ready;
+    assign trace_ready = rst_n && (trace_oversize ||
+                                    (active_valid && (frame_source == SOURCE_TRACE) && frame_ready));
+
+    assign frame_type = (frame_source == SOURCE_ACK) ? ack_frame_type :
+                        (frame_source == SOURCE_RESPONSE) ? response_frame_type :
+                        trace_frame_type;
+    assign frame_seq = (frame_source == SOURCE_ACK) ? ack_seq :
+                       (frame_source == SOURCE_RESPONSE) ? response_seq :
+                       trace_seq;
+    assign frame_timestamp_tick = (frame_source == SOURCE_ACK) ? ack_timestamp_tick :
+                                  (frame_source == SOURCE_RESPONSE) ? response_timestamp_tick :
+                                  trace_timestamp_tick;
+    assign frame_payload_len = (frame_source == SOURCE_ACK) ? ack_payload_len :
+                               (frame_source == SOURCE_RESPONSE) ? response_payload_len :
+                               trace_payload_len;
+    assign frame_payload = (frame_source == SOURCE_ACK) ? ack_payload :
+                           (frame_source == SOURCE_RESPONSE) ? response_payload :
+                           trace_payload;
+
+    function [31:0] saturating_increment32;
+        input [31:0] value;
+        begin
+            if (value == 32'hffffffff) begin
+                saturating_increment32 = value;
+            end else begin
+                saturating_increment32 = value + 32'd1;
+            end
+        end
+    endfunction
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            active_valid <= 1'b0;
+            frame_source <= SOURCE_ACK;
+            trace_oversize_consumed <= 1'b0;
+            trace_drop_count <= 32'd0;
+        end else begin
+            if (trace_valid && trace_ready && trace_oversize && !trace_oversize_consumed) begin
+                trace_oversize_consumed <= 1'b1;
+                trace_drop_count <= saturating_increment32(trace_drop_count);
+            end else if (!trace_valid) begin
+                trace_oversize_consumed <= 1'b0;
+            end
+
+            if (active_valid) begin
+                if (frame_ready) begin
+                    active_valid <= 1'b0;
+                end
+            end else if (ack_valid && (ack_payload_len <= MAX_PAYLOAD_BYTES)) begin
+                active_valid <= 1'b1;
+                frame_source <= SOURCE_ACK;
+            end else if (response_valid && (response_payload_len <= MAX_PAYLOAD_BYTES)) begin
+                active_valid <= 1'b1;
+                frame_source <= SOURCE_RESPONSE;
+            end else if (trace_valid && !trace_oversize) begin
+                active_valid <= 1'b1;
+                frame_source <= SOURCE_TRACE;
+            end
+        end
+    end
+endmodule

+ 289 - 0
src/top/prod2u_fan_tach_binary921_v2_normal_top.v

@@ -0,0 +1,289 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_tach_binary921_v2_normal_top #(
+    parameter integer HOST_UART_CLKS_PER_BIT = 27,
+    parameter integer POR_CYCLES = 1024,
+    parameter integer STARTUP_DELAY_TICKS = 250000,
+    parameter integer HOST_TIMEOUT_TICKS = 125000000,
+    parameter integer PTC_PWM_PERIOD_TICKS = 2500000,
+    parameter integer FAN_PWM_PERIOD_TICKS = 1000,
+    parameter integer TACH_WINDOW_TICKS = 25000000,
+    parameter integer TRACE_PERIOD_TICKS = 2500000,
+    parameter integer READY_REPEAT_COUNT = 3,
+    parameter [31:0] BUILD_ID = 32'h00000000
+) (
+    input  wire        sys_clk,
+    input  wire        bmc_uart_rx,
+    output wire        bmc_uart_tx,
+    input  wire        host_uart_rx,
+    output wire        host_uart_tx,
+    output wire [23:0] ptc_pwm_out,
+    output wire [3:0]  fan_pwm_out,
+    input  wire [7:0]  fan_fg_in,
+    input  wire [3:0]  fan_install_in,
+    output wire [7:0]  led
+);
+    localparam integer TX_MAX_PAYLOAD_BYTES = 28;
+
+    wire sys_rst_n;
+    wire host_rx_valid;
+    wire [7:0] host_rx_data;
+    wire host_rx_ready;
+    wire host_rx_framing_error;
+    wire host_rx_break;
+    wire host_rx_overflow;
+    wire command_valid;
+    wire command_ready;
+    wire [31:0] command_seq;
+    wire [7:0] command_id;
+    wire [7:0] command_channel;
+    wire [7:0] command_value;
+    wire [7:0] command_flags;
+    wire [1:0] command_result;
+    wire [15:0] parser_crc_error_count;
+    wire [15:0] parser_timeout_count;
+    wire [15:0] parser_format_error_count;
+    wire [31:0] parser_error_count;
+
+    wire ack_valid;
+    wire ack_ready;
+    wire [7:0] ack_frame_type;
+    wire [31:0] ack_seq;
+    wire [31:0] ack_timestamp_tick;
+    wire [7:0] ack_payload_len;
+    wire [63:0] core_ack_payload;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] ack_payload;
+    wire response_valid;
+    wire response_ready;
+    wire [7:0] response_frame_type;
+    wire [31:0] response_seq;
+    wire [31:0] response_timestamp_tick;
+    wire [7:0] response_payload_len;
+    wire [223:0] core_response_payload;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] response_payload;
+    wire trace_valid;
+    wire trace_ready;
+    wire [7:0] trace_frame_type;
+    wire [31:0] trace_seq;
+    wire [31:0] trace_timestamp_tick;
+    wire [7:0] trace_payload_len;
+    wire [511:0] core_trace_payload;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] trace_payload;
+
+    wire scheduled_frame_valid;
+    wire scheduled_frame_ready;
+    wire [1:0] scheduled_frame_source;
+    wire [7:0] scheduled_frame_type;
+    wire [31:0] scheduled_frame_seq;
+    wire [31:0] scheduled_frame_timestamp_tick;
+    wire [7:0] scheduled_frame_payload_len;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] scheduled_frame_payload;
+    wire [31:0] scheduler_trace_drop_count;
+
+    wire frame_tx_busy;
+    wire frame_tx_done;
+    wire frame_tx_valid;
+    wire [7:0] frame_tx_data;
+    wire host_phy_tx_ready;
+    wire host_phy_tx_busy;
+    wire [167:0] ptc_active_percent;
+    wire [27:0] fan_active_percent;
+    wire timeout_active;
+    wire [31:0] tach_snapshot_seq;
+
+    generate
+        if (BUILD_ID == 32'h00000000) begin : g_build_identity_required
+            prod2u_build_id_must_be_nonzero u_build_identity_error();
+        end
+    endgenerate
+
+    assign bmc_uart_tx = 1'b1;
+    assign parser_error_count = {16'd0, parser_crc_error_count} +
+                                {16'd0, parser_timeout_count} +
+                                {16'd0, parser_format_error_count} +
+                                {31'd0, host_rx_framing_error} +
+                                {31'd0, host_rx_break} +
+                                {31'd0, host_rx_overflow};
+    assign scheduled_frame_ready = frame_tx_done;
+    assign ack_payload = {160'd0, core_ack_payload};
+    assign response_payload = core_response_payload;
+    assign trace_payload = core_trace_payload[(TX_MAX_PAYLOAD_BYTES*8)-1:0];
+    assign led[0] = sys_rst_n;
+    assign led[1] = timeout_active;
+    assign led[2] = host_phy_tx_busy;
+    assign led[3] = |parser_error_count;
+    assign led[4] = |scheduler_trace_drop_count;
+    assign led[5] = 1'b0;
+    assign led[6] = fan_fg_in[4];
+    assign led[7] = fan_fg_in[5];
+
+    prod2u_por #(
+        .POR_CYCLES(POR_CYCLES)
+    ) u_por (
+        .sys_clk(sys_clk),
+        .sys_rst_n(sys_rst_n)
+    );
+
+    uart_rx_8n1 #(
+        .CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)
+    ) u_host_uart_rx (
+        .clk(sys_clk),
+        .rst_n(sys_rst_n),
+        .rx_i(host_uart_rx),
+        .rx_valid(host_rx_valid),
+        .rx_data(host_rx_data),
+        .rx_ready(host_rx_ready),
+        .framing_error(host_rx_framing_error),
+        .break_detected(host_rx_break),
+        .overflow(host_rx_overflow)
+    );
+
+    prod2u_p4_host_rx u_host_protocol_rx (
+        .clk(sys_clk),
+        .rst_n(sys_rst_n),
+        .rx_valid(host_rx_valid),
+        .rx_ready(host_rx_ready),
+        .rx_data(host_rx_data),
+        .command_valid(command_valid),
+        .command_ready(command_ready),
+        .command_seq(command_seq),
+        .command_id(command_id),
+        .command_channel(command_channel),
+        .command_value(command_value),
+        .command_flags(command_flags),
+        .command_result(command_result),
+        .crc_error_count(parser_crc_error_count),
+        .timeout_count(parser_timeout_count),
+        .format_error_count(parser_format_error_count)
+    );
+
+    prod2u_fan_tach_binary921_v2_core #(
+        .PROFILE_ID(8'd4),
+        .TRACE_MODE(0),
+        .VARIANT_ID(8'd0),
+        .BUILD_ID(BUILD_ID),
+        .STARTUP_DELAY_TICKS(STARTUP_DELAY_TICKS),
+        .HOST_TIMEOUT_TICKS(HOST_TIMEOUT_TICKS),
+        .PTC_PWM_PERIOD_TICKS(PTC_PWM_PERIOD_TICKS),
+        .FAN_PWM_PERIOD_TICKS(FAN_PWM_PERIOD_TICKS),
+        .TACH_WINDOW_TICKS(TACH_WINDOW_TICKS),
+        .TRACE_PERIOD_TICKS(TRACE_PERIOD_TICKS),
+        .READY_REPEAT_COUNT(READY_REPEAT_COUNT)
+    ) u_core (
+        .clk(sys_clk),
+        .rst_n(sys_rst_n),
+        .command_valid(command_valid),
+        .command_ready(command_ready),
+        .command_seq(command_seq),
+        .command_id(command_id),
+        .command_channel(command_channel),
+        .command_value(command_value),
+        .command_flags(command_flags),
+        .command_result(command_result),
+        .ack_valid(ack_valid),
+        .ack_ready(ack_ready),
+        .ack_frame_type(ack_frame_type),
+        .ack_seq(ack_seq),
+        .ack_timestamp_tick(ack_timestamp_tick),
+        .ack_payload_len(ack_payload_len),
+        .ack_payload(core_ack_payload),
+        .response_valid(response_valid),
+        .response_ready(response_ready),
+        .response_frame_type(response_frame_type),
+        .response_seq(response_seq),
+        .response_timestamp_tick(response_timestamp_tick),
+        .response_payload_len(response_payload_len),
+        .response_payload(core_response_payload),
+        .trace_valid(trace_valid),
+        .trace_ready(trace_ready),
+        .trace_frame_type(trace_frame_type),
+        .trace_seq(trace_seq),
+        .trace_timestamp_tick(trace_timestamp_tick),
+        .trace_payload_len(trace_payload_len),
+        .trace_payload(core_trace_payload),
+        .ptc_pwm_out(ptc_pwm_out),
+        .fan_pwm_out(fan_pwm_out),
+        .fan_fg_in(fan_fg_in),
+        .fan_install_in(fan_install_in),
+        .parser_error_count(parser_error_count),
+        .scheduler_trace_drop_count(scheduler_trace_drop_count),
+        .ptc_active_percent(ptc_active_percent),
+        .fan_active_percent(fan_active_percent),
+        .timeout_active(timeout_active),
+        .tach_snapshot_seq(tach_snapshot_seq)
+    );
+
+    prod2u_p4_tx_scheduler #(
+        .MAX_PAYLOAD_BYTES(TX_MAX_PAYLOAD_BYTES)
+    ) u_tx_scheduler (
+        .clk(sys_clk),
+        .rst_n(sys_rst_n),
+        .ack_valid(ack_valid),
+        .ack_ready(ack_ready),
+        .ack_frame_type(ack_frame_type),
+        .ack_seq(ack_seq),
+        .ack_timestamp_tick(ack_timestamp_tick),
+        .ack_payload_len(ack_payload_len),
+        .ack_payload(ack_payload),
+        .response_valid(response_valid),
+        .response_ready(response_ready),
+        .response_frame_type(response_frame_type),
+        .response_seq(response_seq),
+        .response_timestamp_tick(response_timestamp_tick),
+        .response_payload_len(response_payload_len),
+        .response_payload(response_payload),
+        .trace_valid(trace_valid),
+        .trace_ready(trace_ready),
+        .trace_frame_type(trace_frame_type),
+        .trace_seq(trace_seq),
+        .trace_timestamp_tick(trace_timestamp_tick),
+        .trace_payload_len(trace_payload_len),
+        .trace_payload(trace_payload),
+        .frame_valid(scheduled_frame_valid),
+        .frame_ready(scheduled_frame_ready),
+        .frame_source(scheduled_frame_source),
+        .frame_type(scheduled_frame_type),
+        .frame_seq(scheduled_frame_seq),
+        .frame_timestamp_tick(scheduled_frame_timestamp_tick),
+        .frame_payload_len(scheduled_frame_payload_len),
+        .frame_payload(scheduled_frame_payload),
+        .trace_drop_count(scheduler_trace_drop_count)
+    );
+
+    binary921_frame_tx #(
+        .MAX_PAYLOAD_BYTES(TX_MAX_PAYLOAD_BYTES),
+        .LATCH_PAYLOAD(0),
+        .VERSION(8'h02)
+    ) u_frame_tx (
+        .clk(sys_clk),
+        .rst_n(sys_rst_n),
+        .start(scheduled_frame_valid && !frame_tx_busy && !frame_tx_done),
+        .profile_id(8'd4),
+        .frame_type(scheduled_frame_type),
+        .frame_seq(scheduled_frame_seq),
+        .timestamp_tick(scheduled_frame_timestamp_tick),
+        .payload_len(scheduled_frame_payload_len),
+        .payload(scheduled_frame_payload),
+        .busy(frame_tx_busy),
+        .done(frame_tx_done),
+        .tx_valid(frame_tx_valid),
+        .tx_data(frame_tx_data),
+        .tx_ready(host_phy_tx_ready)
+    );
+
+    uart_tx_8n1 #(
+        .CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)
+    ) u_host_uart_tx (
+        .clk(sys_clk),
+        .rst_n(sys_rst_n),
+        .tx_valid(frame_tx_valid),
+        .tx_data(frame_tx_data),
+        .tx_ready(host_phy_tx_ready),
+        .tx_o(host_uart_tx),
+        .busy(host_phy_tx_busy)
+    );
+
+    wire unused_bmc_rx = bmc_uart_rx;
+    wire unused_frame_source = ^scheduled_frame_source;
+    wire unused_state = ^ptc_active_percent ^ ^fan_active_percent ^ ^tach_snapshot_seq;
+endmodule

+ 211 - 0
src/top/prod2u_fan_tach_binary921_v2_trace_top.v

@@ -0,0 +1,211 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_tach_binary921_v2_trace_top #(
+    parameter integer HOST_UART_CLKS_PER_BIT = 27,
+    parameter integer POR_CYCLES = 1024,
+    parameter integer STARTUP_DELAY_TICKS = 250000,
+    parameter integer HOST_TIMEOUT_TICKS = 125000000,
+    parameter integer PTC_PWM_PERIOD_TICKS = 2500000,
+    parameter integer FAN_PWM_PERIOD_TICKS = 1000,
+    parameter integer TACH_WINDOW_TICKS = 25000000,
+    parameter integer TRACE_PERIOD_TICKS = 2500000,
+    parameter integer READY_REPEAT_COUNT = 3,
+    parameter [31:0] BUILD_ID = 32'h00000000
+) (
+    input  wire        sys_clk,
+    input  wire        bmc_uart_rx,
+    output wire        bmc_uart_tx,
+    input  wire        host_uart_rx,
+    output wire        host_uart_tx,
+    output wire [23:0] ptc_pwm_out,
+    output wire [3:0]  fan_pwm_out,
+    input  wire [7:0]  fan_fg_in,
+    input  wire [3:0]  fan_install_in,
+    output wire [7:0]  led
+);
+    localparam integer TX_MAX_PAYLOAD_BYTES = 64;
+
+    wire sys_rst_n;
+    wire host_rx_valid;
+    wire [7:0] host_rx_data;
+    wire host_rx_ready;
+    wire host_rx_framing_error;
+    wire host_rx_break;
+    wire host_rx_overflow;
+    wire command_valid;
+    wire command_ready;
+    wire [31:0] command_seq;
+    wire [7:0] command_id;
+    wire [7:0] command_channel;
+    wire [7:0] command_value;
+    wire [7:0] command_flags;
+    wire [1:0] command_result;
+    wire [15:0] parser_crc_error_count;
+    wire [15:0] parser_timeout_count;
+    wire [15:0] parser_format_error_count;
+    wire [31:0] parser_error_count;
+    wire ack_valid;
+    wire ack_ready;
+    wire [7:0] ack_frame_type;
+    wire [31:0] ack_seq;
+    wire [31:0] ack_timestamp_tick;
+    wire [7:0] ack_payload_len;
+    wire [63:0] core_ack_payload;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] ack_payload;
+    wire response_valid;
+    wire response_ready;
+    wire [7:0] response_frame_type;
+    wire [31:0] response_seq;
+    wire [31:0] response_timestamp_tick;
+    wire [7:0] response_payload_len;
+    wire [223:0] core_response_payload;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] response_payload;
+    wire trace_valid;
+    wire trace_ready;
+    wire [7:0] trace_frame_type;
+    wire [31:0] trace_seq;
+    wire [31:0] trace_timestamp_tick;
+    wire [7:0] trace_payload_len;
+    wire [511:0] core_trace_payload;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] trace_payload;
+    wire scheduled_frame_valid;
+    wire scheduled_frame_ready;
+    wire [1:0] scheduled_frame_source;
+    wire [7:0] scheduled_frame_type;
+    wire [31:0] scheduled_frame_seq;
+    wire [31:0] scheduled_frame_timestamp_tick;
+    wire [7:0] scheduled_frame_payload_len;
+    wire [(TX_MAX_PAYLOAD_BYTES*8)-1:0] scheduled_frame_payload;
+    wire [31:0] scheduler_trace_drop_count;
+    wire frame_tx_busy;
+    wire frame_tx_done;
+    wire frame_tx_valid;
+    wire [7:0] frame_tx_data;
+    wire host_phy_tx_ready;
+    wire host_phy_tx_busy;
+    wire [167:0] ptc_active_percent;
+    wire [27:0] fan_active_percent;
+    wire timeout_active;
+    wire [31:0] tach_snapshot_seq;
+
+    generate
+        if (BUILD_ID == 32'h00000000) begin : g_build_identity_required
+            prod2u_build_id_must_be_nonzero u_build_identity_error();
+        end
+    endgenerate
+
+    assign bmc_uart_tx = 1'b1;
+    assign parser_error_count = {16'd0, parser_crc_error_count} +
+                                {16'd0, parser_timeout_count} +
+                                {16'd0, parser_format_error_count} +
+                                {31'd0, host_rx_framing_error} +
+                                {31'd0, host_rx_break} +
+                                {31'd0, host_rx_overflow};
+    assign scheduled_frame_ready = frame_tx_done;
+    assign ack_payload = {448'd0, core_ack_payload};
+    assign response_payload = {288'd0, core_response_payload};
+    assign trace_payload = core_trace_payload;
+    assign led[0] = sys_rst_n;
+    assign led[1] = timeout_active;
+    assign led[2] = host_phy_tx_busy;
+    assign led[3] = |parser_error_count;
+    assign led[4] = |scheduler_trace_drop_count;
+    assign led[5] = 1'b1;
+    assign led[6] = fan_fg_in[4];
+    assign led[7] = fan_fg_in[5];
+
+    prod2u_por #(.POR_CYCLES(POR_CYCLES)) u_por (
+        .sys_clk(sys_clk), .sys_rst_n(sys_rst_n)
+    );
+
+    uart_rx_8n1 #(.CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)) u_host_uart_rx (
+        .clk(sys_clk), .rst_n(sys_rst_n), .rx_i(host_uart_rx),
+        .rx_valid(host_rx_valid), .rx_data(host_rx_data), .rx_ready(host_rx_ready),
+        .framing_error(host_rx_framing_error), .break_detected(host_rx_break), .overflow(host_rx_overflow)
+    );
+
+    prod2u_p4_host_rx u_host_protocol_rx (
+        .clk(sys_clk), .rst_n(sys_rst_n), .rx_valid(host_rx_valid), .rx_ready(host_rx_ready),
+        .rx_data(host_rx_data), .command_valid(command_valid), .command_ready(command_ready),
+        .command_seq(command_seq), .command_id(command_id), .command_channel(command_channel),
+        .command_value(command_value), .command_flags(command_flags), .command_result(command_result),
+        .crc_error_count(parser_crc_error_count), .timeout_count(parser_timeout_count),
+        .format_error_count(parser_format_error_count)
+    );
+
+    prod2u_fan_tach_binary921_v2_core #(
+        .PROFILE_ID(8'd4),
+        .TRACE_MODE(1),
+        .VARIANT_ID(8'd1),
+        .BUILD_ID(BUILD_ID),
+        .STARTUP_DELAY_TICKS(STARTUP_DELAY_TICKS),
+        .HOST_TIMEOUT_TICKS(HOST_TIMEOUT_TICKS),
+        .PTC_PWM_PERIOD_TICKS(PTC_PWM_PERIOD_TICKS),
+        .FAN_PWM_PERIOD_TICKS(FAN_PWM_PERIOD_TICKS),
+        .TACH_WINDOW_TICKS(TACH_WINDOW_TICKS),
+        .TRACE_PERIOD_TICKS(TRACE_PERIOD_TICKS),
+        .READY_REPEAT_COUNT(READY_REPEAT_COUNT)
+    ) u_core (
+        .clk(sys_clk), .rst_n(sys_rst_n),
+        .command_valid(command_valid), .command_ready(command_ready), .command_seq(command_seq),
+        .command_id(command_id), .command_channel(command_channel), .command_value(command_value),
+        .command_flags(command_flags), .command_result(command_result),
+        .ack_valid(ack_valid), .ack_ready(ack_ready), .ack_frame_type(ack_frame_type),
+        .ack_seq(ack_seq), .ack_timestamp_tick(ack_timestamp_tick), .ack_payload_len(ack_payload_len),
+        .ack_payload(core_ack_payload), .response_valid(response_valid), .response_ready(response_ready),
+        .response_frame_type(response_frame_type), .response_seq(response_seq),
+        .response_timestamp_tick(response_timestamp_tick), .response_payload_len(response_payload_len),
+        .response_payload(core_response_payload), .trace_valid(trace_valid), .trace_ready(trace_ready),
+        .trace_frame_type(trace_frame_type), .trace_seq(trace_seq),
+        .trace_timestamp_tick(trace_timestamp_tick), .trace_payload_len(trace_payload_len),
+        .trace_payload(core_trace_payload), .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out),
+        .fan_fg_in(fan_fg_in), .fan_install_in(fan_install_in),
+        .parser_error_count(parser_error_count),
+        .scheduler_trace_drop_count(scheduler_trace_drop_count),
+        .ptc_active_percent(ptc_active_percent), .fan_active_percent(fan_active_percent),
+        .timeout_active(timeout_active), .tach_snapshot_seq(tach_snapshot_seq)
+    );
+
+    prod2u_p4_tx_scheduler #(
+        .MAX_PAYLOAD_BYTES(TX_MAX_PAYLOAD_BYTES)
+    ) u_tx_scheduler (
+        .clk(sys_clk), .rst_n(sys_rst_n),
+        .ack_valid(ack_valid), .ack_ready(ack_ready), .ack_frame_type(ack_frame_type),
+        .ack_seq(ack_seq), .ack_timestamp_tick(ack_timestamp_tick),
+        .ack_payload_len(ack_payload_len), .ack_payload(ack_payload),
+        .response_valid(response_valid), .response_ready(response_ready),
+        .response_frame_type(response_frame_type), .response_seq(response_seq),
+        .response_timestamp_tick(response_timestamp_tick),
+        .response_payload_len(response_payload_len), .response_payload(response_payload),
+        .trace_valid(trace_valid), .trace_ready(trace_ready), .trace_frame_type(trace_frame_type),
+        .trace_seq(trace_seq), .trace_timestamp_tick(trace_timestamp_tick),
+        .trace_payload_len(trace_payload_len), .trace_payload(trace_payload),
+        .frame_valid(scheduled_frame_valid), .frame_ready(scheduled_frame_ready),
+        .frame_source(scheduled_frame_source), .frame_type(scheduled_frame_type),
+        .frame_seq(scheduled_frame_seq), .frame_timestamp_tick(scheduled_frame_timestamp_tick),
+        .frame_payload_len(scheduled_frame_payload_len), .frame_payload(scheduled_frame_payload),
+        .trace_drop_count(scheduler_trace_drop_count)
+    );
+
+    binary921_frame_tx #(
+        .MAX_PAYLOAD_BYTES(TX_MAX_PAYLOAD_BYTES),
+        .LATCH_PAYLOAD(0),
+        .VERSION(8'h02)
+    ) u_frame_tx (
+        .clk(sys_clk), .rst_n(sys_rst_n),
+        .start(scheduled_frame_valid && !frame_tx_busy && !frame_tx_done), .profile_id(8'd4),
+        .frame_type(scheduled_frame_type), .frame_seq(scheduled_frame_seq),
+        .timestamp_tick(scheduled_frame_timestamp_tick), .payload_len(scheduled_frame_payload_len),
+        .payload(scheduled_frame_payload), .busy(frame_tx_busy), .done(frame_tx_done),
+        .tx_valid(frame_tx_valid), .tx_data(frame_tx_data), .tx_ready(host_phy_tx_ready)
+    );
+
+    uart_tx_8n1 #(.CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)) u_host_uart_tx (
+        .clk(sys_clk), .rst_n(sys_rst_n), .tx_valid(frame_tx_valid), .tx_data(frame_tx_data),
+        .tx_ready(host_phy_tx_ready), .tx_o(host_uart_tx), .busy(host_phy_tx_busy)
+    );
+
+    wire unused_bmc_rx = bmc_uart_rx;
+    wire unused_frame_source = ^scheduled_frame_source;
+    wire unused_state = ^ptc_active_percent ^ ^fan_active_percent ^ ^tach_snapshot_seq;
+endmodule

+ 16 - 0
td/phy/prod2u_fan_tach_binary921_v2_normal.tcl

@@ -0,0 +1,16 @@
+import_device ef2_4.db -package EF2L45BG256B
+import_db ../syn/prod2u_fan_tach_binary921_v2_normal_gate.db
+read_adc {constraints/prod2u_fan_tach_binary921_v2.adc}
+read_sdc {constraints/pid_study_01.sdc}
+set_param route effort routability
+place
+update_timing -mode manhattan
+report_area -io_info -file prod2u_fan_tach_binary921_v2_normal_phy.area
+report_timing_summary -file prod2u_fan_tach_binary921_v2_normal_place.timing
+export_db prod2u_fan_tach_binary921_v2_normal_place.db
+route
+update_timing
+report_area -io_info -file prod2u_fan_tach_binary921_v2_normal_phy.area
+report_timing_summary -file prod2u_fan_tach_binary921_v2_normal_pr.timing
+export_db prod2u_fan_tach_binary921_v2_normal_pr.db
+bitgen -bit prod2u_fan_tach_binary921_v2_normal.bit

+ 16 - 0
td/phy/prod2u_fan_tach_binary921_v2_trace.tcl

@@ -0,0 +1,16 @@
+import_device ef2_4.db -package EF2L45BG256B
+import_db ../syn/prod2u_fan_tach_binary921_v2_trace_gate.db
+read_adc {constraints/prod2u_fan_tach_binary921_v2.adc}
+read_sdc {constraints/pid_study_01.sdc}
+set_param route effort routability
+place
+update_timing -mode manhattan
+report_area -io_info -file prod2u_fan_tach_binary921_v2_trace_phy.area
+report_timing_summary -file prod2u_fan_tach_binary921_v2_trace_place.timing
+export_db prod2u_fan_tach_binary921_v2_trace_place.db
+route
+update_timing
+report_area -io_info -file prod2u_fan_tach_binary921_v2_trace_phy.area
+report_timing_summary -file prod2u_fan_tach_binary921_v2_trace_pr.timing
+export_db prod2u_fan_tach_binary921_v2_trace_pr.db
+bitgen -bit prod2u_fan_tach_binary921_v2_trace.bit

+ 25 - 0
td/prod2u_fan_tach_binary921_v2_normal.prj

@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Project Version="3" Minor="2" RunTime="2026-07-12T00:00:00">
+    <Project_Created_Time></Project_Created_Time>
+    <TD_Version>6.2.2.198412</TD_Version>
+    <Name>prod2u_fan_tach_binary921_v2_normal</Name>
+    <HardWare><Family>EF2</Family><Device>EF2L45BG256B</Device><Speed></Speed></HardWare>
+    <Source_Files>
+        <Verilog>
+            <File Path="../src/rtl/uart_rx_8n1.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="1"/></FileInfo></File>
+            <File Path="../src/rtl/uart_tx_8n1.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="2"/></FileInfo></File>
+            <File Path="../src/rtl/binary921_crc16.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="3"/></FileInfo></File>
+            <File Path="../src/rtl/binary921_frame_tx.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="4"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_por.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="5"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_p4_host_rx.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="6"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_p4_tx_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="7"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_fan_tach_capture8.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="8"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_fan_pwm_bank.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/rtl/prod2u_fan_tach_binary921_v2_core.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/top/prod2u_fan_tach_binary921_v2_normal_top.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>
+        </Verilog>
+        <ADC_FILE><File Path="../constraints/prod2u_fan_tach_binary921_v2.adc"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="constraint_1"/><Attr Name="CompileOrder" Val="1"/></FileInfo></File></ADC_FILE>
+        <SDC_FILE><File Path="../constraints/pid_study_01.sdc"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="constraint_1"/><Attr Name="CompileOrder" Val="2"/></FileInfo></File></SDC_FILE>
+    </Source_Files>
+    <TOP_MODULE><LABEL></LABEL><MODULE>prod2u_fan_tach_binary921_v2_normal_top</MODULE><CREATEINDEX>user</CREATEINDEX></TOP_MODULE>
+</Project>

+ 25 - 0
td/prod2u_fan_tach_binary921_v2_trace.prj

@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Project Version="3" Minor="2" RunTime="2026-07-12T00:00:00">
+    <Project_Created_Time></Project_Created_Time>
+    <TD_Version>6.2.2.198412</TD_Version>
+    <Name>prod2u_fan_tach_binary921_v2_trace</Name>
+    <HardWare><Family>EF2</Family><Device>EF2L45BG256B</Device><Speed></Speed></HardWare>
+    <Source_Files>
+        <Verilog>
+            <File Path="../src/rtl/uart_rx_8n1.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="1"/></FileInfo></File>
+            <File Path="../src/rtl/uart_tx_8n1.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="2"/></FileInfo></File>
+            <File Path="../src/rtl/binary921_crc16.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="3"/></FileInfo></File>
+            <File Path="../src/rtl/binary921_frame_tx.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="4"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_por.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="5"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_p4_host_rx.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="6"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_p4_tx_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="7"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_fan_tach_capture8.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="8"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_fan_pwm_bank.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/rtl/prod2u_fan_tach_binary921_v2_core.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/top/prod2u_fan_tach_binary921_v2_trace_top.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>
+        </Verilog>
+        <ADC_FILE><File Path="../constraints/prod2u_fan_tach_binary921_v2.adc"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="constraint_1"/><Attr Name="CompileOrder" Val="1"/></FileInfo></File></ADC_FILE>
+        <SDC_FILE><File Path="../constraints/pid_study_01.sdc"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="constraint_1"/><Attr Name="CompileOrder" Val="2"/></FileInfo></File></SDC_FILE>
+    </Source_Files>
+    <TOP_MODULE><LABEL></LABEL><MODULE>prod2u_fan_tach_binary921_v2_trace_top</MODULE><CREATEINDEX>user</CREATEINDEX></TOP_MODULE>
+</Project>

+ 23 - 0
td/syn/prod2u_fan_tach_binary921_v2_normal.tcl

@@ -0,0 +1,23 @@
+import_device ef2_4.db -package EF2L45BG256B
+analyze -file {src/rtl/uart_rx_8n1.v}
+analyze -file {src/rtl/uart_tx_8n1.v}
+analyze -file {src/rtl/binary921_crc16.v}
+analyze -file {src/rtl/binary921_frame_tx.v}
+analyze -file {src/rtl/prod2u_por.v}
+analyze -file {src/rtl/prod2u_p4_host_rx.v}
+analyze -file {src/rtl/prod2u_p4_tx_scheduler.v}
+analyze -file {src/rtl/prod2u_fan_tach_capture8.v}
+analyze -file {src/rtl/prod2u_fan_pwm_bank.v}
+analyze -file {src/rtl/prod2u_fan_tach_binary921_v2_core.v}
+analyze -file {src/top/prod2u_fan_tach_binary921_v2_normal_top.v}
+elaborate -top {prod2u_fan_tach_binary921_v2_normal_top}
+read_adc {constraints/prod2u_fan_tach_binary921_v2.adc}
+read_sdc {constraints/pid_study_01.sdc}
+optimize_rtl
+report_area -file prod2u_fan_tach_binary921_v2_normal_rtl.area
+export_db prod2u_fan_tach_binary921_v2_normal_rtl.db
+optimize_gate prod2u_fan_tach_binary921_v2_normal_gate.area
+legalize_phy_inst
+update_timing
+report_timing_summary -file prod2u_fan_tach_binary921_v2_normal_gate.timing
+export_db prod2u_fan_tach_binary921_v2_normal_gate.db

+ 23 - 0
td/syn/prod2u_fan_tach_binary921_v2_trace.tcl

@@ -0,0 +1,23 @@
+import_device ef2_4.db -package EF2L45BG256B
+analyze -file {src/rtl/uart_rx_8n1.v}
+analyze -file {src/rtl/uart_tx_8n1.v}
+analyze -file {src/rtl/binary921_crc16.v}
+analyze -file {src/rtl/binary921_frame_tx.v}
+analyze -file {src/rtl/prod2u_por.v}
+analyze -file {src/rtl/prod2u_p4_host_rx.v}
+analyze -file {src/rtl/prod2u_p4_tx_scheduler.v}
+analyze -file {src/rtl/prod2u_fan_tach_capture8.v}
+analyze -file {src/rtl/prod2u_fan_pwm_bank.v}
+analyze -file {src/rtl/prod2u_fan_tach_binary921_v2_core.v}
+analyze -file {src/top/prod2u_fan_tach_binary921_v2_trace_top.v}
+elaborate -top {prod2u_fan_tach_binary921_v2_trace_top}
+read_adc {constraints/prod2u_fan_tach_binary921_v2.adc}
+read_sdc {constraints/pid_study_01.sdc}
+optimize_rtl
+report_area -file prod2u_fan_tach_binary921_v2_trace_rtl.area
+export_db prod2u_fan_tach_binary921_v2_trace_rtl.db
+optimize_gate prod2u_fan_tach_binary921_v2_trace_gate.area
+legalize_phy_inst
+update_timing
+report_timing_summary -file prod2u_fan_tach_binary921_v2_trace_gate.timing
+export_db prod2u_fan_tach_binary921_v2_trace_gate.db

+ 15 - 0
tests/formal/prod2u_fan_data_path.sby

@@ -0,0 +1,15 @@
+[options]
+mode bmc
+depth 112
+
+[engines]
+smtbmc
+
+[script]
+read_verilog -formal prod2u_fan_tach_capture8.v prod2u_fan_pwm_bank.v prod2u_fan_data_path_formal.v
+prep -top prod2u_fan_data_path_formal
+
+[files]
+../../src/rtl/prod2u_fan_tach_capture8.v
+../../src/rtl/prod2u_fan_pwm_bank.v
+prod2u_fan_data_path_formal.v

+ 69 - 0
tests/formal/prod2u_fan_data_path_formal.v

@@ -0,0 +1,69 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_data_path_formal;
+    (* gclk *) reg clk;
+    reg rst_n = 1'b0;
+    reg [7:0] tach_in;
+    reg startup_active;
+    reg [3:0] disable_mask;
+    reg [3:0] fallback;
+    reg [3:0] requested_enable;
+    reg [27:0] requested_percent;
+    wire [127:0] sample_edges;
+    wire [7:0] sample_overflow;
+    wire [31:0] sample_seq;
+    wire [31:0] sample_ticks;
+    wire [3:0] active_enable;
+    wire [27:0] active_percent;
+    wire [3:0] fan_pwm_raw;
+    reg [31:0] last_sample_seq = 32'd0;
+
+    prod2u_fan_tach_capture8 #(
+        .WINDOW_TICKS(4),
+        .WINDOW_COUNTER_WIDTH(2)
+    ) u_tach (
+        .clk(clk), .rst_n(rst_n), .tach_in(tach_in),
+        .sample_edges(sample_edges),
+        .sample_overflow(sample_overflow), .sample_seq(sample_seq), .sample_ticks(sample_ticks)
+    );
+
+    prod2u_fan_pwm_bank #(
+        .PWM_PERIOD_TICKS(100),
+        .PWM_COUNTER_WIDTH(7)
+    ) u_pwm (
+        .clk(clk), .rst_n(rst_n), .startup_active(startup_active),
+        .disable_mask(disable_mask), .fallback(fallback), .requested_enable(requested_enable),
+        .requested_percent(requested_percent), .active_enable(active_enable),
+        .active_percent(active_percent), .fan_pwm_raw(fan_pwm_raw)
+    );
+
+    always @(posedge clk) begin
+        rst_n <= 1'b1;
+        if (!rst_n) begin
+            last_sample_seq <= 32'd0;
+        end else begin
+            assert(sample_seq >= last_sample_seq);
+            if (sample_seq != last_sample_seq) begin
+                assert(sample_seq == last_sample_seq + 32'd1);
+                assert(sample_ticks == 32'd4);
+            end
+            last_sample_seq <= sample_seq;
+            assert(active_percent[6:0] <= 7'd100);
+            assert(active_percent[13:7] <= 7'd100);
+            assert(active_percent[20:14] <= 7'd100);
+            assert(active_percent[27:21] <= 7'd100);
+            if (!active_enable[0]) begin
+                assert(!fan_pwm_raw[0]);
+            end
+            if (active_enable[0] && active_percent[6:0] == 7'd0) begin
+                assert(fan_pwm_raw[0]);
+            end
+            if (active_enable[0] && active_percent[6:0] == 7'd100) begin
+                assert(!fan_pwm_raw[0]);
+            end
+        end
+    end
+
+    wire unused_tach = ^sample_edges ^ ^sample_overflow;
+    wire unused_pwm = ^fan_pwm_raw;
+endmodule

+ 167 - 0
tests/sim/prod2u_fan_pwm_bank_tb.v

@@ -0,0 +1,167 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_pwm_bank_tb;
+    reg clk;
+    reg rst_n;
+    reg startup_active;
+    reg [3:0] disable_mask;
+    reg [3:0] fallback;
+    reg [3:0] requested_enable;
+    reg [4*7-1:0] requested_percent;
+    wire [3:0] active_enable;
+    wire [4*7-1:0] active_percent;
+    wire [3:0] fan_pwm_raw;
+    wire commit_pulse;
+    integer high_ticks;
+    integer connector_high_ticks;
+    integer sample_idx;
+
+    prod2u_fan_pwm_bank #(
+        .PWM_PERIOD_TICKS(100),
+        .PWM_COUNTER_WIDTH(7)
+    ) dut (
+        .clk(clk),
+        .rst_n(rst_n),
+        .startup_active(startup_active),
+        .disable_mask(disable_mask),
+        .fallback(fallback),
+        .requested_enable(requested_enable),
+        .requested_percent(requested_percent),
+        .active_enable(active_enable),
+        .active_percent(active_percent),
+        .fan_pwm_raw(fan_pwm_raw),
+        .commit_pulse(commit_pulse)
+    );
+
+    initial begin
+        clk = 1'b0;
+        forever #5 clk = ~clk;
+    end
+
+    task wait_period_boundary;
+        begin
+            @(negedge clk);
+            while (dut.pwm_tick !== 0) begin
+                @(negedge clk);
+            end
+        end
+    endtask
+
+    task count_raw_high_ticks;
+        output integer result;
+        begin
+            wait_period_boundary();
+            result = 0;
+            for (sample_idx = 0; sample_idx < 100; sample_idx = sample_idx + 1) begin
+                if (fan_pwm_raw[0]) begin
+                    result = result + 1;
+                end
+                @(negedge clk);
+            end
+        end
+    endtask
+
+    task set_and_check_requested_percent;
+        input [6:0] effective_percent;
+        begin
+            requested_percent[6:0] = effective_percent;
+            @(negedge clk);
+            wait_period_boundary();
+            if (!active_enable[0] || active_percent[6:0] !== effective_percent) begin
+                $display("requested duty %0d must commit at the PWM boundary", effective_percent);
+                $fatal;
+            end
+            count_raw_high_ticks(high_ticks);
+            connector_high_ticks = 100 - high_ticks;
+            if (connector_high_ticks !== effective_percent) begin
+                $display(
+                    "%0d percent fan command expected %0d connector-high ticks after NPN inversion, got %0d",
+                    effective_percent,
+                    effective_percent,
+                    connector_high_ticks
+                );
+                $fatal;
+            end
+        end
+    endtask
+
+    initial begin
+        rst_n = 1'b0;
+        startup_active = 1'b1;
+        disable_mask = 4'd0;
+        fallback = 4'd0;
+        requested_enable = 4'd0;
+        requested_percent = 28'd0;
+        repeat (3) @(negedge clk);
+        rst_n = 1'b1;
+
+        wait_period_boundary();
+        if (!commit_pulse) begin
+            $display("fan bank must announce the PWM boundary commit");
+            $fatal;
+        end
+        if (active_enable !== 4'hf || active_percent[6:0] !== 7'd30) begin
+            $display("startup must commit all fan channels at 30 percent");
+            $fatal;
+        end
+        count_raw_high_ticks(high_ticks);
+        if (high_ticks !== 70) begin
+            $display("30 percent fan command must produce 70 percent CPLD high time before NPN inversion, got %0d", high_ticks);
+            $fatal;
+        end
+
+        startup_active = 1'b0;
+        requested_enable = 4'b0001;
+        requested_percent[6:0] = 7'd80;
+        @(negedge clk);
+        if (active_percent[6:0] !== 7'd30) begin
+            $display("requested duty must not tear an active PWM period");
+            $fatal;
+        end
+        wait_period_boundary();
+        if (!active_enable[0] || active_percent[6:0] !== 7'd80) begin
+            $display("requested duty must commit at the next PWM boundary");
+            $fatal;
+        end
+        count_raw_high_ticks(high_ticks);
+        if (high_ticks !== 20) begin
+            $display("80 percent fan command must produce 20 percent CPLD high time before NPN inversion, got %0d", high_ticks);
+            $fatal;
+        end
+
+        requested_percent[6:0] = 7'd100;
+        wait_period_boundary();
+        if (!active_enable[0] || active_percent[6:0] !== 7'd100) begin
+            $display("100 percent requested duty must commit at the PWM boundary");
+            $fatal;
+        end
+        count_raw_high_ticks(high_ticks);
+        if (high_ticks !== 0 || fan_pwm_raw[0]) begin
+            $display("100 percent fan command must keep the NPN off and connector PWM high, got %0d high ticks", high_ticks);
+            $fatal;
+        end
+
+        set_and_check_requested_percent(7'd0);
+        set_and_check_requested_percent(7'd1);
+        set_and_check_requested_percent(7'd50);
+        set_and_check_requested_percent(7'd99);
+        set_and_check_requested_percent(7'd100);
+
+        fallback[0] = 1'b1;
+        wait_period_boundary();
+        if (!active_enable[0] || active_percent[6:0] !== 7'd30) begin
+            $display("fallback must replace the requested command with 30 percent at the boundary");
+            $fatal;
+        end
+
+        disable_mask[0] = 1'b1;
+        wait_period_boundary();
+        if (active_enable[0] || active_percent[6:0] !== 7'd0 || fan_pwm_raw[0]) begin
+            $display("disable must dominate fallback and force the raw PWM output inactive");
+            $fatal;
+        end
+
+        $display("PASS: prod2u_fan_pwm_bank_tb");
+        $finish;
+    end
+endmodule

+ 358 - 0
tests/sim/prod2u_fan_tach_binary921_v2_core_tb.v

@@ -0,0 +1,358 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_tach_binary921_v2_core_tb;
+    localparam [1:0] RESULT_NEW = 2'd0;
+    localparam [7:0] CMD_SET_PTC = 8'h20;
+    localparam [7:0] CMD_SET_FAN = 8'h21;
+    localparam [7:0] CMD_GET_STATUS = 8'h24;
+    localparam [7:0] CMD_DISABLE = 8'h26;
+    localparam [7:0] CMD_GET_FAN_TELEMETRY = 8'h27;
+    localparam [7:0] FT_READY = 8'h01;
+    localparam [7:0] FT_HOST_ACK = 8'h06;
+    localparam [7:0] FT_FAN_TELEMETRY = 8'h0d;
+    localparam [7:0] FT_STATUS_RESPONSE = 8'h0e;
+    localparam [7:0] FT_TRACE_SNAPSHOT = 8'h0f;
+
+    reg clk;
+    reg rst_n;
+    reg command_valid;
+    wire command_ready;
+    reg [31:0] command_seq;
+    reg [7:0] command_id;
+    reg [7:0] command_channel;
+    reg [7:0] command_value;
+    reg [7:0] command_flags;
+    reg [1:0] command_result;
+
+    wire ack_valid;
+    reg ack_ready;
+    wire [7:0] ack_frame_type;
+    wire [31:0] ack_seq;
+    wire [31:0] ack_timestamp_tick;
+    wire [7:0] ack_payload_len;
+    wire [63:0] ack_payload;
+
+    wire response_valid;
+    reg response_ready;
+    wire [7:0] response_frame_type;
+    wire [31:0] response_seq;
+    wire [31:0] response_timestamp_tick;
+    wire [7:0] response_payload_len;
+    wire [223:0] response_payload;
+
+    wire trace_valid;
+    reg trace_ready;
+    wire [7:0] trace_frame_type;
+    wire [31:0] trace_seq;
+    wire [31:0] trace_timestamp_tick;
+    wire [7:0] trace_payload_len;
+    wire [511:0] trace_payload;
+
+    wire [23:0] ptc_pwm_out;
+    wire [3:0] fan_pwm_out;
+    reg [7:0] fan_fg_in;
+    reg [3:0] fan_install_in;
+    reg [31:0] parser_error_count;
+    reg [31:0] scheduler_trace_drop_count;
+    wire [167:0] ptc_active_percent;
+    wire [27:0] fan_active_percent;
+    wire timeout_active;
+    wire [31:0] tach_snapshot_seq;
+
+    integer ack_count;
+    integer response_count;
+    integer trace_count;
+    reg [31:0] last_ack_seq;
+    reg [63:0] last_ack_payload;
+    reg [7:0] last_response_type;
+    reg [31:0] last_response_seq;
+    reg [7:0] last_response_len;
+    reg [511:0] last_response_payload;
+    reg [223:0] retained_telemetry_payload;
+    reg [511:0] held_trace_payload;
+    reg [31:0] held_trace_seq;
+    reg [31:0] held_trace_timestamp;
+    integer response_before_duplicate;
+
+    prod2u_fan_tach_binary921_v2_core #(
+        .PROFILE_ID(8'd4),
+        .TRACE_MODE(1),
+        .VARIANT_ID(8'd1),
+        .BUILD_ID(32'h1234abcd),
+        .STARTUP_DELAY_TICKS(4),
+        .HOST_TIMEOUT_TICKS(200),
+        .PTC_PWM_PERIOD_TICKS(100),
+        .FAN_PWM_PERIOD_TICKS(100),
+        .TACH_WINDOW_TICKS(16),
+        .TRACE_PERIOD_TICKS(12),
+        .TRACE_STABILITY_GUARD_TICKS(2),
+        .READY_REPEAT_COUNT(2)
+    ) dut (
+        .clk(clk),
+        .rst_n(rst_n),
+        .command_valid(command_valid),
+        .command_ready(command_ready),
+        .command_seq(command_seq),
+        .command_id(command_id),
+        .command_channel(command_channel),
+        .command_value(command_value),
+        .command_flags(command_flags),
+        .command_result(command_result),
+        .ack_valid(ack_valid),
+        .ack_ready(ack_ready),
+        .ack_frame_type(ack_frame_type),
+        .ack_seq(ack_seq),
+        .ack_timestamp_tick(ack_timestamp_tick),
+        .ack_payload_len(ack_payload_len),
+        .ack_payload(ack_payload),
+        .response_valid(response_valid),
+        .response_ready(response_ready),
+        .response_frame_type(response_frame_type),
+        .response_seq(response_seq),
+        .response_timestamp_tick(response_timestamp_tick),
+        .response_payload_len(response_payload_len),
+        .response_payload(response_payload),
+        .trace_valid(trace_valid),
+        .trace_ready(trace_ready),
+        .trace_frame_type(trace_frame_type),
+        .trace_seq(trace_seq),
+        .trace_timestamp_tick(trace_timestamp_tick),
+        .trace_payload_len(trace_payload_len),
+        .trace_payload(trace_payload),
+        .ptc_pwm_out(ptc_pwm_out),
+        .fan_pwm_out(fan_pwm_out),
+        .fan_fg_in(fan_fg_in),
+        .fan_install_in(fan_install_in),
+        .parser_error_count(parser_error_count),
+        .scheduler_trace_drop_count(scheduler_trace_drop_count),
+        .ptc_active_percent(ptc_active_percent),
+        .fan_active_percent(fan_active_percent),
+        .timeout_active(timeout_active),
+        .tach_snapshot_seq(tach_snapshot_seq)
+    );
+
+    initial begin
+        clk = 1'b0;
+        forever #5 clk = ~clk;
+    end
+
+    always @(posedge clk) begin
+        if (!rst_n) begin
+            ack_count <= 0;
+            response_count <= 0;
+            trace_count <= 0;
+            last_ack_seq <= 0;
+            last_ack_payload <= 0;
+            last_response_type <= 0;
+            last_response_seq <= 0;
+            last_response_len <= 0;
+            last_response_payload <= 0;
+        end else begin
+            if (ack_valid && ack_ready) begin
+                ack_count <= ack_count + 1;
+                last_ack_seq <= ack_seq;
+                last_ack_payload <= ack_payload[63:0];
+            end
+            if (response_valid && response_ready) begin
+                response_count <= response_count + 1;
+                last_response_type <= response_frame_type;
+                last_response_seq <= response_seq;
+                last_response_len <= response_payload_len;
+                last_response_payload <= response_payload;
+            end
+            if (trace_valid && trace_ready) begin
+                trace_count <= trace_count + 1;
+            end
+        end
+    end
+
+    task issue_command;
+        input [31:0] seq;
+        input [7:0] cmd;
+        input [7:0] channel;
+        input [7:0] value;
+        integer guard;
+        begin
+            @(negedge clk);
+            command_seq = seq;
+            command_id = cmd;
+            command_channel = channel;
+            command_value = value;
+            command_flags = 8'd0;
+            command_valid = 1'b1;
+            guard = 0;
+            while (!command_ready && guard < 100) begin
+                @(negedge clk);
+                guard = guard + 1;
+            end
+            if (!command_ready) begin
+                $display("command was never accepted cmd=%02x", cmd);
+                $fatal;
+            end
+            @(posedge clk);
+            #1;
+            @(negedge clk);
+            command_valid = 1'b0;
+        end
+    endtask
+
+    task wait_for_ack_count;
+        input integer expected;
+        integer guard;
+        begin
+            guard = 0;
+            while (ack_count < expected && guard < 200) begin
+                @(negedge clk);
+                guard = guard + 1;
+            end
+            if (ack_count != expected) begin
+                $display("ACK timeout got=%0d expected=%0d", ack_count, expected);
+                $fatal;
+            end
+        end
+    endtask
+
+    initial begin
+        rst_n = 1'b0;
+        command_valid = 1'b0;
+        command_seq = 0;
+        command_id = 0;
+        command_channel = 0;
+        command_value = 0;
+        command_flags = 0;
+        command_result = RESULT_NEW;
+        ack_ready = 1'b1;
+        response_ready = 1'b1;
+        trace_ready = 1'b1;
+        fan_fg_in = 0;
+        fan_install_in = 4'h4;
+        parser_error_count = 0;
+        scheduler_trace_drop_count = 0;
+        retained_telemetry_payload = 0;
+        held_trace_payload = 0;
+        held_trace_seq = 0;
+        held_trace_timestamp = 0;
+        response_before_duplicate = 0;
+        repeat (4) @(negedge clk);
+        rst_n = 1'b1;
+
+        while (response_count < 1) @(negedge clk);
+        if (last_response_type !== FT_READY || last_response_len !== 8'd12 ||
+            last_response_payload[31:0] !== 32'h1234abcd ||
+            last_response_payload[39:32] !== 8'd1) begin
+            $display("READY payload mismatch");
+            $fatal;
+        end
+
+        // Start immediately after a FAN boundary so the ACK cannot be early.
+        while (dut.u_fan_pwm.pwm_tick !== 1) @(negedge clk);
+        issue_command(32'd1, CMD_SET_FAN, 8'd3, 8'd20);
+        if (ack_count != 0) begin
+            $display("SET_FAN ACK arrived before the PWM boundary");
+            $fatal;
+        end
+        wait_for_ack_count(1);
+        if (ack_frame_type !== FT_HOST_ACK || last_ack_seq !== 32'd1 ||
+            last_ack_payload[7:0] !== 8'd1 || last_ack_payload[15:8] !== CMD_SET_FAN ||
+            fan_active_percent[(2*7) +: 7] !== 7'd20) begin
+            $display("SET_FAN did not commit connector-effective 20 percent");
+            $fatal;
+        end
+
+        while (dut.ptc_phase !== 1) @(negedge clk);
+        issue_command(32'd2, CMD_SET_PTC, 8'd1, 8'd50);
+        if (ack_count != 1) begin
+            $display("SET_PTC ACK arrived before the PWM boundary");
+            $fatal;
+        end
+        wait_for_ack_count(2);
+        if (last_ack_seq !== 32'd2 || ptc_active_percent[6:0] !== 7'd50) begin
+            $display("SET_PTC did not commit 50 percent");
+            $fatal;
+        end
+
+        // Generate FG5 edges and wait for an atomic snapshot.
+        repeat (4) begin
+            fan_fg_in[4] = 1'b1;
+            repeat (2) @(negedge clk);
+            fan_fg_in[4] = 1'b0;
+            repeat (2) @(negedge clk);
+        end
+        while (tach_snapshot_seq < 1) @(negedge clk);
+        issue_command(32'd3, CMD_GET_FAN_TELEMETRY, 8'd0, 8'd0);
+        wait_for_ack_count(3);
+        while (last_response_type != FT_FAN_TELEMETRY || last_response_seq != 32'd3) @(negedge clk);
+        if (last_response_len !== 8'd28 || last_response_payload[(20*8) +: 16] == 16'd0) begin
+            $display("FG5 telemetry missing or non-atomic");
+            $fatal;
+        end
+        retained_telemetry_payload = last_response_payload[223:0];
+        response_before_duplicate = response_count;
+        command_result = 2'd1;
+        issue_command(32'd3, CMD_GET_FAN_TELEMETRY, 8'd0, 8'd0);
+        command_result = RESULT_NEW;
+        wait_for_ack_count(4);
+        while (response_count <= response_before_duplicate) @(negedge clk);
+        if (last_response_type !== FT_FAN_TELEMETRY || last_response_seq !== 32'd3 ||
+            last_response_payload[223:0] !== retained_telemetry_payload ||
+            last_ack_payload[63:56] !== 8'h0a) begin
+            $display("duplicate telemetry did not return retained response and duplicate flags");
+            $fatal;
+        end
+
+        // Let the watchdog expire. PTC returns to zero and FAN returns to 30 percent.
+        while (!timeout_active) @(negedge clk);
+        repeat (110) @(negedge clk);
+        if (ptc_active_percent[6:0] !== 7'd0 || fan_active_percent[(2*7) +: 7] !== 7'd30) begin
+            $display("watchdog fallback mismatch");
+            $fatal;
+        end
+
+        issue_command(32'd4, CMD_GET_STATUS, 8'd0, 8'd0);
+        wait_for_ack_count(5);
+        while (last_response_type != FT_STATUS_RESPONSE || last_response_seq != 32'd4) @(negedge clk);
+        if (!timeout_active) begin
+            $display("query incorrectly cleared latched timeout");
+            $fatal;
+        end
+
+        issue_command(32'd5, CMD_SET_FAN, 8'd3, 8'd80);
+        wait_for_ack_count(6);
+        if (timeout_active || fan_active_percent[(2*7) +: 7] !== 7'd80) begin
+            $display("control command did not clear timeout and apply FAN3=80");
+            $fatal;
+        end
+
+        issue_command(32'd6, CMD_DISABLE, 8'd0, 8'd0);
+        wait_for_ack_count(7);
+        repeat (110) @(negedge clk);
+        if (ptc_active_percent[6:0] !== 7'd0 || fan_active_percent[(2*7) +: 7] !== 7'd30) begin
+            $display("DISABLE fallback mismatch");
+            $fatal;
+        end
+
+        if (trace_count == 0 || trace_frame_type !== FT_TRACE_SNAPSHOT || trace_payload_len > 8'd64) begin
+            $display("Trace variant did not emit bounded snapshots");
+            $fatal;
+        end
+
+        trace_ready = 1'b0;
+        while (!trace_valid) @(negedge clk);
+        held_trace_payload = trace_payload;
+        held_trace_seq = trace_seq;
+        held_trace_timestamp = trace_timestamp_tick;
+        parser_error_count = parser_error_count + 32'd1;
+        fan_install_in = ~fan_install_in;
+        @(negedge clk);
+        if (!trace_valid || trace_payload !== held_trace_payload || trace_seq !== held_trace_seq ||
+            trace_timestamp_tick !== held_trace_timestamp) begin
+            $display("Trace source changed while backpressured");
+            $fatal;
+        end
+        trace_ready = 1'b1;
+        @(negedge clk);
+
+        $display("PASS: prod2u_fan_tach_binary921_v2_core_tb");
+        $finish;
+    end
+endmodule

+ 83 - 0
tests/sim/prod2u_fan_tach_capture8_tb.v

@@ -0,0 +1,83 @@
+`timescale 1ns/1ps
+
+module prod2u_fan_tach_capture8_tb;
+    reg clk;
+    reg rst_n;
+    reg [7:0] tach_in;
+    wire [8*16-1:0] sample_edges;
+    wire [7:0] sample_overflow;
+    wire [31:0] sample_seq;
+    wire [31:0] sample_ticks;
+
+    prod2u_fan_tach_capture8 #(
+        .WINDOW_TICKS(128),
+        .WINDOW_COUNTER_WIDTH(7),
+        .EDGE_COUNTER_WIDTH(4)
+    ) dut (
+        .clk(clk),
+        .rst_n(rst_n),
+        .tach_in(tach_in),
+        .sample_edges(sample_edges),
+        .sample_overflow(sample_overflow),
+        .sample_seq(sample_seq),
+        .sample_ticks(sample_ticks)
+    );
+
+    initial begin
+        clk = 1'b0;
+        forever #5 clk = ~clk;
+    end
+
+    task wait_window_tick;
+        input [6:0] value;
+        begin
+            while (dut.window_tick !== value) begin
+                @(negedge clk);
+            end
+        end
+    endtask
+
+    initial begin
+        rst_n = 1'b0;
+        tach_in = 8'd0;
+        repeat (3) @(negedge clk);
+        rst_n = 1'b1;
+
+        // Three synchronizer stages from pin observation to edge detection put
+        // this rising edge exactly on the window-closing clock.
+        wait_window_tick(7'd125);
+        tach_in[0] = 1'b1;
+        @(negedge clk);
+        tach_in[0] = 1'b0;
+        @(negedge clk);
+        @(negedge clk);
+        if (sample_seq !== 32'd1 || sample_ticks !== 32'd128 ||
+            sample_edges[15:0] !== 16'd1 || sample_overflow[0]) begin
+            $display("tach sample must atomically include the closing-boundary edge");
+            $fatal;
+        end
+
+        repeat (128) @(negedge clk);
+        if (sample_seq !== 32'd2 || sample_edges[15:0] !== 16'd0 ||
+            sample_overflow[0]) begin
+            $display("tach sample must clear only after publishing the completed window");
+            $fatal;
+        end
+
+        // Sixteen real rising edges overflow a four-bit test counter at 15.
+        repeat (16) begin
+            tach_in[1] = 1'b1;
+            repeat (2) @(negedge clk);
+            tach_in[1] = 1'b0;
+            repeat (2) @(negedge clk);
+        end
+        while (sample_seq < 32'd3) @(negedge clk);
+        if (sample_edges[(1*16) +: 16] !== 16'h000f || !sample_overflow[1]) begin
+            $display("tach sample must saturate at 16 bits and report overflow");
+            $fatal;
+        end
+
+        $display("PASS: prod2u_fan_tach_capture8_tb");
+        $finish;
+    end
+endmodule

+ 305 - 0
tests/sim/prod2u_p4_host_rx_tb.v

@@ -0,0 +1,305 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_host_rx_tb;
+    localparam [1:0] RESULT_NEW = 2'd0;
+    localparam [1:0] RESULT_DUPLICATE = 2'd1;
+    localparam [1:0] RESULT_CONFLICT = 2'd2;
+
+    reg clk;
+    reg rst_n;
+    reg rx_valid;
+    wire rx_ready;
+    reg [7:0] rx_data;
+    wire command_valid;
+    reg command_ready;
+    wire [31:0] command_seq;
+    wire [7:0] command_id;
+    wire [7:0] command_channel;
+    wire [7:0] command_value;
+    wire [7:0] command_flags;
+    wire [1:0] command_result;
+    wire [15:0] crc_error_count;
+    wire [15:0] timeout_count;
+    wire [15:0] format_error_count;
+
+    reg [7:0] frame [0:19];
+    integer i;
+    integer wait_cycles;
+    reg [31:0] held_seq;
+    reg [31:0] held_command;
+    reg [1:0] held_result;
+
+    prod2u_p4_host_rx #(
+        .CLK_HZ(10000),
+        .INTER_BYTE_TIMEOUT_MS(2)
+    ) dut (
+        .clk(clk),
+        .rst_n(rst_n),
+        .rx_valid(rx_valid),
+        .rx_ready(rx_ready),
+        .rx_data(rx_data),
+        .command_valid(command_valid),
+        .command_ready(command_ready),
+        .command_seq(command_seq),
+        .command_id(command_id),
+        .command_channel(command_channel),
+        .command_value(command_value),
+        .command_flags(command_flags),
+        .command_result(command_result),
+        .crc_error_count(crc_error_count),
+        .timeout_count(timeout_count),
+        .format_error_count(format_error_count)
+    );
+
+    initial begin
+        clk = 1'b0;
+        forever #5 clk = ~clk;
+    end
+
+    function [15:0] crc16_byte;
+        input [15:0] crc_in;
+        input [7:0] data;
+        reg [15:0] value;
+        integer bit_index;
+        begin
+            value = crc_in ^ {data, 8'h00};
+            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
+                if (value[15]) begin
+                    value = (value << 1) ^ 16'h1021;
+                end else begin
+                    value = value << 1;
+                end
+            end
+            crc16_byte = value;
+        end
+    endfunction
+
+    task build_command_frame;
+        input [31:0] seq;
+        input [7:0] cmd;
+        input [7:0] channel;
+        input [7:0] value;
+        input [7:0] flags;
+        reg [15:0] crc;
+        begin
+            frame[0] = 8'ha5;
+            frame[1] = 8'h5a;
+            frame[2] = 8'h02;
+            frame[3] = 8'h04;
+            frame[4] = 8'h05;
+            frame[5] = seq[7:0];
+            frame[6] = seq[15:8];
+            frame[7] = seq[23:16];
+            frame[8] = seq[31:24];
+            frame[9] = 8'h00;
+            frame[10] = 8'h00;
+            frame[11] = 8'h00;
+            frame[12] = 8'h00;
+            frame[13] = 8'h04;
+            frame[14] = cmd;
+            frame[15] = channel;
+            frame[16] = value;
+            frame[17] = flags;
+            crc = 16'hffff;
+            for (i = 2; i <= 17; i = i + 1) begin
+                crc = crc16_byte(crc, frame[i]);
+            end
+            frame[18] = crc[7:0];
+            frame[19] = crc[15:8];
+        end
+    endtask
+
+    task send_byte;
+        input [7:0] value;
+        begin
+            while (!rx_ready) begin
+                @(negedge clk);
+            end
+            rx_data = value;
+            rx_valid = 1'b1;
+            @(posedge clk);
+            #1;
+            @(negedge clk);
+            rx_valid = 1'b0;
+        end
+    endtask
+
+    task send_built_frame;
+        begin
+            for (i = 0; i < 20; i = i + 1) begin
+                send_byte(frame[i]);
+            end
+        end
+    endtask
+
+    task expect_command;
+        input [31:0] seq;
+        input [31:0] command;
+        input [1:0] result;
+        begin
+            wait_cycles = 0;
+            while (!command_valid && wait_cycles < 20) begin
+                @(negedge clk);
+                wait_cycles = wait_cycles + 1;
+            end
+            if (!command_valid) begin
+                $display("command result timeout seq=%08x", seq);
+                $fatal;
+            end
+            if (command_seq !== seq ||
+                {command_id, command_channel, command_value, command_flags} !== command ||
+                command_result !== result) begin
+                $display(
+                    "command mismatch seq=%08x/%08x command=%08x/%08x result=%0d/%0d",
+                    command_seq,
+                    seq,
+                    {command_id, command_channel, command_value, command_flags},
+                    command,
+                    command_result,
+                    result
+                );
+                $fatal;
+            end
+            @(posedge clk);
+            #1;
+            if (command_valid) begin
+                $display("command_valid did not clear after ready handshake");
+                $fatal;
+            end
+        end
+    endtask
+
+    initial begin
+        rst_n = 1'b0;
+        rx_valid = 1'b0;
+        rx_data = 8'h00;
+        command_ready = 1'b1;
+        repeat (4) @(negedge clk);
+        rst_n = 1'b1;
+
+        // Repeated A5 must preserve the possible start of magic.
+        build_command_frame(32'h00000010, 8'h21, 8'h03, 8'h28, 8'h00);
+        send_byte(8'h00);
+        send_byte(8'ha5);
+        send_byte(8'ha5);
+        for (i = 1; i < 20; i = i + 1) begin
+            send_byte(frame[i]);
+        end
+        expect_command(32'h00000010, 32'h21032800, RESULT_NEW);
+
+        build_command_frame(32'h00000010, 8'h21, 8'h03, 8'h28, 8'h00);
+        send_built_frame();
+        expect_command(32'h00000010, 32'h21032800, RESULT_DUPLICATE);
+
+        build_command_frame(32'h00000011, 8'h21, 8'h03, 8'h28, 8'h01);
+        send_built_frame();
+        expect_command(32'h00000011, 32'h21032801, RESULT_NEW);
+
+        build_command_frame(32'h00000011, 8'h21, 8'h03, 8'h28, 8'h00);
+        frame[3] = 8'h03;
+        send_built_frame();
+        repeat (3) @(negedge clk);
+        if (command_valid || format_error_count !== 16'd1) begin
+            $display("wrong profile was not rejected count=%0d valid=%0d", format_error_count, command_valid);
+            $fatal;
+        end
+
+        build_command_frame(32'h00000011, 8'h21, 8'h03, 8'h28, 8'h00);
+        frame[4] = 8'h06;
+        send_built_frame();
+        repeat (3) @(negedge clk);
+        if (command_valid || format_error_count !== 16'd2) begin
+            $display("wrong frame type was not rejected count=%0d valid=%0d", format_error_count, command_valid);
+            $fatal;
+        end
+
+        build_command_frame(32'h00000011, 8'h21, 8'h03, 8'h28, 8'h00);
+        frame[13] = 8'h03;
+        send_built_frame();
+        repeat (3) @(negedge clk);
+        if (command_valid || format_error_count !== 16'd3) begin
+            $display("wrong command length was not rejected count=%0d valid=%0d", format_error_count, command_valid);
+            $fatal;
+        end
+
+        build_command_frame(32'h00000010, 8'h21, 8'h03, 8'h29, 8'h00);
+        send_built_frame();
+        expect_command(32'h00000010, 32'h21032900, RESULT_CONFLICT);
+
+        build_command_frame(32'h00000013, 8'h24, 8'h00, 8'h00, 8'h00);
+        send_built_frame();
+        expect_command(32'h00000013, 32'h24000000, RESULT_CONFLICT);
+
+        build_command_frame(32'h00000012, 8'h24, 8'h00, 8'h00, 8'h00);
+        send_built_frame();
+        expect_command(32'h00000012, 32'h24000000, RESULT_NEW);
+
+        build_command_frame(32'h00000013, 8'h20, 8'h01, 8'h32, 8'h00);
+        frame[19] = frame[19] ^ 8'h01;
+        send_built_frame();
+        repeat (3) @(negedge clk);
+        if (command_valid || crc_error_count !== 16'd1) begin
+            $display("bad CRC was not rejected count=%0d valid=%0d", crc_error_count, command_valid);
+            $fatal;
+        end
+
+        // Partial frames expire after the parameterized 2 ms interval.
+        send_byte(8'ha5);
+        send_byte(8'h5a);
+        send_byte(8'h02);
+        repeat (19) @(negedge clk);
+        if (timeout_count !== 16'd0) begin
+            $display("inter-byte timeout asserted before the 2 ms boundary count=%0d", timeout_count);
+            $fatal;
+        end
+        @(negedge clk);
+        if (timeout_count !== 16'd1 || command_valid) begin
+            $display("inter-byte timeout mismatch count=%0d valid=%0d", timeout_count, command_valid);
+            $fatal;
+        end
+
+        // Wrong version is a format error; a following good magic must recover.
+        send_byte(8'ha5);
+        send_byte(8'h5a);
+        send_byte(8'h03);
+        if (format_error_count !== 16'd4) begin
+            $display("wrong version did not increment format error count=%0d", format_error_count);
+            $fatal;
+        end
+
+        command_ready = 1'b0;
+        build_command_frame(32'h00000013, 8'h20, 8'h01, 8'h32, 8'h00);
+        send_built_frame();
+        wait_cycles = 0;
+        while (!command_valid && wait_cycles < 20) begin
+            @(negedge clk);
+            wait_cycles = wait_cycles + 1;
+        end
+        held_seq = command_seq;
+        held_command = {command_id, command_channel, command_value, command_flags};
+        held_result = command_result;
+        repeat (5) begin
+            @(negedge clk);
+            if (!command_valid || rx_ready || command_seq !== held_seq ||
+                {command_id, command_channel, command_value, command_flags} !== held_command ||
+                command_result !== held_result) begin
+                $display("command output changed or RX accepted data under backpressure");
+                $fatal;
+            end
+        end
+        if (held_seq !== 32'h00000013 || held_command !== 32'h20013200 || held_result !== RESULT_NEW) begin
+            $display("backpressured command contents mismatch");
+            $fatal;
+        end
+        command_ready = 1'b1;
+        @(posedge clk);
+        #1;
+        if (command_valid || !rx_ready) begin
+            $display("command handshake did not release RX");
+            $fatal;
+        end
+
+        $display("PASS: prod2u_p4_host_rx_tb");
+        $finish;
+    end
+endmodule

+ 201 - 0
tests/sim/prod2u_p4_tx_scheduler_tb.v

@@ -0,0 +1,201 @@
+`timescale 1ns/1ps
+
+module prod2u_p4_tx_scheduler_tb;
+    reg clk;
+    reg rst_n;
+    reg ack_valid;
+    wire ack_ready;
+    reg [7:0] ack_frame_type;
+    reg [31:0] ack_seq;
+    reg [31:0] ack_timestamp_tick;
+    reg [7:0] ack_payload_len;
+    reg [511:0] ack_payload;
+    reg response_valid;
+    wire response_ready;
+    reg [7:0] response_frame_type;
+    reg [31:0] response_seq;
+    reg [31:0] response_timestamp_tick;
+    reg [7:0] response_payload_len;
+    reg [511:0] response_payload;
+    reg trace_valid;
+    wire trace_ready;
+    reg [7:0] trace_frame_type;
+    reg [31:0] trace_seq;
+    reg [31:0] trace_timestamp_tick;
+    reg [7:0] trace_payload_len;
+    reg [511:0] trace_payload;
+    wire frame_valid;
+    reg frame_ready;
+    wire [1:0] frame_source;
+    wire [7:0] frame_type;
+    wire [31:0] frame_seq;
+    wire [31:0] frame_timestamp_tick;
+    wire [7:0] frame_payload_len;
+    wire [511:0] frame_payload;
+    wire [31:0] trace_drop_count;
+
+    prod2u_p4_tx_scheduler dut (
+        .clk(clk), .rst_n(rst_n),
+        .ack_valid(ack_valid), .ack_ready(ack_ready), .ack_frame_type(ack_frame_type),
+        .ack_seq(ack_seq), .ack_timestamp_tick(ack_timestamp_tick),
+        .ack_payload_len(ack_payload_len), .ack_payload(ack_payload),
+        .response_valid(response_valid), .response_ready(response_ready),
+        .response_frame_type(response_frame_type), .response_seq(response_seq),
+        .response_timestamp_tick(response_timestamp_tick),
+        .response_payload_len(response_payload_len), .response_payload(response_payload),
+        .trace_valid(trace_valid), .trace_ready(trace_ready), .trace_frame_type(trace_frame_type),
+        .trace_seq(trace_seq), .trace_timestamp_tick(trace_timestamp_tick),
+        .trace_payload_len(trace_payload_len), .trace_payload(trace_payload),
+        .frame_valid(frame_valid), .frame_ready(frame_ready), .frame_source(frame_source),
+        .frame_type(frame_type), .frame_seq(frame_seq),
+        .frame_timestamp_tick(frame_timestamp_tick), .frame_payload_len(frame_payload_len),
+        .frame_payload(frame_payload), .trace_drop_count(trace_drop_count)
+    );
+
+    initial begin
+        clk = 1'b0;
+        forever #5 clk = ~clk;
+    end
+
+    task expect_frame;
+        input [1:0] source;
+        input [7:0] kind;
+        input [31:0] seq;
+        input [7:0] first_byte;
+        integer guard;
+        begin
+            guard = 0;
+            while (!frame_valid && guard < 20) begin
+                @(negedge clk);
+                guard = guard + 1;
+            end
+            if (!frame_valid || frame_source !== source || frame_type !== kind ||
+                frame_seq !== seq || frame_payload[7:0] !== first_byte) begin
+                $display("frame mismatch source=%0d/%0d type=%02x/%02x seq=%08x/%08x", frame_source, source, frame_type, kind, frame_seq, seq);
+                $fatal;
+            end
+        end
+    endtask
+
+    task complete_current;
+        input [1:0] source;
+        begin
+            @(negedge clk);
+            frame_ready = 1'b1;
+            #1;
+            if ((source == 2'd0 && !ack_ready) ||
+                (source == 2'd1 && !response_ready) ||
+                (source == 2'd2 && !trace_ready)) begin
+                $display("selected source did not receive completion ready");
+                $fatal;
+            end
+            @(posedge clk);
+            #1;
+            if (source == 2'd0) ack_valid = 1'b0;
+            if (source == 2'd1) response_valid = 1'b0;
+            if (source == 2'd2) trace_valid = 1'b0;
+            @(negedge clk);
+            frame_ready = 1'b0;
+        end
+    endtask
+
+    initial begin
+        rst_n = 1'b0;
+        frame_ready = 1'b0;
+        ack_valid = 1'b0;
+        ack_frame_type = 8'h06;
+        ack_seq = 32'd1;
+        ack_timestamp_tick = 32'd11;
+        ack_payload_len = 8'd8;
+        ack_payload = 512'd0;
+        ack_payload[7:0] = 8'ha1;
+        response_valid = 1'b0;
+        response_frame_type = 8'h0d;
+        response_seq = 32'd2;
+        response_timestamp_tick = 32'd12;
+        response_payload_len = 8'd28;
+        response_payload = 512'd0;
+        response_payload[7:0] = 8'hb2;
+        trace_valid = 1'b0;
+        trace_frame_type = 8'h0f;
+        trace_seq = 32'd3;
+        trace_timestamp_tick = 32'd13;
+        trace_payload_len = 8'd64;
+        trace_payload = {64{8'hc3}};
+        repeat (4) @(negedge clk);
+        rst_n = 1'b1;
+
+        // The source registers are the queues; scheduler locks only one owner.
+        ack_valid = 1'b1;
+        response_valid = 1'b1;
+        trace_valid = 1'b1;
+        expect_frame(2'd0, 8'h06, 32'd1, 8'ha1);
+        repeat (3) begin
+            @(negedge clk);
+            if (!frame_valid || frame_source !== 2'd0 || frame_seq !== 32'd1 ||
+                ack_ready || response_ready || trace_ready) begin
+                $display("ACK frame changed or source was released before serializer completion valid=%b source=%0d seq=%08x ack_ready=%b response_ready=%b trace_ready=%b frame_ready=%b",
+                         frame_valid, frame_source, frame_seq, ack_ready, response_ready,
+                         trace_ready, frame_ready);
+                $fatal;
+            end
+        end
+        complete_current(2'd0);
+
+        // Response was already pending and now owns the non-preemptive frame.
+        expect_frame(2'd1, 8'h0d, 32'd2, 8'hb2);
+        ack_seq = 32'd4;
+        ack_payload[7:0] = 8'ha4;
+        ack_valid = 1'b1;
+        repeat (2) @(negedge clk);
+        if (frame_source !== 2'd1 || frame_seq !== 32'd2) begin
+            $display("new ACK preempted an active response frame");
+            $fatal;
+        end
+        complete_current(2'd1);
+        expect_frame(2'd0, 8'h06, 32'd4, 8'ha4);
+        complete_current(2'd0);
+        expect_frame(2'd2, 8'h0f, 32'd3, 8'hc3);
+        complete_current(2'd2);
+
+        // A maximum-size response streams without an extra 512-bit queue copy.
+        response_seq = 32'd5;
+        response_payload_len = 8'd64;
+        response_payload = {64{8'h5a}};
+        response_valid = 1'b1;
+        expect_frame(2'd1, 8'h0d, 32'd5, 8'h5a);
+        if (frame_payload[511:504] !== 8'h5a) begin
+            $display("64-byte response was truncated");
+            $fatal;
+        end
+        complete_current(2'd1);
+
+        response_payload_len = 8'd65;
+        response_valid = 1'b1;
+        repeat (3) @(negedge clk);
+        if (frame_valid || response_ready) begin
+            $display("oversize reliable response was accepted");
+            $fatal;
+        end
+        response_valid = 1'b0;
+
+        trace_payload_len = 8'd65;
+        trace_valid = 1'b1;
+        @(negedge clk);
+        if (!trace_ready) begin
+            $display("oversize trace must be consumed as an accounted drop");
+            $fatal;
+        end
+        @(posedge clk);
+        #1;
+        trace_valid = 1'b0;
+        @(negedge clk);
+        if (trace_drop_count !== 32'd1 || frame_valid) begin
+            $display("oversize trace drop count mismatch count=%0d", trace_drop_count);
+            $fatal;
+        end
+
+        $display("PASS: prod2u_p4_tx_scheduler_tb");
+        $finish;
+    end
+endmodule

+ 59 - 0
tests/unit/test_pid_harness.py

@@ -23,10 +23,12 @@ from pid_harness import (  # noqa: E402
     clean_runtime_payload,
     clean_runtime_payload,
     contract_coverage_matrix_payload,
     contract_coverage_matrix_payload,
     contract_replay_payload,
     contract_replay_payload,
+    cmd_static,
     cmd_uart_validate,
     cmd_uart_validate,
     offline_fidelity_gate_v1_payload,
     offline_fidelity_gate_v1_payload,
     offline_toolchain_bootstrap_payload,
     offline_toolchain_bootstrap_payload,
     formal_payload,
     formal_payload,
+    formal_targets,
     hdl_testbenches,
     hdl_testbenches,
     hdl_sim_payload,
     hdl_sim_payload,
     VERILATOR_LINT_WAIVERS,
     VERILATOR_LINT_WAIVERS,
@@ -49,6 +51,30 @@ from pid_harness import (  # noqa: E402
 
 
 
 
 class PidHarnessTests(unittest.TestCase):
 class PidHarnessTests(unittest.TestCase):
+    def test_static_command_can_emit_a_machine_readable_receipt(self) -> None:
+        completed = __import__("subprocess").CompletedProcess(
+            args=[sys.executable, "verify_pid_study.py"],
+            returncode=0,
+            stdout="PASS: static project checks\n",
+            stderr="",
+        )
+        with tempfile.TemporaryDirectory() as temporary_directory:
+            report = Path(temporary_directory) / "static.json"
+            args = build_parser().parse_args(["static", "--json", "--report-file", str(report)])
+            stdout = __import__("io").StringIO()
+            with mock.patch("pid_harness.run_python", return_value=completed), contextlib.redirect_stdout(stdout):
+                returncode = cmd_static(args)
+
+            payload = json.loads(stdout.getvalue())
+            written = json.loads(report.read_text(encoding="utf-8"))
+
+        self.assertEqual(returncode, 0)
+        self.assertEqual(payload, written)
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["verification_layer"], "static")
+        self.assertEqual(payload["returncode"], 0)
+        self.assertIn("PASS: static project checks", payload["stdout"])
+
     def valid_offline_toolchain_payload(self) -> dict:
     def valid_offline_toolchain_payload(self) -> dict:
         tools = {
         tools = {
             "python": {"status": "present", "path": r"C:\Python\python.exe"},
             "python": {"status": "present", "path": r"C:\Python\python.exe"},
@@ -286,6 +312,8 @@ Clock Summary
             "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921",
             "prod2u_bmc_replay_binary921",
             "prod2u_bmc_replay_binary921",
+            "prod2u_fan_tach_binary921_v2_normal",
+            "prod2u_fan_tach_binary921_v2_trace",
         ]:
         ]:
             with self.subTest(top=top):
             with self.subTest(top=top):
                 payload = td_build_payload(run=False, top=top)
                 payload = td_build_payload(run=False, top=top)
@@ -302,6 +330,8 @@ Clock Summary
         debug_binary_top = "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921"
         debug_binary_top = "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921"
         formal_binary_top = "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921"
         formal_binary_top = "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921"
         production_binary_top = "prod2u_bmc_replay_binary921"
         production_binary_top = "prod2u_bmc_replay_binary921"
+        production_fan_tach_normal_top = "prod2u_fan_tach_binary921_v2_normal"
+        production_fan_tach_trace_top = "prod2u_fan_tach_binary921_v2_trace"
         self.assertEqual(
         self.assertEqual(
             set(TD_TOP_PROFILES),
             set(TD_TOP_PROFILES),
             {
             {
@@ -314,6 +344,8 @@ Clock Summary
                 debug_binary_top,
                 debug_binary_top,
                 formal_binary_top,
                 formal_binary_top,
                 production_binary_top,
                 production_binary_top,
+                production_fan_tach_normal_top,
+                production_fan_tach_trace_top,
             },
             },
         )
         )
 
 
@@ -425,6 +457,33 @@ Clock Summary
             sources,
             sources,
         )
         )
 
 
+    def test_prod2u_profile4_hdl_and_formal_targets_are_registered(self) -> None:
+        tests_by_name = {item["name"]: item for item in hdl_testbenches()}
+        for name in (
+            "prod2u_p4_host_rx_tb",
+            "prod2u_p4_tx_scheduler_tb",
+            "prod2u_fan_tach_capture8_tb",
+            "prod2u_fan_pwm_bank_tb",
+            "prod2u_fan_tach_binary921_v2_core_tb",
+        ):
+            self.assertIn(name, tests_by_name)
+
+        core_sources = tests_by_name["prod2u_fan_tach_binary921_v2_core_tb"]["sources"]
+        self.assertIn("src/rtl/prod2u_fan_tach_binary921_v2_core.v", core_sources)
+        self.assertIn("tests/sim/prod2u_fan_tach_binary921_v2_core_tb.v", core_sources)
+        formal = {item["name"]: item for item in formal_targets()}
+        self.assertEqual(formal["prod2u_fan_data_path"]["sby"], "tests/formal/prod2u_fan_data_path.sby")
+        self.assertIn("prod2u_fan_data_path", formal_payload(run=False)["properties"])
+
+    def test_prod2u_profile4_td_receipts_declare_the_profile4_schema(self) -> None:
+        for top in (
+            "prod2u_fan_tach_binary921_v2_normal",
+            "prod2u_fan_tach_binary921_v2_trace",
+        ):
+            with self.subTest(top=top):
+                payload = td_build_payload(run=False, top=top)
+                self.assertEqual(payload["schema"], "prod2u-td-build-receipt-v1")
+
     def test_latest_td_project_and_scripts_are_build_only(self) -> None:
     def test_latest_td_project_and_scripts_are_build_only(self) -> None:
         stems = [
         stems = [
             "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921",

+ 23 - 0
tests/unit/test_pin_inventory.py

@@ -297,6 +297,29 @@ class PinInventoryTests(unittest.TestCase):
         self.assertEqual(active["assignments"], payload["assignments"])
         self.assertEqual(active["assignments"], payload["assignments"])
         self.assertEqual(active["uart_assignments"], payload["uart_assignments"])
         self.assertEqual(active["uart_assignments"], payload["uart_assignments"])
 
 
+    def test_prod2u_profile4_uses_uart2_combined_port_and_leaves_uart1_idle(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        payload = diagnostic_profile_assignments(inventory, "prod2u-fan-tach-binary921-v2")
+
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "prod2u-fan-tach-binary921-v2")
+        self.assertEqual(payload["bmc_source"], "out_of_scope")
+        self.assertEqual(payload["live_bmc_link_status"], "out_of_scope")
+        self.assertEqual(payload["transport"], "combined_host_debug_uart")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[2]"], "T4")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[21]"], "R10")
+        self.assertEqual(payload["assignments"]["fan_pwm_out[2]"], "B1")
+        self.assertEqual(payload["assignments"]["fan_fg_in[4]"], "C1")
+        self.assertEqual(payload["assignments"]["fan_fg_in[5]"], "C2")
+        self.assertEqual(payload["uart_assignments"]["idle_uart1_tx"]["fpga_ball"], "L10")
+        self.assertEqual(payload["uart_assignments"]["ignored_uart1_rx"]["fpga_ball"], "M9")
+        self.assertEqual(payload["uart_assignments"]["combined_debug_host_uart_tx"]["fpga_ball"], "M10")
+        self.assertEqual(payload["uart_assignments"]["combined_debug_host_uart_rx"]["fpga_ball"], "N11")
+        self.assertEqual(payload["ptc_substitutions"], {})
+        self.assertEqual(payload["conflict_check"]["status"], "pass")
+        self.assertIn("UART1", payload["authority_boundary"])
+        self.assertIn("out of scope", payload["authority_boundary"])
+
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     unittest.main()
     unittest.main()

+ 24 - 0
tests/unit/test_prod2u_contract.py

@@ -94,10 +94,34 @@ def program_receipt(build_id: str = "1234ABCD") -> dict:
         "process_cleanup": {
         "process_cleanup": {
             "status": "pass",
             "status": "pass",
             "td_root": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412",
             "td_root": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412",
+            "identity_audit_completed_before_action": True,
+            "ownership_policy": {
+                "owner": "DESKTOP\\Administrator",
+                "session_id": 1,
+                "parent_pid": 1234,
+                "approved_binaries": [
+                    {
+                        "name": "bw_commands_prompt.exe",
+                        "path": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412\\bin\\bw_commands_prompt.exe",
+                        "exe_sha256": "6" * 64,
+                    }
+                ],
+                "command_line": "bw_commands_prompt.exe -file program-sram.tcl",
+            },
+            "discovered_processes": [],
+            "harness_owned_processes": [],
+            "blocking_processes": [],
             "graceful_close_requested": [],
             "graceful_close_requested": [],
             "forced_terminated": [],
             "forced_terminated": [],
             "wait_seconds": 5.0,
             "wait_seconds": 5.0,
             "remaining": [],
             "remaining": [],
+            "post_action_audit_completed": True,
+            "post_action_discovered_processes": [],
+            "post_action_harness_owned_processes": [],
+            "post_action_blocking_processes": [],
+            "residual_processes": [],
+            "post_action_errors": [],
+            "errors": [],
         },
         },
         "artifacts": {
         "artifacts": {
             name: {"path": name, "size": 1, "sha256": char * 64}
             name: {"path": name, "size": 1, "sha256": char * 64}

ファイルの差分が大きいため隠しています
+ 1122 - 0
tests/unit/test_prod2u_p4_cli_campaign.py


+ 200 - 0
tests/unit/test_prod2u_p4_cli_identity.py

@@ -0,0 +1,200 @@
+#!/usr/bin/env python3
+"""Identity and entrypoint contracts for the Prod2U Profile 4 CLI."""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+
+ROOT = Path(__file__).resolve().parents[2]
+TOOLS = ROOT / "tools"
+sys.path.insert(0, str(TOOLS))
+
+
+def load_cli():
+    path = TOOLS / "prod2u_p4_cli.py"
+    spec = importlib.util.spec_from_file_location("test_prod2u_p4_cli_identity_owned", path)
+    if spec is None or spec.loader is None:
+        raise AssertionError(f"unable to import {path}")
+    module = importlib.util.module_from_spec(spec)
+    sys.modules[spec.name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def write_identity_fixture(root: Path, *, variant: str = "normal") -> SimpleNamespace:
+    from prod2u_build_identity import source_manifest_sha256
+
+    bitstream = root / f"{variant}.bit"
+    bitstream.write_bytes(f"prod2u-p4-{variant}".encode("ascii"))
+    bitstream_sha256 = hashlib.sha256(bitstream.read_bytes()).hexdigest()
+    source = {
+        "schema": "prod2u-source-manifest-v1",
+        "profile": "prod2u-fan-tach-binary921-v2",
+        "td_version": "6.2.2.198412",
+        "files": [
+            {
+                "path": f"src/top/prod2u_fan_tach_binary921_v2_{variant}_top.v",
+                "size": 1,
+                "sha256": "a" * 64,
+            }
+        ],
+    }
+    source_hash = source_manifest_sha256(source)
+    source.update(source_manifest_sha256=source_hash, build_id=source_hash[:8].upper())
+    source_manifest = root / f"{variant}-source-manifest.json"
+    source_manifest.write_text(json.dumps(source), encoding="utf-8")
+
+    td_receipt = root / f"{variant}-td.json"
+    td_receipt.write_text(
+        json.dumps(
+            {
+                "schema": "prod2u-td-build-receipt-v1",
+                "status": "pass",
+                "top": f"prod2u_fan_tach_binary921_v2_{variant}",
+                "top_module": f"prod2u_fan_tach_binary921_v2_{variant}_top",
+                "pin_profile": "prod2u-fan-tach-binary921-v2",
+                "build_id": source["build_id"],
+                "source_manifest_sha256": source_hash,
+                "build_identity": {
+                    "status": "pass",
+                    "build_id": source["build_id"],
+                    "source_manifest_sha256": source_hash,
+                    "staged_manifest_sha256": "b" * 64,
+                },
+                "por_initialization": {"status": "not_applicable", "failures": []},
+                "bitstream": {
+                    "path": str(bitstream),
+                    "size": bitstream.stat().st_size,
+                    "sha256": bitstream_sha256,
+                },
+                "resources": {"utilization": {"lut": 1}},
+                "timing": {"setup_wns_ns": 1.0, "hold_wns_ns": 0.1},
+                "timing_gate": {"status": "pass", "failures": []},
+                "syn": {"returncode": 0, "log_has_error": False},
+                "phy": {"returncode": 0, "log_has_error": False},
+            }
+        ),
+        encoding="utf-8",
+    )
+    td_root = root / "TD"
+    (td_root / "bin").mkdir(parents=True)
+    (td_root / "bin" / "bw_commands_prompt.exe").write_bytes(b"fixture")
+    return SimpleNamespace(
+        variant=variant,
+        build_id=int(source["build_id"], 16),
+        bitstream=bitstream,
+        sha256=bitstream_sha256,
+        td_receipt=td_receipt,
+        source_manifest=source_manifest,
+        td_root=td_root,
+        output_dir=root / "evidence",
+        run_id="identity-fixture",
+    )
+
+
+class Prod2UP4CliIdentityTests(unittest.TestCase):
+    def test_live_commands_require_td_receipt_and_source_manifest(self) -> None:
+        cli = load_cli()
+        parser = cli.build_parser()
+        with self.assertRaises(SystemExit):
+            parser.parse_args(
+                [
+                    "program-only",
+                    "--variant",
+                    "normal",
+                    "--build-id",
+                    "1234ABCD",
+                    "--bitstream",
+                    "normal.bit",
+                    "--sha256",
+                    "a" * 64,
+                    "--td-root",
+                    "TD",
+                    "--output-dir",
+                    "evidence",
+                ]
+            )
+
+    def test_preflight_hash_binds_bitstream_manifest_td_receipt_and_build(self) -> None:
+        cli = load_cli()
+        with tempfile.TemporaryDirectory() as temp:
+            args = write_identity_fixture(Path(temp))
+            passed = cli.run_preflight(args)
+            receipt = json.loads(args.td_receipt.read_text(encoding="utf-8"))
+            receipt["build_id"] = "DEADBEEF"
+            args.td_receipt.write_text(json.dumps(receipt), encoding="utf-8")
+            failed = cli.run_preflight(args)
+
+        self.assertEqual(passed["status"], "pass", passed)
+        self.assertEqual(passed["identity"]["build_id"], f"{args.build_id:08X}")
+        self.assertEqual(passed["identity"]["source_manifest_status"], "pass")
+        self.assertEqual(passed["identity"]["td_receipt_status"], "pass")
+        self.assertEqual(failed["status"], "fail")
+        self.assertIn("td_receipt_build_id_mismatch", failed["failures"])
+
+    def test_default_powershell_selftest_routes_to_profile4(self) -> None:
+        result = subprocess.run(
+            [
+                "powershell.exe",
+                "-NoProfile",
+                "-ExecutionPolicy",
+                "Bypass",
+                "-File",
+                str(TOOLS / "prod2u.ps1"),
+                "selftest",
+            ],
+            cwd=ROOT,
+            capture_output=True,
+            text=True,
+            check=False,
+        )
+        payload = json.loads(result.stdout)
+        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+        self.assertEqual(payload["profile_id"], 4)
+        self.assertEqual(payload["protocol_version"], 2)
+
+    def test_powershell_profile_routing_preserves_profile3_read_only_commands(self) -> None:
+        def run(*arguments: str) -> subprocess.CompletedProcess[str]:
+            return subprocess.run(
+                [
+                    "powershell.exe",
+                    "-NoProfile",
+                    "-ExecutionPolicy",
+                    "Bypass",
+                    "-File",
+                    str(TOOLS / "prod2u.ps1"),
+                    *arguments,
+                ],
+                cwd=ROOT,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+
+        profile3_selftest = run("selftest", "-Profile", "profile3")
+        self.assertEqual(profile3_selftest.returncode, 0, profile3_selftest.stdout + profile3_selftest.stderr)
+        self.assertEqual(json.loads(profile3_selftest.stdout)["profile_id"], 3)
+
+        with tempfile.TemporaryDirectory() as temp:
+            receipt = Path(temp) / "td.json"
+            receipt.write_text("{}", encoding="utf-8")
+            profile3_legacy = run("validate-td-receipt", "-Profile", "profile3", "-TdReceipt", str(receipt))
+        self.assertEqual(profile3_legacy.returncode, 1)
+        self.assertEqual(json.loads(profile3_legacy.stdout)["schema"], "prod2u-td-receipt-schema-validation-v1")
+
+        unsupported = run("validate-td-receipt", "-Profile", "profile4")
+        self.assertNotEqual(unsupported.returncode, 0)
+        self.assertIn("Profile 4 does not support command: validate-td-receipt", unsupported.stdout + unsupported.stderr)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 394 - 0
tests/unit/test_prod2u_p4_evidence_binding.py

@@ -0,0 +1,394 @@
+import copy
+import importlib.util
+from pathlib import Path
+import tempfile
+import sys
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def load_validator():
+    path = ROOT / "tools" / "prod2u_p4_validate.py"
+    spec = importlib.util.spec_from_file_location("prod2u_p4_validate_binding_test", path)
+    module = importlib.util.module_from_spec(spec)
+    assert spec.loader is not None
+    sys.modules[spec.name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def load_campaign():
+    path = ROOT / "tools" / "prod2u_p4_campaign.py"
+    spec = importlib.util.spec_from_file_location("prod2u_p4_campaign_binding_test", path)
+    module = importlib.util.module_from_spec(spec)
+    assert spec.loader is not None
+    sys.modules[spec.name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def identity(variant="trace"):
+    return {
+        "dut_id": "DUT-P4-01",
+        "build_id": "A1B2C3D4",
+        "bitstream_sha256": "a" * 64,
+        "variant": variant,
+        "profile": "prod2u-fan-tach-binary921-v2",
+        "source_manifest_sha256": "b" * 64,
+    }
+
+
+def binding(variant="trace"):
+    return {
+        "programmer_receipt": {
+            "path": "round/programmer/program-sram-receipt.json",
+            "sha256": "c" * 64,
+            "status": "pass",
+        },
+        "pre_program_raw": {"path": "round/pre-program.raw", "sha256": "d" * 64},
+        "combined_rx_raw": {"path": "round/combined-rx.raw", "sha256": "e" * 64},
+        "raw_transcript": {"path": "round/wire-transcript.json", "sha256": "f" * 64},
+        "td_receipt": {"path": f"{variant}-td.json", "sha256": "1" * 64},
+        "source_manifest": {"path": f"{variant}-source-manifest.json", "sha256": "b" * 64},
+        "package_manifest": {"path": "manifest.json", "sha256": "2" * 64},
+        "package_inventory": {"path": "sha256-inventory.json", "sha256": "3" * 64},
+        "identity": identity(variant),
+    }
+
+
+def qualification():
+    def layer(**artifacts):
+        return {"status": "pass", "artifacts": artifacts}
+
+    return {
+        "schema": "prod2u-p4-static-qualification-v1",
+        "status": "pass",
+        "profile": "prod2u-fan-tach-binary921-v2",
+        "profile_id": 4,
+        "layers": {
+            "source": layer(
+                normal_source_manifest={"path": "normal-source.json", "sha256": "b" * 64},
+                trace_source_manifest={"path": "trace-source.json", "sha256": "b" * 64},
+            ),
+            "protocol": layer(protocol_junit={"path": "protocol.xml", "sha256": "4" * 64}),
+            "rtl": layer(rtl_sim_receipt={"path": "rtl.json", "sha256": "5" * 64}),
+            "formal": layer(formal_receipt={"path": "formal.json", "sha256": "6" * 64}),
+            "td_normal": layer(normal_td_receipt={"path": "normal-td.json", "sha256": "1" * 64}),
+            "td_trace": layer(trace_td_receipt={"path": "trace-td.json", "sha256": "1" * 64}),
+            "package": layer(
+                package_manifest={"path": "manifest.json", "sha256": "2" * 64},
+                package_inventory={"path": "inventory.json", "sha256": "3" * 64},
+                static_receipt={"path": "static.json", "sha256": "7" * 64},
+            ),
+        },
+        "variants": {},
+        "failures": [],
+    }
+
+
+def evidence(round_number=1, variant="trace"):
+    actual_identity = identity(variant)
+    rpm_by_setting = {0: 9000, 20: 1200, 40: 1500, 60: 1800, 80: 2200, 100: 2600}
+    windows = []
+    raw_samples = []
+    snapshot_seq = 100
+    window_index = 0
+    for setting in (0, 20, 40, 60, 80, 100):
+        for _ in range(2):
+            windows.append(
+                {
+                    "index": window_index,
+                    "start_s": window_index,
+                    "end_s": window_index + 1,
+                    "continuous": True,
+                    "snapshot_seq": snapshot_seq,
+                    "overflow_mask": 0,
+                }
+            )
+            snapshot_seq += 1
+            window_index += 1
+        for sample_index in range(5):
+            windows.append(
+                {
+                    "index": window_index,
+                    "start_s": window_index,
+                    "end_s": window_index + 1,
+                    "continuous": True,
+                    "snapshot_seq": snapshot_seq,
+                    "overflow_mask": 0,
+                }
+            )
+            raw_samples.append(
+                {
+                    "fan_setting_percent": setting,
+                    "snapshot_seq": snapshot_seq,
+                    "overflow_mask": 0,
+                    "FG5": {
+                        "window_edges": 0 if setting == 100 or (setting == 80 and sample_index == 4) else 1,
+                        "rpm": rpm_by_setting[setting],
+                    },
+                    "FG6": {"window_edges": 0, "rpm": 0},
+                }
+            )
+            snapshot_seq += 1
+            window_index += 1
+    return {
+        "schema": "prod2u-p4-evidence-v2",
+        "evidence_id": f"P4-20260712-01-R{round_number:02d}",
+        "campaign_id": "P4-20260712-01",
+        "campaign_identity": {**actual_identity, "planned_rounds": 10},
+        "round": round_number,
+        "identity": actual_identity,
+        "bmc": {"status": "out_of_scope", "reason": "offline"},
+        "layers": {
+            "required": {
+                name: "pass"
+                for name in (
+                    "program_sram",
+                    "fresh_ready",
+                    "host_ack",
+                    "pwm_state",
+                    "fan3_tach_trend",
+                    "timeout_fallback",
+                    "disable",
+                    "ptc_command_path",
+                )
+            },
+            "optional": {},
+        },
+        "fan": {"FAN3": {"FG5": "detected", "FG6": "absent"}},
+        "windows": windows,
+        "raw_samples": raw_samples,
+        "correlation": {
+            "samples": [
+                {"fan_setting_percent": setting, "rpm": rpm}
+                for setting, rpm in rpm_by_setting.items()
+            ],
+            "spearman_rho": 1.0,
+            "low_mean_rpm": 1350,
+            "high_mean_rpm": 2400,
+            "high_significantly_higher": True,
+        },
+        "rpm": {"status": "not_qualified", "reason": "trend only"},
+        "ptc": {"actuation": True, "measurement": "not_run"},
+        "evidence_binding": binding(variant),
+    }
+
+
+def test_complete_evidence_binding_is_accepted():
+    validator = load_validator()
+
+    result = validator.validate_evidence(evidence())
+
+    assert result["status"] == "pass", result["failures"]
+
+
+def test_missing_raw_binding_blocks_evidence_pass():
+    validator = load_validator()
+    document = evidence()
+    del document["evidence_binding"]["combined_rx_raw"]
+
+    result = validator.validate_evidence(document)
+
+    assert result["status"] == "fail"
+    assert "missing_binding:combined_rx_raw:1" in result["failures"]
+
+
+def test_tampered_binding_identity_blocks_evidence_pass():
+    validator = load_validator()
+    document = evidence()
+    document["evidence_binding"]["identity"]["build_id"] = "DEADBEEF"
+
+    result = validator.validate_evidence(document)
+
+    assert result["status"] == "fail"
+    assert "binding_identity_mismatch:1:build_id" in result["failures"]
+
+
+def test_declared_strong_rho_cannot_mask_weak_trend_samples():
+    validator = load_validator()
+    document = evidence()
+    document["correlation"]["samples"] = [
+        {"fan_setting_percent": setting, "rpm": rpm}
+        for setting, rpm in ((0, 1000), (20, 1000), (40, 1000), (60, 1000), (80, 1000), (100, 1000))
+    ]
+    document["correlation"]["spearman_rho"] = 1.0
+    document["correlation"]["low_mean_rpm"] = 1000
+    document["correlation"]["high_mean_rpm"] = 3000
+
+    result = validator.validate_evidence(document)
+
+    assert result["status"] == "fail"
+    assert any(failure.startswith("spearman_") for failure in result["failures"])
+
+
+def test_final_gate_requires_round_evidence_bindings():
+    validator = load_validator()
+    gate = {
+        "schema": "prod2u-p4-final-gate-v2",
+        "status": "pass",
+        "campaign_id": "P4-20260712-01",
+        "campaign_identity": {**identity(), "planned_rounds": 10},
+        "bmc": {"status": "out_of_scope", "reason": "offline"},
+        "layers": {"required": {"software_model": "pass"}, "optional": {}},
+        "round_count": 10,
+        "failures": [],
+    }
+
+    result = validator.validate_final_gate(gate)
+
+    assert result["status"] == "fail"
+    assert "missing_required:final_gate:evidence_bindings" in result["failures"]
+
+
+def test_campaign_binding_helper_hashes_all_required_evidence_files():
+    campaign = load_campaign()
+    actual_identity = identity()
+    with tempfile.TemporaryDirectory() as temporary:
+        root = Path(temporary)
+        files = {
+            "programmer_receipt": root / "programmer.json",
+            "pre_program_raw": root / "pre-program.raw",
+            "combined_rx_raw": root / "combined-rx.raw",
+            "raw_transcript": root / "wire-transcript.json",
+            "td_receipt": root / "trace-td.json",
+            "source_manifest": root / "trace-source-manifest.json",
+            "package_manifest": root / "manifest.json",
+            "package_inventory": root / "sha256-inventory.json",
+        }
+        for index, path in enumerate(files.values(), start=1):
+            path.write_bytes(f"artifact-{index}".encode("ascii"))
+
+        result = campaign.build_evidence_binding(
+            programmer_receipt=files["programmer_receipt"],
+            pre_program_raw=files["pre_program_raw"],
+            combined_rx_raw=files["combined_rx_raw"],
+            raw_transcript=files["raw_transcript"],
+            td_receipt=files["td_receipt"],
+            source_manifest=files["source_manifest"],
+            package_manifest=files["package_manifest"],
+            package_inventory=files["package_inventory"],
+            identity=actual_identity,
+        )
+
+    assert set(result) == {
+        "programmer_receipt",
+        "pre_program_raw",
+        "combined_rx_raw",
+        "raw_transcript",
+        "td_receipt",
+        "source_manifest",
+        "package_manifest",
+        "package_inventory",
+        "identity",
+    }
+    assert all(len(result[name]["sha256"]) == 64 for name in result if name != "identity")
+    assert result["programmer_receipt"]["status"] == "pass"
+    assert result["identity"] == actual_identity
+
+
+def test_build_final_gate_preserves_all_round_bindings_and_validates_strictly():
+    validator = load_validator()
+    rounds = []
+    bindings = []
+    for round_number in range(1, 11):
+        item = evidence(round_number)
+        rounds.append(item)
+        bindings.append({"round": round_number, "evidence_binding": item["evidence_binding"]})
+    campaign = {
+        "schema": "prod2u-p4-campaign-v2",
+        "status": "pass",
+        "campaign_id": "P4-20260712-01",
+        "campaign_identity": {**identity(), "planned_rounds": 10},
+        "bmc": {"status": "out_of_scope", "reason": "offline"},
+        "qualification": qualification(),
+        "rounds": rounds,
+        "evidence_bindings": bindings,
+    }
+
+    gate = validator.build_final_gate(campaign)
+    result = validator.validate_final_gate(gate)
+
+    assert result["status"] == "pass", result["failures"]
+    assert gate["evidence_bindings"] == bindings
+
+
+def test_execute_round_marks_weak_trend_as_failed_round():
+    campaign = load_campaign()
+
+    class WeakController:
+        watchdog_safe = True
+        snapshot_seq = 0
+
+        def set_fan(self, channel, percent):
+            del channel, percent
+
+        def sample_fans(self):
+            self.snapshot_seq += 1
+            return {
+                "snapshot_seq": self.snapshot_seq,
+                "overflow_mask": 0,
+                "FG5": {"window_edges": 1, "rpm": 1000},
+                "FG6": {"window_edges": 1, "rpm": 1000},
+            }
+
+        def set_ptc(self, channel, percent):
+            del channel, percent
+
+        def sleep(self, seconds):
+            del seconds
+
+        def disable(self):
+            return None
+
+        def verify_timeout_fallback(self):
+            return {"status": "pass", "timeout_active": True}
+
+        def evidence_summary(self):
+            return {
+                "all_acks_matched": True,
+                "fan_commit_acks": 6,
+                "ptc_commit_acks": 12,
+                "disable_commit_acks": 1,
+                "timeout_verified": True,
+            }
+
+    result = campaign.execute_round(WeakController(), campaign.RoundPlan(1, 1, "trace"))
+
+    assert result["status"] == "fail"
+    assert any(failure.startswith("trend_") for failure in result["failures"])
+
+
+def test_source_manifest_file_hash_is_distinct_from_declared_source_identity_hash():
+    campaign = load_campaign()
+    validator = load_validator()
+    actual_identity = identity()
+    with tempfile.TemporaryDirectory() as temporary:
+        root = Path(temporary)
+        files = {}
+        for name in (
+            "programmer_receipt",
+            "pre_program_raw",
+            "combined_rx_raw",
+            "raw_transcript",
+            "td_receipt",
+            "source_manifest",
+            "package_manifest",
+            "package_inventory",
+        ):
+            files[name] = root / f"{name}.artifact"
+            files[name].write_bytes(b"artifact")
+        files["source_manifest"].write_text(
+            '{"source_manifest_sha256":"' + actual_identity["source_manifest_sha256"] + '"}',
+            encoding="ascii",
+        )
+        bound = campaign.build_evidence_binding(**files, identity=actual_identity)
+        document = evidence()
+        document["evidence_binding"] = bound
+
+    result = validator.validate_evidence(document)
+
+    assert result["status"] == "pass", result["failures"]
+    assert bound["source_manifest"]["sha256"] != actual_identity["source_manifest_sha256"]
+    assert bound["source_manifest"]["declared_sha256"] == actual_identity["source_manifest_sha256"]

+ 297 - 0
tests/unit/test_prod2u_p4_integration.py

@@ -0,0 +1,297 @@
+#!/usr/bin/env python3
+"""Integration contracts for the Prod2U Profile 4 fan-tach release."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+
+sys.dont_write_bytecode = True
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "tools"))
+PROFILE = "prod2u-fan-tach-binary921-v2"
+NORMAL_STEM = "prod2u_fan_tach_binary921_v2_normal"
+TRACE_STEM = "prod2u_fan_tach_binary921_v2_trace"
+
+
+def load_pid_harness():
+    path = ROOT / "tools" / "pid_harness.py"
+    spec = importlib.util.spec_from_file_location("pid_harness_p4_contract", path)
+    if spec is None or spec.loader is None:
+        raise AssertionError(f"unable to import {path}")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class Prod2UProfile4IntegrationTests(unittest.TestCase):
+    def test_shared_frame_serializer_is_versioned_without_breaking_v1_default(self) -> None:
+        source = (ROOT / "src" / "rtl" / "binary921_frame_tx.v").read_text(encoding="ascii")
+
+        self.assertIn("parameter [7:0] VERSION = 8'h01", source)
+        self.assertIn("parameter integer LATCH_PAYLOAD = 1", source)
+        self.assertNotIn("localparam [7:0] VERSION = 8'h01", source)
+        self.assertIn(".data(tx_data)", source)
+        self.assertNotIn("reg [7:0] send_byte;", source)
+        self.assertEqual(source.count("case (next_byte_index)"), 1)
+        self.assertNotIn("case (byte_index)", source)
+
+    def test_profile4_release_assets_exist(self) -> None:
+        expected = (
+            ROOT / "src" / "rtl" / "prod2u_fan_tach_binary921_v2_core.v",
+            ROOT / "src" / "top" / f"{NORMAL_STEM}_top.v",
+            ROOT / "src" / "top" / f"{TRACE_STEM}_top.v",
+            ROOT / "constraints" / "prod2u_fan_tach_binary921_v2.adc",
+            ROOT / "td" / f"{NORMAL_STEM}.prj",
+            ROOT / "td" / f"{TRACE_STEM}.prj",
+            ROOT / "td" / "syn" / f"{NORMAL_STEM}.tcl",
+            ROOT / "td" / "syn" / f"{TRACE_STEM}.tcl",
+            ROOT / "td" / "phy" / f"{NORMAL_STEM}.tcl",
+            ROOT / "td" / "phy" / f"{TRACE_STEM}.tcl",
+            ROOT / "tools" / "prod2u_p4_cli.py",
+            ROOT / "tools" / "prod2u_p4_collector.py",
+            ROOT / "tools" / "prod2u_p4_campaign.py",
+            ROOT / "tools" / "package_prod2u_p4.ps1",
+            ROOT / "docs" / "prod2u-p4-start-here.zh-CN.md",
+        )
+
+        missing = [path.relative_to(ROOT).as_posix() for path in expected if not path.is_file()]
+        self.assertEqual(missing, [])
+
+    def test_pid_harness_registers_independent_normal_and_trace_builds(self) -> None:
+        harness = load_pid_harness()
+
+        for stem, variant in ((NORMAL_STEM, "normal"), (TRACE_STEM, "trace")):
+            with self.subTest(variant=variant):
+                profile = harness.TD_TOP_PROFILES[stem]
+                self.assertEqual(profile["top_module"], f"{stem}_top")
+                self.assertEqual(profile["pin_profile"], PROFILE)
+                self.assertEqual(profile["protocol"], "binary921-v2")
+                self.assertEqual(profile["runtime_profile_id"], 4)
+                self.assertEqual(profile["variant"], variant)
+                self.assertEqual(profile["host_uart_baud"], 921600)
+                self.assertEqual(profile["host_uart_clks_per_bit"], 27)
+                self.assertEqual(profile["bmc_status"], "out_of_scope")
+
+    def test_top_and_constraints_lock_uart_idle_and_connector_pwm_semantics(self) -> None:
+        adc = (ROOT / "constraints" / "prod2u_fan_tach_binary921_v2.adc").read_text(encoding="ascii")
+        self.assertIn("{ host_uart_tx } { LOCATION = M10;", adc)
+        self.assertIn("{ host_uart_rx } { LOCATION = N11;", adc)
+        self.assertIn("{ bmc_uart_tx } { LOCATION = L10;", adc)
+        self.assertIn("{ bmc_uart_rx } { LOCATION = M9;", adc)
+        self.assertIn("{ fan_pwm_out[2] } { LOCATION = B1;", adc)
+        self.assertIn("{ fan_fg_in[4] } { LOCATION = C1;", adc)
+        self.assertIn("{ fan_fg_in[5] } { LOCATION = C2;", adc)
+
+        for stem, trace_mode in ((NORMAL_STEM, "0"), (TRACE_STEM, "1")):
+            source = (ROOT / "src" / "top" / f"{stem}_top.v").read_text(encoding="ascii")
+            with self.subTest(stem=stem):
+                self.assertIn("assign bmc_uart_tx = 1'b1;", source)
+                self.assertIn("prod2u_fan_tach_binary921_v2_core", source)
+                self.assertIn(f".TRACE_MODE({trace_mode})", source)
+                self.assertIn(".PROFILE_ID(8'd4)", source)
+                self.assertNotIn("bmc_uart_raw48_poll_lite", source)
+
+        core = (ROOT / "src" / "rtl" / "prod2u_fan_tach_binary921_v2_core.v").read_text(encoding="ascii")
+        self.assertIn("FAN_PWM_PERIOD_TICKS = 1000", core)
+        self.assertIn("PTC_PWM_PERIOD_TICKS = 2500000", core)
+        self.assertIn("HOST_TIMEOUT_TICKS = 125000000", core)
+        self.assertIn("prod2u_fan_tach_capture8", core)
+        self.assertIn("prod2u_fan_pwm_bank", core)
+
+    def test_normal_variant_uses_a_28_byte_transport_and_disables_trace_generation(self) -> None:
+        normal = (ROOT / "src" / "top" / f"{NORMAL_STEM}_top.v").read_text(encoding="ascii")
+        trace = (ROOT / "src" / "top" / f"{TRACE_STEM}_top.v").read_text(encoding="ascii")
+        core = (ROOT / "src" / "rtl" / "prod2u_fan_tach_binary921_v2_core.v").read_text(encoding="ascii")
+
+        self.assertIn("localparam integer TX_MAX_PAYLOAD_BYTES = 28;", normal)
+        self.assertGreaterEqual(normal.count(".MAX_PAYLOAD_BYTES(TX_MAX_PAYLOAD_BYTES)"), 2)
+        self.assertIn(".LATCH_PAYLOAD(0)", normal)
+        self.assertIn("localparam integer TX_MAX_PAYLOAD_BYTES = 64;", trace)
+        self.assertGreaterEqual(trace.count(".MAX_PAYLOAD_BYTES(TX_MAX_PAYLOAD_BYTES)"), 2)
+        self.assertIn(".LATCH_PAYLOAD(0)", trace)
+        self.assertIn(
+            "if ((TRACE_MODE != 0) && !trace_valid && trace_snapshot_safe)",
+            core,
+        )
+
+    def test_tach_capture_keeps_only_windowed_protocol_state(self) -> None:
+        capture = (ROOT / "src" / "rtl" / "prod2u_fan_tach_capture8.v").read_text(encoding="ascii")
+        core = (ROOT / "src" / "rtl" / "prod2u_fan_tach_binary921_v2_core.v").read_text(encoding="ascii")
+
+        self.assertNotIn("tach_total_edges", capture)
+        self.assertNotIn("total_edges", capture)
+        self.assertNotIn("tach_total_edges", core)
+
+    def test_core_payload_registers_match_the_fixed_wire_contract(self) -> None:
+        core = (ROOT / "src" / "rtl" / "prod2u_fan_tach_binary921_v2_core.v").read_text(encoding="ascii")
+
+        self.assertIn("output reg  [63:0]  ack_payload", core)
+        self.assertIn("output reg  [223:0] response_payload", core)
+        self.assertIn("output wire [511:0] trace_payload", core)
+        self.assertNotIn("cache_response_payload", core)
+        self.assertIn("TRACE_STABILITY_GUARD_TICKS", core)
+        self.assertIn("trace_snapshot_window_safe", core)
+        self.assertNotIn("trace_payload <=", core)
+
+    def test_fan_pwm_maps_requested_percent_to_connector_high_duty(self) -> None:
+        source = (ROOT / "src" / "rtl" / "prod2u_fan_pwm_bank.v").read_text(encoding="ascii")
+
+        self.assertIn("raw_ticks_from_connector_percent", source)
+        self.assertIn("7'd100 - connector_percent", source)
+        self.assertIn("(raw_percent_ticks << 3) + (raw_percent_ticks << 1)", source)
+        self.assertNotIn("PWM_PERIOD_TICKS *", source)
+        self.assertNotIn(") / 100", source)
+
+    def test_fixed_period_counters_use_minimum_production_widths(self) -> None:
+        core = (ROOT / "src" / "rtl" / "prod2u_fan_tach_binary921_v2_core.v").read_text(encoding="ascii")
+        tach = (ROOT / "src" / "rtl" / "prod2u_fan_tach_capture8.v").read_text(encoding="ascii")
+        host_rx = (ROOT / "src" / "rtl" / "prod2u_p4_host_rx.v").read_text(encoding="ascii")
+
+        self.assertIn("localparam integer STARTUP_COUNTER_WIDTH = 18;", core)
+        self.assertIn("localparam integer WATCHDOG_COUNTER_WIDTH = 27;", core)
+        self.assertIn("localparam integer PTC_STEP_COUNTER_WIDTH = 15;", core)
+        self.assertIn("localparam integer TRACE_PERIOD_COUNTER_WIDTH = 22;", core)
+        self.assertIn("reg [STARTUP_COUNTER_WIDTH-1:0] startup_counter;", core)
+        self.assertIn("reg [WATCHDOG_COUNTER_WIDTH-1:0] watchdog_counter;", core)
+        self.assertIn("reg [PTC_STEP_COUNTER_WIDTH-1:0] ptc_step_tick;", core)
+        self.assertIn("reg [TRACE_PERIOD_COUNTER_WIDTH-1:0] trace_period_counter;", core)
+        self.assertNotIn("reg [31:0] startup_counter;", core)
+        self.assertNotIn("reg [31:0] watchdog_counter;", core)
+        self.assertNotIn("reg [31:0] ptc_step_tick;", core)
+        self.assertNotIn("reg [31:0] trace_period_counter;", core)
+        self.assertIn(".PWM_COUNTER_WIDTH(10)", core)
+        self.assertIn(".WINDOW_COUNTER_WIDTH(25)", core)
+        self.assertIn("output wire [31:0]                  sample_ticks", tach)
+        self.assertIn("assign sample_ticks = WINDOW_TICKS;", tach)
+        self.assertNotIn("sample_ticks <=", tach)
+        self.assertIn("reg [15:0] timeout_counter;", host_rx)
+        self.assertNotIn("timeout_counter <= 32'd0", host_rx)
+
+    def test_rtl_status_codes_match_the_profile4_python_contract(self) -> None:
+        from prod2u_p4_protocol import StatusCode
+
+        source = (ROOT / "src" / "rtl" / "prod2u_fan_tach_binary921_v2_core.v").read_text(encoding="ascii")
+        expected = {
+            "STATUS_OK": StatusCode.OK,
+            "STATUS_UNSUPPORTED_IN_PROFILE": StatusCode.UNSUPPORTED_IN_PROFILE,
+            "STATUS_BAD_FLAGS": StatusCode.BAD_FLAGS,
+            "STATUS_BAD_LENGTH": StatusCode.BAD_LENGTH,
+            "STATUS_BAD_CHANNEL": StatusCode.BAD_CHANNEL,
+            "STATUS_BAD_VALUE": StatusCode.BAD_VALUE,
+            "STATUS_SEQ_CONFLICT": StatusCode.SEQ_CONFLICT,
+            "STATUS_SEQ_JUMP": StatusCode.SEQ_JUMP,
+            "STATUS_QUEUE_FULL": StatusCode.QUEUE_FULL,
+        }
+        for name, value in expected.items():
+            self.assertIn(f"localparam [7:0] {name} = 8'h{int(value):02x};", source)
+
+    def test_td_sources_exclude_bmc_poll_and_build_each_variant(self) -> None:
+        required_rtl = (
+            "src/rtl/uart_rx_8n1.v",
+            "src/rtl/uart_tx_8n1.v",
+            "src/rtl/binary921_crc16.v",
+            "src/rtl/binary921_frame_tx.v",
+            "src/rtl/prod2u_por.v",
+            "src/rtl/prod2u_p4_host_rx.v",
+            "src/rtl/prod2u_p4_tx_scheduler.v",
+            "src/rtl/prod2u_fan_tach_capture8.v",
+            "src/rtl/prod2u_fan_pwm_bank.v",
+            "src/rtl/prod2u_fan_tach_binary921_v2_core.v",
+        )
+        for stem in (NORMAL_STEM, TRACE_STEM):
+            project = (ROOT / "td" / f"{stem}.prj").read_text(encoding="utf-8")
+            syn = (ROOT / "td" / "syn" / f"{stem}.tcl").read_text(encoding="ascii")
+            phy = (ROOT / "td" / "phy" / f"{stem}.tcl").read_text(encoding="ascii")
+            combined = "\n".join((project.replace("../", ""), syn, phy))
+            with self.subTest(stem=stem):
+                for source in required_rtl:
+                    self.assertIn(source, combined)
+                self.assertIn(f"src/top/{stem}_top.v", combined)
+                self.assertNotIn("bmc_uart_raw48_poll_lite", combined)
+                self.assertIn("set_param route effort routability", phy)
+                self.assertIn(f"bitgen -bit {stem}.bit", phy)
+
+    def test_profile4_cli_selftest_and_powershell_contract(self) -> None:
+        cli = ROOT / "tools" / "prod2u_p4_cli.py"
+        env = os.environ.copy()
+        env["PYTHONDONTWRITEBYTECODE"] = "1"
+        result = subprocess.run(
+            [sys.executable, "-B", str(cli), "selftest"],
+            cwd=ROOT,
+            capture_output=True,
+            text=True,
+            check=False,
+            env=env,
+        )
+        self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
+        payload = json.loads(result.stdout)
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], PROFILE)
+        self.assertEqual(payload["profile_id"], 4)
+        self.assertEqual(payload["protocol_version"], 2)
+        self.assertEqual(payload["bmc_status"], "out_of_scope")
+
+        wrapper = (ROOT / "tools" / "prod2u.ps1").read_text(encoding="utf-8")
+        for command in (
+            "bootstrap",
+            "selftest",
+            "preflight",
+            "program-only",
+            "query-fans",
+            "set-fan",
+            "set-ptc",
+            "disable",
+            "accept",
+        ):
+            self.assertIn(f'"{command}"', wrapper)
+        self.assertIn("PYTHONDONTWRITEBYTECODE", wrapper)
+        self.assertIn("-B", wrapper)
+
+    def test_live_collector_does_not_mislabel_unrelated_required_layer_failures(self) -> None:
+        source = (ROOT / "tools" / "prod2u_p4_cli.py").read_text(encoding="utf-8")
+
+        self.assertIn(
+            'if required_layers["program_sram"] != "pass" or required_layers["fresh_ready"] != "pass":',
+            source,
+        )
+
+    def test_package_and_runbook_lock_sram_rs232_and_bmc_boundaries(self) -> None:
+        packager = (ROOT / "tools" / "package_prod2u_p4.ps1").read_text(encoding="utf-8")
+        for artifact in (
+            "normal.bit",
+            "trace.bit",
+            "requirements.lock",
+            "wheelhouse",
+            "sha256-inventory.json",
+            "prod2u-p4-start-here.zh-CN.md",
+        ):
+            self.assertIn(artifact, packager)
+        self.assertIn("prod2u-p4-fantach-", packager)
+        self.assertIn("fan_connector_high_duty_percent", packager)
+        self.assertIn("100_minus_requested_percent", packager)
+        self.assertNotIn("PROGRAM_FLASH", packager)
+        self.assertNotIn("ERASE_FLASH", packager)
+        self.assertNotIn("PROGRAM_SPIBIN", packager)
+
+        runbook = (ROOT / "docs" / "prod2u-p4-start-here.zh-CN.md").read_text(encoding="utf-8")
+        self.assertIn("CON78", runbook)
+        self.assertIn("pin1", runbook)
+        self.assertIn("pin2", runbook)
+        self.assertIn("pin3/4", runbook)
+        self.assertIn("USB-RS232", runbook)
+        self.assertIn("USB-TTL", runbook)
+        self.assertIn("200kHz", runbook)
+        self.assertIn("PROGRAM_SRAM", runbook)
+        self.assertIn("BMC", runbook)
+        self.assertIn("out_of_scope", runbook)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 443 - 0
tests/unit/test_prod2u_p4_package.py

@@ -0,0 +1,443 @@
+#!/usr/bin/env python3
+"""TDD contract tests for the immutable Prod2U Profile 4 handoff."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import subprocess
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+PACKAGER = ROOT / "tools" / "package_prod2u_p4.ps1"
+P4_TD_SCHEMA = ROOT / "schemas" / "prod2u_p4_td_build_receipt.schema.json"
+START_HERE = ROOT / "docs" / "prod2u-p4-start-here.zh-CN.md"
+RUNBOOK = ROOT / "docs" / "prod2u-p4-program-sram-runbook.zh-CN.md"
+
+
+def sha256(path: Path) -> str:
+    return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def build_fixture_source_manifest(*, source: Path) -> dict[str, object]:
+    relative = source.relative_to(ROOT).as_posix()
+    row = {"path": relative, "size": source.stat().st_size, "sha256": sha256(source)}
+    canonical = {
+        "schema": "prod2u-source-manifest-v1",
+        "profile": "prod2u-fan-tach-binary921-v2",
+        "td_version": "6.2.2.198412",
+        "files": [row],
+    }
+    manifest_hash = hashlib.sha256(
+        json.dumps(canonical, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
+    ).hexdigest()
+    return {
+        **canonical,
+        "source_manifest_sha256": manifest_hash,
+        "build_id": manifest_hash[:8].upper(),
+    }
+
+
+def write_fixture_release_assets(directory: Path) -> dict[str, Path]:
+    assets: dict[str, Path] = {}
+    for variant in ("normal", "trace"):
+        bitstream = directory / f"{variant}.bit"
+        bitstream.write_bytes(f"fixture-profile4-{variant}".encode("ascii"))
+        source_manifest = build_fixture_source_manifest(
+            source=ROOT / "src" / "top" / f"prod2u_fan_tach_binary921_v2_{variant}_top.v"
+        )
+        manifest_path = directory / f"{variant}-source-manifest.json"
+        manifest_path.write_text(json.dumps(source_manifest), encoding="utf-8")
+        receipt = {
+            "schema": "prod2u-td-build-receipt-v1",
+            "status": "pass",
+            "top": f"prod2u_fan_tach_binary921_v2_{variant}",
+            "top_module": f"prod2u_fan_tach_binary921_v2_{variant}_top",
+            "pin_profile": "prod2u-fan-tach-binary921-v2",
+            "build_id": source_manifest["build_id"],
+            "source_manifest_sha256": source_manifest["source_manifest_sha256"],
+            "build_identity": {
+                "status": "pass",
+                "build_id": source_manifest["build_id"],
+                "source_manifest_sha256": source_manifest["source_manifest_sha256"],
+                "staged_manifest_sha256": "a" * 64,
+            },
+            "bitstream": {"path": bitstream.name, "size": bitstream.stat().st_size, "sha256": sha256(bitstream)},
+            "resources": {"status": "pass"},
+            "timing": {"status": "pass"},
+            "timing_gate": {"status": "pass"},
+            "syn": {"returncode": 0, "log_has_error": False},
+            "phy": {"returncode": 0, "log_has_error": False},
+        }
+        receipt_path = directory / f"{variant}-td.json"
+        receipt_path.write_text(json.dumps(receipt), encoding="utf-8")
+        assets[f"{variant}_bitstream"] = bitstream
+        assets[f"{variant}_td_receipt"] = receipt_path
+        assets[f"{variant}_source_manifest"] = manifest_path
+    protocol = directory / "protocol-junit.xml"
+    protocol.write_text(
+        '<testsuites tests="4" failures="0" errors="0" skipped="0"><testsuite tests="4" failures="0" errors="0"/></testsuites>',
+        encoding="utf-8",
+    )
+    rtl = directory / "rtl-sim.json"
+    rtl.write_text(
+        json.dumps(
+            {
+                "status": "pass",
+                "verification_layer": "rtl_sim_compat",
+                "tests": [
+                    {"name": name, "status": "pass"}
+                    for name in (
+                        "prod2u_p4_host_rx_tb",
+                        "prod2u_p4_tx_scheduler_tb",
+                        "prod2u_fan_tach_capture8_tb",
+                        "prod2u_fan_pwm_bank_tb",
+                        "prod2u_fan_tach_binary921_v2_core_tb",
+                    )
+                ],
+            }
+        ),
+        encoding="utf-8",
+    )
+    formal = directory / "formal.json"
+    formal.write_text(
+        json.dumps(
+            {
+                "status": "pass",
+                "verification_layer": "formal",
+                "targets": [{"name": "prod2u_fan_data_path", "status": "pass", "returncode": 0}],
+            }
+        ),
+        encoding="utf-8",
+    )
+    static = directory / "static.json"
+    static.write_text(json.dumps({"status": "pass", "verification_layer": "static"}), encoding="utf-8")
+    assets.update(protocol_junit=protocol, rtl_sim_receipt=rtl, formal_receipt=formal, static_receipt=static)
+    return assets
+
+
+def run_package_wrapper(package: Path, command: str, *, venv_dir: Path | None = None) -> subprocess.CompletedProcess[str]:
+    arguments = [
+        "powershell.exe",
+        "-NoProfile",
+        "-ExecutionPolicy",
+        "Bypass",
+        "-File",
+        str(package / "prod2u.ps1"),
+        command,
+        "-Profile",
+        "profile4",
+    ]
+    if venv_dir is not None:
+        arguments.extend(["-VenvDir", str(venv_dir)])
+    return subprocess.run(arguments, cwd=package, capture_output=True, text=True, check=False)
+
+
+class Prod2UP4PackageTests(unittest.TestCase):
+    def test_packager_and_runbooks_lock_the_profile4_delivery_contract(self) -> None:
+        self.assertTrue(PACKAGER.is_file(), PACKAGER)
+        self.assertTrue(START_HERE.is_file(), START_HERE)
+        self.assertTrue(RUNBOOK.is_file(), RUNBOOK)
+
+        packager = PACKAGER.read_text(encoding="utf-8")
+        for required in (
+                "prod2u-p4-fantach-",
+            "normal.bit",
+            "trace.bit",
+            "normal-td.json",
+            "trace-td.json",
+            "normal-source-manifest.json",
+            "trace-source-manifest.json",
+            "wheelhouse",
+            "requirements.lock",
+            "sha256-inventory.json",
+            "PYTHONDONTWRITEBYTECODE",
+            "-B",
+            "__pycache__",
+            "*.pyc",
+            "out_of_scope",
+            "prod2u_programmer.py",
+            "prod2u_p4_td_build_receipt.schema.json",
+            "prod2u_p4_qualification.schema.json",
+            "protocol-junit.xml",
+            "rtl-sim.json",
+            "formal.json",
+            "static.json",
+            "prod2u.ps1",
+            "--package-root",
+        ):
+            with self.subTest(required=required):
+                self.assertIn(required, packager)
+        for forbidden in ("PROGRAM_FLASH", "ERASE_FLASH", "PROGRAM_SPIBIN", "DIRECT_FLASH_WRITE"):
+            with self.subTest(forbidden=forbidden):
+                self.assertNotIn(forbidden, packager)
+
+        documentation = START_HERE.read_text(encoding="utf-8") + "\n" + RUNBOOK.read_text(encoding="utf-8")
+        for required in (
+            "CON78",
+            "pin1",
+            "pin2",
+            "pin3/4",
+            "USB-RS232",
+            "USB-TTL",
+            "COM5",
+            "921600",
+            "200kHz",
+            "PROGRAM_SRAM",
+            "no power cycle",
+            "BMC",
+            "out_of_scope",
+            "FAN3",
+            "CON25",
+            "PWM3=B1",
+            "FG5=C1",
+            "FG6=C2",
+            "PTC1-6",
+        ):
+            with self.subTest(required=required):
+                self.assertIn(required, documentation)
+
+    def test_packager_rejects_missing_normal_bitstream_before_creating_a_package(self) -> None:
+        self.assertTrue(PACKAGER.is_file(), PACKAGER)
+        with tempfile.TemporaryDirectory() as temporary_directory:
+            temporary = Path(temporary_directory)
+            output = temporary / "out"
+            result = subprocess.run(
+                [
+                    "powershell.exe",
+                    "-NoProfile",
+                    "-ExecutionPolicy",
+                    "Bypass",
+                    "-File",
+                    str(PACKAGER),
+                    "-OutputDir",
+                    str(output),
+                    "-NormalBitstream",
+                    str(temporary / "missing-normal.bit"),
+                    "-TraceBitstream",
+                    str(temporary / "missing-trace.bit"),
+                    "-NormalTdReceipt",
+                    str(temporary / "missing-normal-td.json"),
+                    "-TraceTdReceipt",
+                    str(temporary / "missing-trace-td.json"),
+                    "-NormalSourceManifest",
+                    str(temporary / "missing-normal-source.json"),
+                    "-TraceSourceManifest",
+                    str(temporary / "missing-trace-source.json"),
+                    "-ProtocolJUnit",
+                    str(temporary / "missing-protocol.xml"),
+                    "-RtlSimReceipt",
+                    str(temporary / "missing-rtl.json"),
+                    "-FormalReceipt",
+                    str(temporary / "missing-formal.json"),
+                    "-StaticReceipt",
+                    str(temporary / "missing-static.json"),
+                ],
+                cwd=ROOT,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertNotEqual(result.returncode, 0)
+            self.assertIn("Normal bitstream is missing", result.stdout + result.stderr)
+            self.assertFalse(output.exists(), "validation failure must not create an output directory")
+
+    def test_fixture_package_validates_both_variants_and_detects_package_tampering(self) -> None:
+        with tempfile.TemporaryDirectory() as temporary_directory:
+            temporary = Path(temporary_directory)
+            assets = write_fixture_release_assets(temporary)
+            result = subprocess.run(
+                [
+                    "powershell.exe",
+                    "-NoProfile",
+                    "-ExecutionPolicy",
+                    "Bypass",
+                    "-File",
+                    str(PACKAGER),
+                    "-OutputDir",
+                    str(temporary / "out"),
+                    "-NormalBitstream",
+                    str(assets["normal_bitstream"]),
+                    "-TraceBitstream",
+                    str(assets["trace_bitstream"]),
+                    "-NormalTdReceipt",
+                    str(assets["normal_td_receipt"]),
+                    "-TraceTdReceipt",
+                    str(assets["trace_td_receipt"]),
+                    "-NormalSourceManifest",
+                    str(assets["normal_source_manifest"]),
+                    "-TraceSourceManifest",
+                    str(assets["trace_source_manifest"]),
+                    "-ProtocolJUnit",
+                    str(assets["protocol_junit"]),
+                    "-RtlSimReceipt",
+                    str(assets["rtl_sim_receipt"]),
+                    "-FormalReceipt",
+                    str(assets["formal_receipt"]),
+                    "-StaticReceipt",
+                    str(assets["static_receipt"]),
+                ],
+                cwd=ROOT,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+            payload = json.loads(result.stdout)
+            package = Path(payload["package_folder"])
+            archive = Path(payload["package_zip"])
+            self.assertTrue(P4_TD_SCHEMA.is_file(), P4_TD_SCHEMA)
+            self.assertEqual(payload["selftest"], {"folder": "pass", "zip": "pass"})
+            self.assertEqual(payload["bootstrap"], {"folder": "pass", "zip": "pass"})
+
+            required = {
+                "prod2u.ps1",
+                "prod2u_programmer.py",
+                "schemas/prod2u_p4_td_build_receipt.schema.json",
+                "schemas/prod2u_p4_qualification.schema.json",
+                "protocol-junit.xml",
+                "rtl-sim.json",
+                "formal.json",
+                "static.json",
+                "sha256-inventory.json",
+            }
+            with zipfile.ZipFile(archive) as handle:
+                self.assertTrue(required.issubset(set(handle.namelist())))
+                extract = temporary / "extracted"
+                handle.extractall(extract)
+
+            for root, label in ((package, "folder"), (extract, "extracted zip")):
+                bootstrap = run_package_wrapper(root, "bootstrap", venv_dir=temporary / f"{label}-runtime" / ".venv")
+                self.assertEqual(bootstrap.returncode, 0, bootstrap.stdout + bootstrap.stderr)
+                bootstrap_payload = json.loads(bootstrap.stdout)
+                self.assertEqual(bootstrap_payload["status"], "pass")
+                self.assertTrue(bootstrap_payload["no_index"])
+                self.assertTrue(bootstrap_payload["require_hashes"])
+                self.assertFalse(Path(bootstrap_payload["venv_dir"]).is_relative_to(root))
+
+                passed = run_package_wrapper(root, "selftest")
+                self.assertEqual(passed.returncode, 0, passed.stdout + passed.stderr)
+                passed_payload = json.loads(passed.stdout)
+                self.assertEqual(passed_payload["status"], "pass")
+                self.assertFalse(passed_payload["enumerated_com_ports"])
+                self.assertFalse(passed_payload["dtr"])
+                self.assertFalse(passed_payload["rts"])
+                self.assertFalse(passed_payload["flash_attempted"])
+
+                tracked = root / "prod2u_programmer.py"
+                original = tracked.read_bytes()
+                tracked.write_bytes(bytes([original[0] ^ 1]) + original[1:])
+                tampered = run_package_wrapper(root, "selftest")
+                self.assertNotEqual(tampered.returncode, 0)
+                self.assertIn("package_inventory_sha256_mismatch:prod2u_programmer.py", tampered.stdout + tampered.stderr)
+                tracked.write_bytes(original)
+
+                unlisted = root / "unexpected.txt"
+                unlisted.write_text("not part of the immutable package", encoding="ascii")
+                unlisted_result = run_package_wrapper(root, "selftest")
+                self.assertNotEqual(unlisted_result.returncode, 0)
+                self.assertIn("package_inventory_unlisted_file:unexpected.txt", unlisted_result.stdout + unlisted_result.stderr)
+
+    def test_supplied_release_assets_package_and_selftest_from_folder_and_zip(self) -> None:
+        required_environment = (
+            "PROD2U_P4_NORMAL_BIT",
+            "PROD2U_P4_TRACE_BIT",
+            "PROD2U_P4_NORMAL_TD_RECEIPT",
+            "PROD2U_P4_TRACE_TD_RECEIPT",
+            "PROD2U_P4_NORMAL_SOURCE_MANIFEST",
+            "PROD2U_P4_TRACE_SOURCE_MANIFEST",
+            "PROD2U_P4_PROTOCOL_JUNIT",
+            "PROD2U_P4_RTL_SIM_RECEIPT",
+            "PROD2U_P4_FORMAL_RECEIPT",
+            "PROD2U_P4_STATIC_RECEIPT",
+        )
+        missing = [name for name in required_environment if not os.environ.get(name)]
+        if missing:
+            self.skipTest("real Profile 4 release assets have not been supplied: " + ", ".join(missing))
+
+        with tempfile.TemporaryDirectory() as temporary_directory:
+            output = Path(temporary_directory) / "out"
+            command = [
+                "powershell.exe",
+                "-NoProfile",
+                "-ExecutionPolicy",
+                "Bypass",
+                "-File",
+                str(PACKAGER),
+                "-OutputDir",
+                str(output),
+                "-NormalBitstream",
+                os.environ["PROD2U_P4_NORMAL_BIT"],
+                "-TraceBitstream",
+                os.environ["PROD2U_P4_TRACE_BIT"],
+                "-NormalTdReceipt",
+                os.environ["PROD2U_P4_NORMAL_TD_RECEIPT"],
+                "-TraceTdReceipt",
+                os.environ["PROD2U_P4_TRACE_TD_RECEIPT"],
+                "-NormalSourceManifest",
+                os.environ["PROD2U_P4_NORMAL_SOURCE_MANIFEST"],
+                "-TraceSourceManifest",
+                os.environ["PROD2U_P4_TRACE_SOURCE_MANIFEST"],
+                "-ProtocolJUnit",
+                os.environ["PROD2U_P4_PROTOCOL_JUNIT"],
+                "-RtlSimReceipt",
+                os.environ["PROD2U_P4_RTL_SIM_RECEIPT"],
+                "-FormalReceipt",
+                os.environ["PROD2U_P4_FORMAL_RECEIPT"],
+                "-StaticReceipt",
+                os.environ["PROD2U_P4_STATIC_RECEIPT"],
+            ]
+            result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, check=False)
+            self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+            payload = json.loads(result.stdout)
+            package = Path(payload["package_folder"])
+            archive = Path(payload["package_zip"])
+            self.assertTrue(package.is_dir())
+            self.assertTrue(archive.is_file())
+            self.assertTrue((archive.with_suffix(archive.suffix + ".sha256.txt")).is_file())
+            self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), payload["package_zip_sha256"])
+            self.assertEqual(payload["selftest"]["folder"], "pass")
+            self.assertEqual(payload["selftest"]["zip"], "pass")
+            manifest = json.loads((package / "manifest.json").read_text(encoding="utf-8-sig"))
+            self.assertEqual(manifest["campaign"]["round_count"], 10)
+            self.assertEqual(manifest["campaign"]["final_variant"], "normal")
+            self.assertEqual(manifest["campaign"]["fan3_percent_ladder"], [0, 20, 40, 60, 80, 100])
+            self.assertEqual(manifest["campaign"]["ptc_percent"], 10)
+            self.assertEqual(manifest["campaign"]["ptc_hold_seconds"], 2)
+            self.assertEqual(
+                manifest["fan_tach"]["requested_percent_semantics"],
+                "fan_connector_high_duty_percent",
+            )
+            self.assertEqual(
+                manifest["fan_tach"]["cpld_high_level_effect"],
+                "npn_on_connector_pwm_low",
+            )
+            self.assertEqual(
+                manifest["fan_tach"]["cpld_high_duty_mapping"],
+                "100_minus_requested_percent",
+            )
+
+            with zipfile.ZipFile(archive) as package_zip:
+                names = set(package_zip.namelist())
+            for required in (
+                "normal.bit",
+                "trace.bit",
+                "manifest.json",
+                "sha256-inventory.json",
+                "wheelhouse/",
+                "requirements.lock",
+                "START-HERE.zh-CN.md",
+                "prod2u-p4-program-sram-runbook.zh-CN.md",
+                "schemas/prod2u_program_sram_receipt.schema.json",
+            ):
+                with self.subTest(required=required):
+                    self.assertTrue(any(name == required or name.startswith(required) for name in names), required)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 333 - 0
tests/unit/test_prod2u_p4_protocol.py

@@ -0,0 +1,333 @@
+#!/usr/bin/env python3
+"""Contract tests for the Prod2U Profile4 binary921 v2 wire protocol."""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+
+sys.dont_write_bytecode = True
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "tools"))
+
+from prod2u_p4_protocol import (  # noqa: E402
+    CommandId,
+    CommandTimeoutState,
+    FrameType,
+    P4FrameError,
+    StatusCode,
+    TimeoutPhase,
+    build_host_ack,
+    build_host_command,
+    crc16_ccitt,
+    decode_fan_telemetry,
+    decode_frame,
+    decode_host_ack,
+    decode_host_command,
+    decode_ready,
+    decode_status,
+    decode_stream,
+    encode_fan_telemetry,
+    encode_frame,
+    encode_ready,
+    encode_status,
+    observe_ack,
+    poll_timeout,
+    rpm_from_edges,
+    start_timeout,
+)
+
+
+class Prod2UProfile4ProtocolTests(unittest.TestCase):
+    def test_profile4_enum_values_match_the_approved_wire_contract(self) -> None:
+        self.assertEqual(FrameType.FAN_TELEMETRY, 0x0D)
+        self.assertEqual(FrameType.STATUS_RESPONSE, 0x0E)
+        self.assertEqual(FrameType.TRACE_SNAPSHOT, 0x0F)
+        self.assertFalse(hasattr(FrameType, "STATUS"))
+        self.assertEqual(CommandId.GET_FAN_TELEMETRY, 0x27)
+        self.assertEqual(
+            {
+                StatusCode.OK: 0x00,
+                StatusCode.UNSUPPORTED_IN_PROFILE: 0x01,
+                StatusCode.BAD_FLAGS: 0x02,
+                StatusCode.BAD_LENGTH: 0x03,
+                StatusCode.BAD_CHANNEL: 0x04,
+                StatusCode.BAD_VALUE: 0x05,
+                StatusCode.SEQ_CONFLICT: 0x06,
+                StatusCode.SEQ_JUMP: 0x07,
+                StatusCode.QUEUE_FULL: 0x08,
+            },
+            {member: int(member) for member in StatusCode},
+        )
+
+    def test_v2_profile4_envelope_roundtrip_and_crc_vector(self) -> None:
+        self.assertEqual(crc16_ccitt(b"123456789"), 0x29B1)
+
+        wire = encode_frame(
+            frame_type=FrameType.READY,
+            seq=0x01020304,
+            timestamp_tick=0x11223344,
+            payload=b"p4",
+        )
+
+        self.assertEqual(wire[:5], b"\xA5\x5A\x02\x04\x01")
+        self.assertEqual(wire[5:9], b"\x04\x03\x02\x01")
+        self.assertEqual(wire[9:13], b"\x44\x33\x22\x11")
+        self.assertEqual(wire[13], 2)
+        frame = decode_frame(wire)
+        self.assertEqual(frame.version, 2)
+        self.assertEqual(frame.profile_id, 4)
+        self.assertEqual(frame.frame_type, FrameType.READY)
+        self.assertEqual(frame.payload, b"p4")
+
+    def test_frame_decoder_rejects_wrong_version_profile_length_and_crc(self) -> None:
+        wire = bytearray(
+            encode_frame(frame_type=FrameType.READY, seq=1, timestamp_tick=2, payload=b"")
+        )
+        for index, message in ((2, "version"), (3, "profile")):
+            bad = bytearray(wire)
+            bad[index] ^= 1
+            with self.subTest(index=index):
+                with self.assertRaisesRegex(P4FrameError, message):
+                    decode_frame(bad)
+
+        with self.assertRaisesRegex(P4FrameError, "length"):
+            decode_frame(wire[:-1])
+        bad_crc = bytearray(wire)
+        bad_crc[-1] ^= 1
+        with self.assertRaisesRegex(P4FrameError, "crc"):
+            decode_frame(bad_crc)
+
+    def test_host_command_is_exactly_four_bytes_and_validates_enum(self) -> None:
+        wire = build_host_command(
+            seq=7,
+            command=CommandId.SET_FAN,
+            channel=3,
+            value=40,
+            flags=1,
+        )
+        frame = decode_frame(wire)
+        self.assertEqual(frame.frame_type, FrameType.HOST_CMD)
+        self.assertEqual(frame.payload, bytes([CommandId.SET_FAN, 3, 40, 1]))
+        command = decode_host_command(frame)
+        self.assertEqual(command.command, CommandId.SET_FAN)
+        self.assertEqual((command.channel, command.value, command.flags), (3, 40, 1))
+
+        with self.assertRaisesRegex(ValueError, "four bytes"):
+            decode_host_command(b"\x21\x03\x28")
+        with self.assertRaisesRegex(ValueError, "command"):
+            build_host_command(seq=8, command=0xFF)
+
+    def test_host_ack_has_the_exact_fixed_payload_and_uses_frame_seq(self) -> None:
+        wire = build_host_ack(
+            seq=0x89ABCDEF,
+            ok=True,
+            command=CommandId.GET_FAN_TELEMETRY,
+            status=StatusCode.OK,
+            detail=0xA5,
+            state_hash16=0x1234,
+            response_type=FrameType.FAN_TELEMETRY,
+            result_flags=0x03,
+        )
+        frame = decode_frame(wire)
+        self.assertEqual(frame.frame_type, FrameType.HOST_ACK)
+        self.assertEqual(frame.seq, 0x89ABCDEF)
+        self.assertEqual(
+            frame.payload,
+            bytes([1, CommandId.GET_FAN_TELEMETRY, StatusCode.OK, 0xA5, 0x34, 0x12, FrameType.FAN_TELEMETRY, 0x03]),
+        )
+        ack = decode_host_ack(frame)
+        self.assertTrue(ack.ok)
+        self.assertEqual(ack.command, CommandId.GET_FAN_TELEMETRY)
+        self.assertEqual(ack.status, StatusCode.OK)
+        self.assertEqual(ack.detail, 0xA5)
+        self.assertEqual(ack.state_hash16, 0x1234)
+        self.assertEqual(ack.response_type, FrameType.FAN_TELEMETRY)
+        self.assertEqual(ack.result_flags, 0x03)
+        self.assertEqual(ack.request_seq, 0x89ABCDEF)
+
+        with self.assertRaisesRegex(ValueError, "eight bytes"):
+            decode_host_ack(b"\x24\x00")
+
+    def test_ready_has_deterministic_identity_variant_and_startup_layout(self) -> None:
+        frame = decode_frame(
+            encode_ready(
+                seq=1,
+                timestamp_tick=10,
+                build_id=0x1234ABCD,
+                variant=1,
+                startup_reason=3,
+                startup_seq=0x7E,
+                capability_flags=0x89ABCDEF,
+            )
+        )
+        self.assertEqual(
+            frame.payload,
+            b"\xCD\xAB\x34\x12\x01\x03\x7E\x00\xEF\xCD\xAB\x89",
+        )
+        ready = decode_ready(frame)
+        self.assertEqual(ready.build_id, 0x1234ABCD)
+        self.assertEqual(ready.variant, 1)
+        self.assertEqual(ready.startup_reason, 3)
+        self.assertEqual(ready.startup_seq, 0x7E)
+        self.assertEqual(ready.capability_flags, 0x89ABCDEF)
+
+        with self.assertRaisesRegex(ValueError, "variant"):
+            encode_ready(
+                seq=1,
+                timestamp_tick=10,
+                build_id=1,
+                variant=2,
+                startup_reason=0,
+                startup_seq=0,
+                capability_flags=0,
+            )
+
+    def test_status_response_roundtrip_uses_frame_type_0x0e(self) -> None:
+        frame = decode_frame(
+            encode_status(
+                seq=2,
+                timestamp_tick=20,
+                status=StatusCode.QUEUE_FULL,
+                last_command_status=StatusCode.OK,
+                flags=0x05,
+                variant=1,
+                command_count=513,
+                watchdog_ticks_remaining=0x11223344,
+                tach_snapshot_seq=0x55667788,
+                trace_drop_count=0x01020304,
+                parser_error_count=0xA1A2A3A4,
+            )
+        )
+        self.assertEqual(frame.frame_type, FrameType.STATUS_RESPONSE)
+        self.assertEqual(frame.seq, 2)
+        self.assertEqual(
+            frame.payload,
+            b"\x08\x00\x05\x01\x01\x02\x00\x00"
+            b"\x44\x33\x22\x11\x88\x77\x66\x55"
+            b"\x04\x03\x02\x01\xA4\xA3\xA2\xA1",
+        )
+        status = decode_status(frame)
+        self.assertEqual(status.status, StatusCode.QUEUE_FULL)
+        self.assertEqual(status.last_command_status, StatusCode.OK)
+        self.assertEqual(status.flags, 5)
+        self.assertEqual(status.variant, 1)
+        self.assertEqual(status.command_count, 513)
+        self.assertEqual(status.watchdog_ticks_remaining, 0x11223344)
+        self.assertEqual(status.tach_snapshot_seq, 0x55667788)
+        self.assertEqual(status.trace_drop_count, 0x01020304)
+        self.assertEqual(status.parser_error_count, 0xA1A2A3A4)
+
+    def test_fan_telemetry_is_one_atomic_eight_channel_snapshot(self) -> None:
+        edge_counts = (1, 2, 3, 4, 5, 6, 7, 0xFFFF)
+        frame = decode_frame(
+            encode_fan_telemetry(
+                seq=3,
+                timestamp_tick=30,
+                snapshot_seq=0x01020304,
+                window_ticks=25_000_000,
+                overflow_mask=0x81,
+                fan_install_mask=0x5A,
+                edge_counts=edge_counts,
+            )
+        )
+        self.assertEqual(frame.frame_type, FrameType.FAN_TELEMETRY)
+        self.assertEqual(frame.seq, 3)
+        self.assertEqual(len(frame.payload), 28)
+        self.assertEqual(
+            frame.payload,
+            b"\x04\x03\x02\x01\x40\x78\x7D\x01\x81\x5A\x00\x00"
+            b"\x01\x00\x02\x00\x03\x00\x04\x00"
+            b"\x05\x00\x06\x00\x07\x00\xFF\xFF",
+        )
+        telemetry = decode_fan_telemetry(frame)
+        self.assertEqual(telemetry.snapshot_seq, 0x01020304)
+        self.assertEqual(telemetry.window_ticks, 25_000_000)
+        self.assertEqual(telemetry.overflow_mask, 0x81)
+        self.assertEqual(telemetry.fan_install_mask, 0x5A)
+        self.assertEqual(telemetry.edge_counts, edge_counts)
+        self.assertEqual(telemetry.rpm, tuple(edges * 30 for edges in edge_counts))
+        self.assertFalse(telemetry.calibrated)
+        self.assertEqual(telemetry.calibration_status, "uncalibrated")
+
+        with self.assertRaisesRegex(ValueError, "eight edge counts"):
+            encode_fan_telemetry(
+                seq=4,
+                timestamp_tick=31,
+                snapshot_seq=2,
+                window_ticks=10,
+                overflow_mask=0,
+                fan_install_mask=0,
+                edge_counts=(1, 2),
+            )
+
+    def test_stream_resync_skips_noise_and_bad_crc_and_keeps_partial_magic(self) -> None:
+        first = encode_ready(
+            seq=1,
+            timestamp_tick=0,
+            build_id=1,
+            variant=0,
+            startup_reason=0,
+            startup_seq=1,
+            capability_flags=0,
+        )
+        bad = bytearray(encode_status(seq=2, timestamp_tick=1, status=StatusCode.OK))
+        bad[-1] ^= 1
+        last = encode_fan_telemetry(
+            seq=3,
+            timestamp_tick=2,
+            snapshot_seq=1,
+            window_ticks=25_000_000,
+            overflow_mask=0,
+            fan_install_mask=0xFF,
+            edge_counts=(1, 2, 3, 4, 5, 6, 7, 8),
+        )
+
+        frames, remainder = decode_stream(b"noise" + first + bytes(bad) + b"junk" + last + b"\xA5")
+
+        self.assertEqual([frame.frame_type for frame in frames], [FrameType.READY, FrameType.FAN_TELEMETRY])
+        self.assertEqual(remainder, b"\xA5")
+
+    def test_complete_frame_whose_crc_ends_in_partial_magic_has_no_remainder(self) -> None:
+        request = build_host_command(seq=222, command=CommandId.GET_FAN_TELEMETRY)
+        self.assertEqual(request[-1], 0xA5, "fixture must preserve the observed board-campaign CRC boundary")
+
+        frames, remainder = decode_stream(request)
+
+        self.assertEqual(len(frames), 1)
+        self.assertEqual(frames[0].seq, 222)
+        self.assertEqual(remainder, b"")
+
+    def test_two_millisecond_timeout_state_is_pure_and_boundary_exact(self) -> None:
+        idle = CommandTimeoutState()
+        pending = start_timeout(idle, request_seq=12, now_us=1_000)
+
+        self.assertEqual(idle.phase, TimeoutPhase.IDLE)
+        self.assertEqual(pending.phase, TimeoutPhase.PENDING)
+        self.assertEqual(pending.deadline_us, 3_000)
+        self.assertIs(poll_timeout(pending, now_us=2_999), pending)
+
+        timed_out = poll_timeout(pending, now_us=3_000)
+        self.assertEqual(timed_out.phase, TimeoutPhase.TIMED_OUT)
+        self.assertEqual(timed_out.request_seq, 12)
+
+        acked = observe_ack(pending, request_seq=12, now_us=2_500)
+        self.assertEqual(acked.phase, TimeoutPhase.ACKED)
+        self.assertIs(observe_ack(pending, request_seq=13, now_us=2_500), pending)
+        self.assertEqual(observe_ack(pending, request_seq=12, now_us=3_000).phase, TimeoutPhase.TIMED_OUT)
+
+    def test_rpm_conversion_is_explicitly_uncalibrated(self) -> None:
+        estimate = rpm_from_edges(7)
+
+        self.assertEqual(estimate.rpm, 210)
+        self.assertEqual(estimate.window_edges, 7)
+        self.assertFalse(estimate.calibrated)
+        self.assertEqual(estimate.calibration_status, "uncalibrated")
+        with self.assertRaisesRegex(ValueError, "edges"):
+            rpm_from_edges(-1)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 183 - 0
tests/unit/test_prod2u_p4_qualification.py

@@ -0,0 +1,183 @@
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+import sys
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def load_cli():
+    tools = ROOT / "tools"
+    sys.path.insert(0, str(tools))
+    path = tools / "prod2u_p4_cli.py"
+    spec = importlib.util.spec_from_file_location("prod2u_p4_qualification_test", path)
+    module = importlib.util.module_from_spec(spec)
+    assert spec.loader is not None
+    sys.modules[spec.name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def write_json(path: Path, payload: dict) -> None:
+    path.write_text(json.dumps(payload), encoding="utf-8")
+
+
+def artifact(path: Path) -> dict:
+    path.write_bytes(path.name.encode("ascii"))
+    return {"path": str(path), "sha256": __import__("hashlib").sha256(path.read_bytes()).hexdigest()}
+
+
+def qualification_fixture(root: Path) -> tuple[dict, dict, dict]:
+    normal_source = artifact(root / "normal-source-manifest.json")
+    trace_source = artifact(root / "trace-source-manifest.json")
+    normal_td = artifact(root / "normal-td.json")
+    trace_td = artifact(root / "trace-td.json")
+    write_json(
+        root / "manifest.json",
+        {
+            "schema": "prod2u-p4-package-manifest-v1",
+            "status": "pass",
+            "profile": "prod2u-fan-tach-binary921-v2",
+            "profile_id": 4,
+            "variants": {
+                "normal": {
+                    "bitstream": {"sha256": "a" * 64},
+                    "td_receipt": {"sha256": normal_td["sha256"]},
+                    "source_manifest": {"build_id": "11111111", "sha256": "b" * 64},
+                },
+                "trace": {
+                    "bitstream": {"sha256": "c" * 64},
+                    "td_receipt": {"sha256": trace_td["sha256"]},
+                    "source_manifest": {"build_id": "22222222", "sha256": "d" * 64},
+                },
+            },
+        },
+    )
+    write_json(root / "sha256-inventory.json", {"schema": "prod2u-p4-package-sha256-inventory-v1", "inventory": []})
+    (root / "protocol-junit.xml").write_text(
+        '<testsuites tests="4" failures="0" errors="0" skipped="0"><testsuite tests="4" failures="0" errors="0"/></testsuites>',
+        encoding="utf-8",
+    )
+    write_json(
+        root / "rtl-sim.json",
+        {
+            "status": "pass",
+            "verification_layer": "rtl_sim_compat",
+            "tests": [
+                {"name": name, "status": "pass"}
+                for name in (
+                    "prod2u_p4_host_rx_tb",
+                    "prod2u_p4_tx_scheduler_tb",
+                    "prod2u_fan_tach_capture8_tb",
+                    "prod2u_fan_pwm_bank_tb",
+                    "prod2u_fan_tach_binary921_v2_core_tb",
+                )
+            ],
+        },
+    )
+    write_json(
+        root / "formal.json",
+        {
+            "status": "pass",
+            "verification_layer": "formal",
+            "targets": [{"name": "prod2u_fan_data_path", "status": "pass", "returncode": 0}],
+        },
+    )
+    write_json(root / "static.json", {"status": "pass", "verification_layer": "static"})
+    preflights = {
+        "normal": {
+            "status": "pass",
+            "identity": {
+                "source_manifest": normal_source["path"],
+                "source_manifest_artifact_sha256": normal_source["sha256"],
+                "source_manifest_sha256": "b" * 64,
+                "td_receipt": normal_td["path"],
+                "td_receipt_artifact_sha256": normal_td["sha256"],
+            },
+        },
+        "trace": {
+            "status": "pass",
+            "identity": {
+                "source_manifest": trace_source["path"],
+                "source_manifest_artifact_sha256": trace_source["sha256"],
+                "source_manifest_sha256": "d" * 64,
+                "td_receipt": trace_td["path"],
+                "td_receipt_artifact_sha256": trace_td["sha256"],
+            },
+        },
+    }
+    inventory = {
+        "status": "pass",
+        "inventory": str(root / "sha256-inventory.json"),
+        "inventory_sha256": __import__("hashlib").sha256((root / "sha256-inventory.json").read_bytes()).hexdigest(),
+        "failures": [],
+    }
+    selftest = {"status": "pass", "failures": []}
+    return preflights, inventory, selftest
+
+
+def test_static_qualification_requires_all_seven_bound_layers(tmp_path: Path):
+    cli = load_cli()
+    preflights, inventory, selftest = qualification_fixture(tmp_path)
+
+    result = cli.build_static_qualification(
+        package_root=tmp_path,
+        variant_preflights=preflights,
+        package_inventory=inventory,
+        package_selftest=selftest,
+    )
+
+    assert result["status"] == "pass", result["failures"]
+    assert set(result["layers"]) == {
+        "source",
+        "protocol",
+        "rtl",
+        "formal",
+        "td_normal",
+        "td_trace",
+        "package",
+    }
+    assert all(layer["status"] == "pass" for layer in result["layers"].values())
+    assert result["layers"]["package"]["artifacts"]["package_inventory"]["sha256"] == inventory["inventory_sha256"]
+
+
+def test_static_qualification_rejects_failed_protocol_junit(tmp_path: Path):
+    cli = load_cli()
+    preflights, inventory, selftest = qualification_fixture(tmp_path)
+    (tmp_path / "protocol-junit.xml").write_text(
+        '<testsuites tests="4" failures="1" errors="0"><testsuite tests="4" failures="1" errors="0"/></testsuites>',
+        encoding="utf-8",
+    )
+
+    result = cli.build_static_qualification(
+        package_root=tmp_path,
+        variant_preflights=preflights,
+        package_inventory=inventory,
+        package_selftest=selftest,
+    )
+
+    assert result["status"] == "fail"
+    assert result["layers"]["protocol"]["status"] == "fail"
+    assert "protocol_junit_not_clean" in result["failures"]
+
+
+def test_static_qualification_requires_profile4_formal_target(tmp_path: Path):
+    cli = load_cli()
+    preflights, inventory, selftest = qualification_fixture(tmp_path)
+    write_json(
+        tmp_path / "formal.json",
+        {"status": "pass", "verification_layer": "formal", "targets": []},
+    )
+
+    result = cli.build_static_qualification(
+        package_root=tmp_path,
+        variant_preflights=preflights,
+        package_inventory=inventory,
+        package_selftest=selftest,
+    )
+
+    assert result["status"] == "fail"
+    assert "formal_required_target_missing:prod2u_fan_data_path" in result["failures"]

+ 325 - 0
tests/unit/test_prod2u_p4_validate_contract.py

@@ -0,0 +1,325 @@
+import importlib.util
+import json
+from pathlib import Path
+import sys
+
+import jsonschema
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+SETTINGS = (0, 20, 40, 60, 80, 100)
+REQUIRED_LAYERS = (
+    "program_sram",
+    "fresh_ready",
+    "host_ack",
+    "pwm_state",
+    "fan3_tach_trend",
+    "timeout_fallback",
+    "disable",
+    "ptc_command_path",
+)
+REQUIRED_STATIC_LAYERS = (
+    "source",
+    "protocol",
+    "rtl",
+    "formal",
+    "td_normal",
+    "td_trace",
+    "package",
+)
+
+
+def load_validator():
+    path = ROOT / "tools" / "prod2u_p4_validate.py"
+    spec = importlib.util.spec_from_file_location("prod2u_p4_validate_contract_test", path)
+    module = importlib.util.module_from_spec(spec)
+    assert spec.loader is not None
+    sys.modules[spec.name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def identity():
+    return {
+        "dut_id": "DUT-P4-01",
+        "build_id": "A1B2C3D4",
+        "bitstream_sha256": "a" * 64,
+        "variant": "trace",
+        "profile": "prod2u-fan-tach-binary921-v2",
+        "source_manifest_sha256": "b" * 64,
+    }
+
+
+def binding():
+    artifacts = {
+        "programmer_receipt": {"path": "programmer.json", "sha256": "c" * 64, "status": "pass"},
+        "pre_program_raw": {"path": "pre.raw", "sha256": "d" * 64},
+        "combined_rx_raw": {"path": "rx.raw", "sha256": "e" * 64},
+        "raw_transcript": {"path": "wire.json", "sha256": "f" * 64},
+        "td_receipt": {"path": "td.json", "sha256": "1" * 64},
+        "source_manifest": {"path": "source.json", "sha256": "b" * 64},
+        "package_manifest": {"path": "manifest.json", "sha256": "2" * 64},
+        "package_inventory": {"path": "inventory.json", "sha256": "3" * 64},
+    }
+    return {**artifacts, "identity": identity()}
+
+
+def valid_evidence():
+    rpm_by_setting = {0: 9000, 20: 100, 40: 200, 60: 300, 80: 400, 100: 500}
+    raw_samples = []
+    windows = []
+    snapshot_seq = 100
+    window_index = 0
+    for setting in SETTINGS:
+        for _ in range(2):
+            windows.append(
+                {
+                    "index": window_index,
+                    "start_s": float(window_index),
+                    "end_s": float(window_index + 1),
+                    "continuous": True,
+                    "snapshot_seq": snapshot_seq,
+                    "overflow_mask": 0,
+                }
+            )
+            snapshot_seq += 1
+            window_index += 1
+        for sample_index in range(5):
+            windows.append(
+                {
+                    "index": window_index,
+                    "start_s": float(window_index),
+                    "end_s": float(window_index + 1),
+                    "continuous": True,
+                    "snapshot_seq": snapshot_seq,
+                    "overflow_mask": 0,
+                }
+            )
+            raw_samples.append(
+                {
+                    "fan_setting_percent": setting,
+                    "snapshot_seq": snapshot_seq,
+                    "overflow_mask": 0,
+                    "FG5": {
+                        "window_edges": 0 if setting == 100 or (setting == 80 and sample_index == 4) else 1,
+                        "rpm": rpm_by_setting[setting],
+                    },
+                    "FG6": {"window_edges": 0, "rpm": 0},
+                }
+            )
+            snapshot_seq += 1
+            window_index += 1
+    return {
+        "schema": "prod2u-p4-evidence-v2",
+        "evidence_id": "P4-20260712-01-R01",
+        "campaign_id": "P4-20260712-01",
+        "campaign_identity": {**identity(), "planned_rounds": 10},
+        "round": 1,
+        "identity": identity(),
+        "bmc": {"status": "out_of_scope", "reason": "offline"},
+        "layers": {"required": {name: "pass" for name in REQUIRED_LAYERS}, "optional": {}},
+        "fan": {"FAN3": {"FG5": "detected", "FG6": "absent"}},
+        "windows": windows,
+        "raw_samples": raw_samples,
+        "correlation": {
+            "samples": [
+                {"fan_setting_percent": setting, "rpm": rpm_by_setting[setting]}
+                for setting in SETTINGS
+            ],
+            "spearman_rho": 1.0,
+            "low_mean_rpm": 150.0,
+            "high_mean_rpm": 450.0,
+            "high_significantly_higher": True,
+        },
+        "rpm": {"status": "not_qualified", "reason": "trend only"},
+        "ptc": {"actuation": True, "measurement": "not_run"},
+        "evidence_binding": binding(),
+    }
+
+
+def validate(document):
+    return load_validator().validate_evidence(document)
+
+
+def test_valid_contract_excludes_zero_from_correlation_and_accepts_either_high_setting_detection():
+    result = validate(valid_evidence())
+
+    assert result["status"] == "pass", result["failures"]
+
+
+@pytest.mark.parametrize("setting", SETTINGS)
+def test_raw_samples_require_five_retained_samples_for_each_setting(setting):
+    document = valid_evidence()
+    document["raw_samples"] = [
+        row for index, row in enumerate(document["raw_samples"])
+        if not (row["fan_setting_percent"] == setting and index == SETTINGS.index(setting) * 5)
+    ]
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert f"raw_samples_setting_count:1:{setting}:4" in result["failures"]
+
+
+@pytest.mark.parametrize("replacement", [100, 102])
+def test_snapshot_sequence_rejects_duplicate_or_gap(replacement):
+    document = valid_evidence()
+    document["raw_samples"][1]["snapshot_seq"] = replacement
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert "snapshot_seq_not_contiguous:1" in result["failures"]
+
+
+def test_retained_sample_sequence_allows_the_two_deliberate_settle_windows_between_settings():
+    result = validate(valid_evidence())
+
+    assert result["status"] == "pass", result["failures"]
+
+
+def test_detected_channel_rejects_its_overflow_bit():
+    document = valid_evidence()
+    document["raw_samples"][0]["overflow_mask"] = 1 << 4
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert "detected_channel_overflow:1:FG5" in result["failures"]
+
+
+def test_declared_detection_must_match_high_setting_samples():
+    document = valid_evidence()
+    document["fan"]["FAN3"]["FG5"] = "intermittent"
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert "fan_status_mismatch:1:FAN3:FG5:detected" in result["failures"]
+
+
+def test_at_least_one_fan3_signal_must_be_detected():
+    document = valid_evidence()
+    for row in document["raw_samples"]:
+        row["FG5"]["window_edges"] = 0
+    document["fan"]["FAN3"] = {"FG5": "absent", "FG6": "absent"}
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert "fan3_signal_not_detected:1" in result["failures"]
+
+
+def test_other_high_setting_patterns_are_intermittent():
+    document = valid_evidence()
+    for row in document["raw_samples"]:
+        setting = row["fan_setting_percent"]
+        sample_index = (row["snapshot_seq"] - 100) % 5
+        row["FG5"]["window_edges"] = 1 if setting == 80 and sample_index < 3 else 0
+        row["FG6"]["window_edges"] = 1 if setting == 100 and sample_index < 4 else 0
+    document["fan"]["FAN3"] = {"FG5": "intermittent", "FG6": "detected"}
+
+    result = validate(document)
+
+    assert result["status"] == "pass", result["failures"]
+
+
+@pytest.mark.parametrize("replacement", [4, 6])
+def test_window_sequence_rejects_duplicate_or_gap(replacement):
+    document = valid_evidence()
+    document["windows"][5]["index"] = replacement
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert "window_index_not_contiguous:1" in result["failures"]
+
+
+def test_window_sequence_must_start_at_zero():
+    document = valid_evidence()
+    for window in document["windows"]:
+        window["index"] += 1
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert "window_index_not_contiguous:1" in result["failures"]
+
+
+def test_window_snapshot_sequence_rejects_a_real_gap():
+    document = valid_evidence()
+    document["windows"][10]["snapshot_seq"] += 1
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert "window_snapshot_seq_not_contiguous:1" in result["failures"]
+
+
+@pytest.mark.parametrize("layer", REQUIRED_LAYERS)
+def test_all_dynamic_layers_are_required(layer):
+    document = valid_evidence()
+    del document["layers"]["required"][layer]
+
+    result = validate(document)
+
+    assert result["status"] == "fail"
+    assert f"required_layer_missing:1:{layer}" in result["failures"]
+
+
+@pytest.mark.parametrize(
+    "schema_name",
+    [
+        "prod2u_p4_evidence.schema.json",
+        "prod2u_p4_campaign.schema.json",
+        "prod2u_p4_final_gate.schema.json",
+    ],
+)
+def test_schemas_require_explicit_dynamic_layer_names(schema_name):
+    schema = json.loads((ROOT / "schemas" / schema_name).read_text(encoding="utf-8"))
+    jsonschema.Draft202012Validator.check_schema(schema)
+    layer_schema = schema["$defs"]["layers"]["properties"]["required"]
+
+    assert set(layer_schema["required"]) == set(REQUIRED_LAYERS)
+    assert set(layer_schema["properties"]) == set(REQUIRED_LAYERS)
+
+
+def test_evidence_schema_requires_raw_sample_contract():
+    schema = json.loads((ROOT / "schemas" / "prod2u_p4_evidence.schema.json").read_text(encoding="utf-8"))
+    jsonschema.Draft202012Validator.check_schema(schema)
+
+    assert "raw_samples" in schema["required"]
+    assert schema["properties"]["raw_samples"] == {"$ref": "#/$defs/rawSamples"}
+    raw_samples = schema["$defs"]["rawSamples"]
+    assert raw_samples["minItems"] == 30
+    assert raw_samples["maxItems"] == 30
+
+
+def test_evidence_schema_requires_at_least_one_detected_fan3_signal():
+    schema = json.loads((ROOT / "schemas" / "prod2u_p4_evidence.schema.json").read_text(encoding="utf-8"))
+    document = valid_evidence()
+    document["fan"]["FAN3"] = {"FG5": "absent", "FG6": "absent"}
+
+    with pytest.raises(jsonschema.ValidationError):
+        jsonschema.validate(document, schema)
+
+
+def test_campaign_and_final_gate_schemas_require_static_qualification():
+    for schema_name in ("prod2u_p4_campaign.schema.json", "prod2u_p4_final_gate.schema.json"):
+        schema = json.loads((ROOT / "schemas" / schema_name).read_text(encoding="utf-8"))
+        jsonschema.Draft202012Validator.check_schema(schema)
+
+        assert "qualification" in schema["required"]
+        assert schema["properties"]["qualification"] == {"$ref": "#/$defs/staticQualification"}
+        static_layers = schema["$defs"]["staticQualification"]["properties"]["layers"]
+        assert set(static_layers["required"]) == set(REQUIRED_STATIC_LAYERS)
+
+
+def test_static_qualification_schema_locks_all_required_layers():
+    schema = json.loads((ROOT / "schemas" / "prod2u_p4_qualification.schema.json").read_text(encoding="utf-8"))
+    jsonschema.Draft202012Validator.check_schema(schema)
+
+    assert schema["$id"] == "prod2u-p4-static-qualification-v1"
+    layers = schema["properties"]["layers"]
+    assert set(layers["required"]) == set(REQUIRED_STATIC_LAYERS)

+ 345 - 0
tests/unit/test_prod2u_programmer_process_audit.py

@@ -0,0 +1,345 @@
+#!/usr/bin/env python3
+"""Focused TDD coverage for Prod2U PROGRAM_SRAM process auditing."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import subprocess
+import unittest
+from pathlib import Path
+
+import jsonschema
+
+
+ROOT = Path(__file__).resolve().parents[2]
+MODULE_PATH = ROOT / "tools" / "prod2u_programmer.py"
+SCHEMA_PATH = ROOT / "schemas" / "prod2u_program_sram_receipt.schema.json"
+TD_ROOT = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412")
+
+
+def load_module():
+    spec = importlib.util.spec_from_file_location("prod2u_programmer_process_audit", MODULE_PATH)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load Prod2U programmer")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def identity(
+    pid: int,
+    name: str,
+    *,
+    path: str | None = None,
+    user: str = r"WORKSTATION\operator",
+    session_id: int = 7,
+    parent_pid: int = 9001,
+    command_line: str | None = None,
+) -> dict[str, object]:
+    executable = path or str(TD_ROOT / "bin" / name)
+    return {
+        "pid": pid,
+        "name": name,
+        "path": executable,
+        "user": user,
+        "session_id": session_id,
+        "parent_pid": parent_pid,
+        "command_line": command_line or f'"{executable}" --interactive',
+        "start_time": "2026-07-12T01:02:03.0000000Z",
+        "exe_sha256": f"{pid:064x}",
+    }
+
+
+def ownership_policy(process: dict[str, object]) -> dict[str, object]:
+    return {
+        "owner": process["user"],
+        "session_id": process["session_id"],
+        "parent_pid": process["parent_pid"],
+        "approved_binaries": [
+            {
+                "name": process["name"],
+                "path": process["path"],
+                "exe_sha256": process["exe_sha256"],
+            }
+        ],
+        "command_line": process["command_line"],
+    }
+
+
+class FakeProcessAdapter:
+    def __init__(
+        self,
+        discovered: list[dict[str, object]],
+        *,
+        survivors: set[int] | None = None,
+        final: list[dict[str, object]] | None = None,
+    ) -> None:
+        self.discovered = discovered
+        self.survivors = set(survivors or set())
+        self.final = [] if final is None else final
+        self.events: list[tuple[str, int]] = []
+        self.discovery_count = 0
+
+    def discover(self) -> list[dict[str, object]]:
+        self.discovery_count += 1
+        return self.discovered if self.discovery_count == 1 else self.final
+
+    def request_close(self, process: dict[str, object]) -> None:
+        self.events.append(("close", int(process["pid"])))
+
+    def is_running(self, process: dict[str, object]) -> bool:
+        self.events.append(("probe", int(process["pid"])))
+        return int(process["pid"]) in self.survivors
+
+    def force_stop(self, process: dict[str, object]) -> None:
+        self.events.append(("force", int(process["pid"])))
+
+
+class Prod2UProgrammerProcessAuditTests(unittest.TestCase):
+    def setUp(self) -> None:
+        self.module = load_module()
+
+    def test_discovers_every_td_bitwriter_and_hardware_service_name(self) -> None:
+        self.assertEqual(
+            self.module.TD_PROCESS_EXECUTABLES,
+            (
+                "td.exe",
+                "td_commands_prompt.exe",
+                "bw.exe",
+                "bw_commands_prompt.exe",
+                "hwserver.exe",
+            ),
+        )
+
+    def test_unrelated_td_session_is_a_blocker_and_is_never_terminated(self) -> None:
+        blocker = identity(101, "td.exe", parent_pid=42)
+        owned = identity(
+            104,
+            "bw_commands_prompt.exe",
+            command_line=f'"{TD_ROOT / "bin" / "bw_commands_prompt.exe"}" C:/run/program-sram.tcl',
+        )
+        adapter = FakeProcessAdapter([blocker, owned], survivors={104})
+        sleeps: list[float] = []
+
+        result = self.module.close_td_processes(
+            TD_ROOT,
+            ownership_policy=ownership_policy(owned),
+            process_adapter=adapter,
+            sleeper=sleeps.append,
+        )
+
+        self.assertEqual(result["status"], "fail", result)
+        self.assertTrue(result["identity_audit_completed_before_action"])
+        self.assertEqual(result["discovered_processes"], [blocker, owned])
+        self.assertEqual(result["harness_owned_processes"], [owned])
+        self.assertEqual(result["blocking_processes"], [blocker])
+        self.assertEqual(result["graceful_close_requested"], [])
+        self.assertEqual(result["forced_terminated"], [])
+        self.assertEqual(result["remaining"], [blocker, owned])
+        self.assertEqual(result["wait_seconds"], 5.0)
+        self.assertEqual(sleeps, [])
+        self.assertEqual(adapter.events, [])
+        self.assertIn("blocking_td_processes_present", result["errors"])
+
+    def test_exact_harness_owned_process_can_be_closed_and_forced(self) -> None:
+        owned = identity(
+            104,
+            "bw_commands_prompt.exe",
+            command_line=f'"{TD_ROOT / "bin" / "bw_commands_prompt.exe"}" C:/run/program-sram.tcl',
+        )
+        adapter = FakeProcessAdapter([owned], survivors={104})
+        sleeps: list[float] = []
+
+        result = self.module.close_td_processes(
+            TD_ROOT,
+            ownership_policy=ownership_policy(owned),
+            process_adapter=adapter,
+            sleeper=sleeps.append,
+        )
+
+        self.assertEqual(result["status"], "pass", result)
+        self.assertEqual(result["harness_owned_processes"], [owned])
+        self.assertEqual(result["blocking_processes"], [])
+        self.assertEqual(adapter.events, [("close", 104), ("probe", 104), ("force", 104)])
+        self.assertEqual(sleeps, [5.0])
+
+    def test_unreadable_identity_fails_before_any_close_or_wait(self) -> None:
+        incomplete = identity(201, "td.exe")
+        incomplete["user"] = None
+        adapter = FakeProcessAdapter([incomplete], survivors={201})
+        sleeps: list[float] = []
+
+        result = self.module.close_td_processes(
+            TD_ROOT,
+            ownership_policy=ownership_policy(identity(201, "td.exe")),
+            process_adapter=adapter,
+            sleeper=sleeps.append,
+        )
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("identity_unreadable:201:user", result["errors"])
+        self.assertEqual(adapter.events, [])
+        self.assertEqual(sleeps, [])
+        self.assertFalse(result["identity_audit_completed_before_action"])
+
+    def test_unknown_executable_path_fails_before_any_close_or_wait(self) -> None:
+        outside = identity(301, "hwserver.exe", path=r"D:\OtherVendor\hwserver.exe")
+        adapter = FakeProcessAdapter([outside], survivors={301})
+        sleeps: list[float] = []
+
+        result = self.module.close_td_processes(
+            TD_ROOT,
+            ownership_policy=ownership_policy(identity(301, "hwserver.exe")),
+            process_adapter=adapter,
+            sleeper=sleeps.append,
+        )
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("unknown_process_path:301", result["errors"])
+        self.assertEqual(adapter.events, [])
+        self.assertEqual(sleeps, [])
+
+    def test_executable_basename_must_match_reported_process_name(self) -> None:
+        mismatched = identity(
+            302,
+            "td.exe",
+            path=str(TD_ROOT / "bin" / "bw.exe"),
+        )
+        adapter = FakeProcessAdapter([mismatched], survivors={302})
+
+        result = self.module.close_td_processes(
+            TD_ROOT,
+            ownership_policy=ownership_policy(identity(302, "td.exe")),
+            process_adapter=adapter,
+            sleeper=lambda _seconds: None,
+        )
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("process_name_path_mismatch:302", result["errors"])
+        self.assertEqual(adapter.events, [])
+
+    def test_windows_action_script_does_not_assign_read_only_pid_variable(self) -> None:
+        calls: list[list[str]] = []
+
+        def fake_runner(command, **_kwargs):
+            calls.append(command)
+            return subprocess.CompletedProcess(
+                command,
+                0,
+                stdout='{"status":"not_running","running":false}',
+                stderr="",
+            )
+
+        adapter = self.module.WindowsTdProcessAdapter(runner=fake_runner)
+        adapter.request_close(identity(303, "td.exe"))
+
+        script = calls[0][3]
+        self.assertNotIn("$pid =", script)
+        self.assertIn("Get-Process -Id $pidValue", script)
+        for field in ("OWNER", "SESSION", "PARENT", "COMMAND_LINE", "SHA256"):
+            self.assertIn(f"PROD2U_PROCESS_{field}", script)
+
+    def test_post_action_residual_audit_never_controls_processes(self) -> None:
+        residual = identity(501, "hwserver.exe", parent_pid=42)
+        adapter = FakeProcessAdapter([residual])
+
+        result = self.module.audit_td_processes(
+            TD_ROOT,
+            ownership_policy=ownership_policy(identity(502, "bw_commands_prompt.exe")),
+            process_adapter=adapter,
+        )
+
+        self.assertEqual(result["status"], "fail")
+        self.assertTrue(result["post_action_audit_completed"])
+        self.assertEqual(result["residual_processes"], [residual])
+        self.assertEqual(adapter.events, [])
+
+    def test_post_action_unreadable_identity_marks_audit_incomplete(self) -> None:
+        unreadable = identity(503, "hwserver.exe")
+        unreadable["command_line"] = None
+        adapter = FakeProcessAdapter([unreadable])
+
+        result = self.module.audit_td_processes(
+            TD_ROOT,
+            ownership_policy=ownership_policy(identity(504, "bw_commands_prompt.exe")),
+            process_adapter=adapter,
+        )
+
+        self.assertEqual(result["status"], "fail")
+        self.assertFalse(result["post_action_audit_completed"])
+        self.assertIn("identity_unreadable:503:command_line", result["post_action_errors"])
+        self.assertEqual(adapter.events, [])
+
+    def test_process_cleanup_schema_requires_complete_identity_audit(self) -> None:
+        schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
+        cleanup_schema = {
+            "$schema": schema["$schema"],
+            "$defs": schema["$defs"],
+            **schema["properties"]["process_cleanup"],
+        }
+        valid = {
+            "status": "pass",
+            "td_root": str(TD_ROOT),
+            "identity_audit_completed_before_action": True,
+            "ownership_policy": ownership_policy(identity(401, "bw_commands_prompt.exe")),
+            "discovered_processes": [],
+            "harness_owned_processes": [],
+            "blocking_processes": [],
+            "graceful_close_requested": [],
+            "forced_terminated": [],
+            "wait_seconds": 5.0,
+            "remaining": [],
+            "post_action_audit_completed": True,
+            "post_action_discovered_processes": [],
+            "post_action_harness_owned_processes": [],
+            "post_action_blocking_processes": [],
+            "residual_processes": [],
+            "post_action_errors": [],
+            "errors": [],
+        }
+
+        jsonschema.validate(valid, cleanup_schema)
+        required_cleanup_fields = (
+            "identity_audit_completed_before_action",
+            "ownership_policy",
+            "discovered_processes",
+            "harness_owned_processes",
+            "blocking_processes",
+            "errors",
+            "post_action_audit_completed",
+            "post_action_discovered_processes",
+            "post_action_harness_owned_processes",
+            "post_action_blocking_processes",
+            "residual_processes",
+            "post_action_errors",
+        )
+        for missing in required_cleanup_fields:
+            with self.subTest(missing=missing):
+                invalid = json.loads(json.dumps(valid))
+                del invalid[missing]
+                with self.assertRaises(jsonschema.ValidationError):
+                    jsonschema.validate(invalid, cleanup_schema)
+
+        process_valid = json.loads(json.dumps(valid))
+        process_valid["discovered_processes"] = [identity(402, "bw.exe")]
+        for missing in (
+            "pid",
+            "name",
+            "path",
+            "user",
+            "session_id",
+            "parent_pid",
+            "command_line",
+            "start_time",
+            "exe_sha256",
+        ):
+            with self.subTest(process_identity_missing=missing):
+                invalid = json.loads(json.dumps(process_valid))
+                del invalid["discovered_processes"][0][missing]
+                with self.assertRaises(jsonschema.ValidationError):
+                    jsonschema.validate(invalid, cleanup_schema)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 106 - 28
tests/unit/test_prod2u_programmer_runtime.py

@@ -5,6 +5,7 @@ from __future__ import annotations
 
 
 import hashlib
 import hashlib
 import importlib.util
 import importlib.util
+import inspect
 import json
 import json
 import copy
 import copy
 import subprocess
 import subprocess
@@ -50,21 +51,6 @@ class FakeMutex:
 
 
 
 
 class Prod2UProgrammerRuntimeTests(unittest.TestCase):
 class Prod2UProgrammerRuntimeTests(unittest.TestCase):
-    def test_cleanup_targets_stale_bitwriter_cli_but_not_td_cli_or_hwserver(self) -> None:
-        source = MODULE_PATH.read_text(encoding="utf-8")
-
-        self.assertIn("'bw_commands_prompt'", source)
-        allowed_line = next(line for line in source.splitlines() if "$allowed = @(" in line)
-        self.assertNotIn("td_commands_prompt", allowed_line)
-        self.assertNotIn("hwserver", allowed_line)
-
-    def test_cleanup_td_root_match_requires_a_path_component_boundary(self) -> None:
-        source = MODULE_PATH.read_text(encoding="utf-8")
-
-        self.assertIn("$rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar", source)
-        self.assertIn(".StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)", source)
-        self.assertNotIn(".StartsWith($root, [System.StringComparison]::OrdinalIgnoreCase)", source)
-
     def setUp(self) -> None:
     def setUp(self) -> None:
         self.module = load_module()
         self.module = load_module()
         self.build_id = uuid.uuid4().hex[:8].upper()
         self.build_id = uuid.uuid4().hex[:8].upper()
@@ -107,15 +93,53 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
         )
         )
 
 
     def cleanup_result(self) -> dict:
     def cleanup_result(self) -> dict:
+        policy = {
+            "owner": r"WORKSTATION\operator",
+            "session_id": 7,
+            "parent_pid": 9001,
+            "approved_binaries": [
+                {
+                    "name": "bw_commands_prompt.exe",
+                    "path": str(self.bw_exe),
+                    "exe_sha256": hashlib.sha256(self.bw_exe.read_bytes()).hexdigest(),
+                }
+            ],
+            "command_line": f'"{self.bw_exe}" program-sram.tcl',
+        }
         return {
         return {
             "td_root": str(self.td_root_path),
             "td_root": str(self.td_root_path),
-            "graceful_close_requested": ["bw.exe:101"],
+            "identity_audit_completed_before_action": True,
+            "ownership_policy": policy,
+            "discovered_processes": [],
+            "harness_owned_processes": [],
+            "blocking_processes": [],
+            "graceful_close_requested": [],
             "forced_terminated": [],
             "forced_terminated": [],
             "wait_seconds": 5.0,
             "wait_seconds": 5.0,
             "remaining": [],
             "remaining": [],
+            "post_action_audit_completed": False,
+            "post_action_discovered_processes": [],
+            "post_action_harness_owned_processes": [],
+            "post_action_blocking_processes": [],
+            "residual_processes": [],
+            "post_action_errors": [],
+            "errors": [],
             "status": "pass",
             "status": "pass",
         }
         }
 
 
+    def residual_result(self, *, status: str = "pass") -> dict:
+        errors = [] if status == "pass" else ["post_action_td_processes_remaining"]
+        residuals = [] if status == "pass" else [{"pid": 999}]
+        return {
+            "status": status,
+            "post_action_audit_completed": True,
+            "post_action_discovered_processes": residuals,
+            "post_action_harness_owned_processes": residuals,
+            "post_action_blocking_processes": [],
+            "residual_processes": residuals,
+            "post_action_errors": errors,
+        }
+
     def test_runner_stages_hashes_executes_once_and_parses_only_new_log_bytes(self) -> None:
     def test_runner_stages_hashes_executes_once_and_parses_only_new_log_bytes(self) -> None:
         old_log = self.log_dir / "bw_existing.log"
         old_log = self.log_dir / "bw_existing.log"
         old_log.write_text("PRG-8002 ERROR stale historical failure\n", encoding="utf-8")
         old_log.write_text("PRG-8002 ERROR stale historical failure\n", encoding="utf-8")
@@ -137,7 +161,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
             td_root=self.td_root_path,
             td_root=self.td_root_path,
             run_id="runtime-pass",
             run_id="runtime-pass",
             process_runner=fake_runner,
             process_runner=fake_runner,
-            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+            residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
             mutex_factory=lambda: FakeMutex(),
             mutex_factory=lambda: FakeMutex(),
         )
         )
 
 
@@ -190,7 +215,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
             td_root=self.td_root_path,
             td_root=self.td_root_path,
             run_id="runtime-no-delta",
             run_id="runtime-no-delta",
             process_runner=lambda command, **kwargs: subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr=""),
             process_runner=lambda command, **kwargs: subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr=""),
-            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+            residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
             mutex_factory=lambda: FakeMutex(),
             mutex_factory=lambda: FakeMutex(),
         )
         )
 
 
@@ -198,6 +224,33 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
         self.assertIn("missing_bitwriter_log_delta", receipt["parser"]["failures"])
         self.assertIn("missing_bitwriter_log_delta", receipt["parser"]["failures"])
         self.assertFalse(receipt["parser"]["ordered_markers_complete"])
         self.assertFalse(receipt["parser"]["ordered_markers_complete"])
 
 
+    def test_post_action_residual_audit_is_required_and_fails_receipt_without_retry(self) -> None:
+        calls: list[str] = []
+
+        def fake_runner(command, **_kwargs):
+            calls.append("program")
+            (self.log_dir / "bw_residual.log").write_text(self.success_log(), encoding="utf-8")
+            return subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr="")
+
+        receipt = self.module.execute_program_sram(
+            source_bitstream=self.source_bit,
+            expected_bitstream_sha256=self.expected_sha256,
+            build_id=self.build_id,
+            output_dir=self.output_dir / "residual",
+            td_root=self.td_root_path,
+            run_id="runtime-residual",
+            process_runner=fake_runner,
+            cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+            residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(status="fail"),
+            mutex_factory=lambda: FakeMutex(),
+        )
+
+        self.assertEqual(calls, ["program"])
+        self.assertEqual(receipt["status"], "fail")
+        self.assertIn("post_action_process_audit_failed", receipt["parser"]["failures"])
+        self.assertTrue(receipt["process_cleanup"]["post_action_audit_completed"])
+        self.assertEqual(receipt["process_cleanup"]["post_action_errors"], ["post_action_td_processes_remaining"])
+
     def test_real_cli_stdout_mirror_and_connect_setup_are_accepted(self) -> None:
     def test_real_cli_stdout_mirror_and_connect_setup_are_accepted(self) -> None:
         cli_log = self.cli_success_log()
         cli_log = self.cli_success_log()
 
 
@@ -213,7 +266,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
             td_root=self.td_root_path,
             td_root=self.td_root_path,
             run_id="runtime-cli-pass",
             run_id="runtime-cli-pass",
             process_runner=fake_runner,
             process_runner=fake_runner,
-            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+            residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
             mutex_factory=lambda: FakeMutex(),
             mutex_factory=lambda: FakeMutex(),
         )
         )
 
 
@@ -234,7 +288,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                 stdout='couldn\'t read file "C:broken\\program-sram.tcl": no such file or directory\nbw > ',
                 stdout='couldn\'t read file "C:broken\\program-sram.tcl": no such file or directory\nbw > ',
                 stderr="",
                 stderr="",
             ),
             ),
-            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+            residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
             mutex_factory=lambda: FakeMutex(),
             mutex_factory=lambda: FakeMutex(),
         )
         )
 
 
@@ -261,7 +316,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                     td_root=self.td_root_path,
                     td_root=self.td_root_path,
                     run_id=f"runtime-{name}",
                     run_id=f"runtime-{name}",
                     process_runner=fake_runner,
                     process_runner=fake_runner,
-                    cleanup_runner=lambda _td_root: self.cleanup_result(),
+                    cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+                    residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
                     mutex_factory=lambda: FakeMutex(),
                     mutex_factory=lambda: FakeMutex(),
                 )
                 )
                 self.assertNotEqual(receipt["status"], "pass")
                 self.assertNotEqual(receipt["status"], "pass")
@@ -301,7 +357,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                     td_root=self.td_root_path,
                     td_root=self.td_root_path,
                     run_id=f"runtime-{name}",
                     run_id=f"runtime-{name}",
                     process_runner=fake_runner,
                     process_runner=fake_runner,
-                    cleanup_runner=lambda _td_root: self.cleanup_result(),
+                    cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+                    residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
                     mutex_factory=lambda: FakeMutex(),
                     mutex_factory=lambda: FakeMutex(),
                 )
                 )
                 self.assertNotEqual(receipt["status"], "pass")
                 self.assertNotEqual(receipt["status"], "pass")
@@ -333,7 +390,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                         td_root=self.td_root_path,
                         td_root=self.td_root_path,
                         run_id=f"runtime-marker-{marker_name}-{stream_name}",
                         run_id=f"runtime-marker-{marker_name}-{stream_name}",
                         process_runner=fake_runner,
                         process_runner=fake_runner,
-                        cleanup_runner=lambda _td_root: self.cleanup_result(),
+                        cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+                        residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
                         mutex_factory=lambda: FakeMutex(),
                         mutex_factory=lambda: FakeMutex(),
                     )
                     )
 
 
@@ -360,7 +418,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
             td_root=self.td_root_path,
             td_root=self.td_root_path,
             run_id="runtime-replaced",
             run_id="runtime-replaced",
             process_runner=fake_runner,
             process_runner=fake_runner,
-            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+            residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
             mutex_factory=lambda: FakeMutex(),
             mutex_factory=lambda: FakeMutex(),
         )
         )
 
 
@@ -406,6 +465,18 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                 "Job Object did not terminate the spawned child process",
                 "Job Object did not terminate the spawned child process",
             )
             )
 
 
+    def test_windows_job_runner_assigns_suspended_process_before_resume(self) -> None:
+        source = inspect.getsource(self.module.run_process_in_job)
+
+        create_index = source.index("if not kernel32.CreateProcessW(")
+        suspended_index = source.index("CREATE_SUSPENDED")
+        assign_index = source.index("if not kernel32.AssignProcessToJobObject(job")
+        resume_index = source.index("if kernel32.ResumeThread(")
+        self.assertLess(suspended_index, create_index)
+        self.assertLess(create_index, assign_index)
+        self.assertLess(assign_index, resume_index)
+        self.assertNotIn("subprocess.Popen(", source)
+
     def test_td_process_cleanup_accepts_a_normal_absolute_windows_path(self) -> None:
     def test_td_process_cleanup_accepts_a_normal_absolute_windows_path(self) -> None:
         if sys.platform != "win32":
         if sys.platform != "win32":
             self.skipTest("Windows PowerShell process cleanup coverage")
             self.skipTest("Windows PowerShell process cleanup coverage")
@@ -413,7 +484,11 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
             td_root = Path(tmp) / "TD"
             td_root = Path(tmp) / "TD"
             td_root.mkdir()
             td_root.mkdir()
 
 
-            result = self.module.close_td_processes(td_root)
+            policy = self.module.build_process_ownership_policy(
+                executable=self.bw_exe,
+                command=[str(self.bw_exe), "C:/run/program-sram.tcl"],
+            )
+            result = self.module.close_td_processes(td_root, ownership_policy=policy)
 
 
         self.assertEqual(result["status"], "pass", result)
         self.assertEqual(result["status"], "pass", result)
         self.assertEqual(Path(result["td_root"]), td_root.resolve())
         self.assertEqual(Path(result["td_root"]), td_root.resolve())
@@ -435,7 +510,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                 td_root=self.td_root_path,
                 td_root=self.td_root_path,
                 run_id="runtime-hash",
                 run_id="runtime-hash",
                 process_runner=fake_runner,
                 process_runner=fake_runner,
-                cleanup_runner=lambda _td_root: self.cleanup_result(),
+                cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+                residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
                 mutex_factory=lambda: FakeMutex(),
                 mutex_factory=lambda: FakeMutex(),
             )
             )
         self.assertEqual(calls, [])
         self.assertEqual(calls, [])
@@ -452,7 +528,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                 td_root=self.td_root_path,
                 td_root=self.td_root_path,
                 run_id="runtime-reused",
                 run_id="runtime-reused",
                 process_runner=fake_runner,
                 process_runner=fake_runner,
-                cleanup_runner=lambda _td_root: self.cleanup_result(),
+                cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+                residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
                 mutex_factory=lambda: FakeMutex(),
                 mutex_factory=lambda: FakeMutex(),
             )
             )
         self.assertEqual(calls, [])
         self.assertEqual(calls, [])
@@ -466,7 +543,8 @@ class Prod2UProgrammerRuntimeTests(unittest.TestCase):
                 td_root=self.td_root_path,
                 td_root=self.td_root_path,
                 run_id="runtime-mutex",
                 run_id="runtime-mutex",
                 process_runner=fake_runner,
                 process_runner=fake_runner,
-                cleanup_runner=lambda _td_root: self.cleanup_result(),
+                cleanup_runner=lambda _td_root, **_kwargs: self.cleanup_result(),
+                residual_audit_runner=lambda _td_root, **_kwargs: self.residual_result(),
                 mutex_factory=lambda: FakeMutex(acquired=False),
                 mutex_factory=lambda: FakeMutex(acquired=False),
             )
             )
         self.assertEqual(calls, [])
         self.assertEqual(calls, [])

+ 317 - 0
tests/unit/test_prod2u_validator.py

@@ -768,5 +768,322 @@ class Prod2UValidatorTests(unittest.TestCase):
                 self.assertTrue(evidence["blockers"])
                 self.assertTrue(evidence["blockers"])
 
 
 
 
+class TestProd2UP4Validator(unittest.TestCase):
+    @staticmethod
+    def qualification_fixture() -> dict:
+        def layer(status: str, **artifacts: dict) -> dict:
+            return {"status": status, "artifacts": artifacts}
+
+        return {
+            "schema": "prod2u-p4-static-qualification-v1",
+            "status": "pass",
+            "profile": "prod2u-fan-tach-binary921-v2",
+            "profile_id": 4,
+            "layers": {
+                "source": layer(
+                    "pass",
+                    normal_source_manifest={"path": "normal-source.json", "sha256": "b" * 64},
+                    trace_source_manifest={"path": "trace-source.json", "sha256": "b" * 64},
+                ),
+                "protocol": layer("pass", protocol_junit={"path": "protocol.xml", "sha256": "4" * 64}),
+                "rtl": layer("pass", rtl_sim_receipt={"path": "rtl.json", "sha256": "5" * 64}),
+                "formal": layer("pass", formal_receipt={"path": "formal.json", "sha256": "6" * 64}),
+                "td_normal": layer("pass", normal_td_receipt={"path": "normal-td.json", "sha256": "1" * 64}),
+                "td_trace": layer("pass", trace_td_receipt={"path": "trace-td.json", "sha256": "1" * 64}),
+                "package": layer(
+                    "pass",
+                    package_manifest={"path": "manifest.json", "sha256": "2" * 64},
+                    package_inventory={"path": "inventory.json", "sha256": "3" * 64},
+                    static_receipt={"path": "static.json", "sha256": "7" * 64},
+                ),
+            },
+            "variants": {},
+            "failures": [],
+        }
+
+    @staticmethod
+    def round_fixture(round_number: int, *, identity: dict | None = None) -> dict:
+        identity = identity or {
+            "dut_id": "DUT-P4-01",
+            "build_id": "P4BUILD01",
+            "bitstream_sha256": "a" * 64,
+            "profile": "prod2u-p4",
+        }
+        variant = "trace" if round_number <= 5 else "normal"
+        identity = {
+            **identity,
+            "variant": variant,
+            "source_manifest_sha256": identity.get("source_manifest_sha256", "b" * 64),
+        }
+        rpm_by_setting = {0: 1200, 20: 1400, 40: 1600, 60: 1900, 80: 2200, 100: 2400}
+        windows = []
+        raw_samples = []
+        snapshot_seq = 100
+        window_index = 0
+        for setting in (0, 20, 40, 60, 80, 100):
+            for _ in range(2):
+                windows.append(
+                    {
+                        "index": window_index,
+                        "start_s": window_index,
+                        "end_s": window_index + 1,
+                        "continuous": True,
+                        "snapshot_seq": snapshot_seq,
+                        "overflow_mask": 0,
+                    }
+                )
+                snapshot_seq += 1
+                window_index += 1
+            for sample_index in range(5):
+                windows.append(
+                    {
+                        "index": window_index,
+                        "start_s": window_index,
+                        "end_s": window_index + 1,
+                        "continuous": True,
+                        "snapshot_seq": snapshot_seq,
+                        "overflow_mask": 0,
+                    }
+                )
+                raw_samples.append(
+                    {
+                        "fan_setting_percent": setting,
+                        "snapshot_seq": snapshot_seq,
+                        "overflow_mask": 0,
+                        "FG5": {
+                            "window_edges": 1 if setting in (80, 100) else 0,
+                            "rpm": rpm_by_setting[setting],
+                        },
+                        "FG6": {
+                            "window_edges": 1 if setting == 80 and sample_index == 0 else 0,
+                            "rpm": rpm_by_setting[setting] if setting == 80 and sample_index == 0 else 0,
+                        },
+                    }
+                )
+                snapshot_seq += 1
+                window_index += 1
+        return {
+            "round": round_number,
+            "identity": identity,
+            "layers": {
+                "required": {
+                    name: "pass"
+                    for name in (
+                        "program_sram",
+                        "fresh_ready",
+                        "host_ack",
+                        "pwm_state",
+                        "fan3_tach_trend",
+                        "timeout_fallback",
+                        "disable",
+                        "ptc_command_path",
+                    )
+                },
+                "optional": {
+                    "rtl_replay": "not_run",
+                    "td_elaboration": "not_run",
+                    "uart_strict_receipt": "not_run",
+                },
+            },
+            "fan": {
+                "FAN3": {
+                    "FG5": "detected",
+                    "FG6": "intermittent",
+                }
+            },
+            "windows": windows,
+            "raw_samples": raw_samples,
+            "correlation": {
+                "samples": [
+                    {"fan_setting_percent": setting, "rpm": rpm}
+                    for setting, rpm in ((0, 1200), (20, 1400), (40, 1600), (60, 1900), (80, 2200), (100, 2400))
+                ],
+                "spearman_rho": 1.0,
+                "low_mean_rpm": 1500,
+                "high_mean_rpm": 2300,
+                "high_significantly_higher": True,
+            },
+            "rpm": {"status": "not_qualified", "reason": "FG input is not a qualified RPM measurement"},
+            "ptc": {"actuation": True, "measurement": "not_run"},
+            "evidence_binding": {
+                "programmer_receipt": {
+                    "path": "round/programmer/program-sram-receipt.json",
+                    "sha256": "c" * 64,
+                    "status": "pass",
+                },
+                "pre_program_raw": {"path": "round/pre-program.raw", "sha256": "d" * 64},
+                "combined_rx_raw": {"path": "round/combined-rx.raw", "sha256": "e" * 64},
+                "raw_transcript": {"path": "round/wire-transcript.json", "sha256": "f" * 64},
+                "td_receipt": {"path": f"{variant}-td.json", "sha256": "1" * 64},
+                "source_manifest": {"path": f"{variant}-source-manifest.json", "sha256": identity["source_manifest_sha256"]},
+                "package_manifest": {"path": "manifest.json", "sha256": "2" * 64},
+                "package_inventory": {"path": "sha256-inventory.json", "sha256": "3" * 64},
+                "identity": dict(identity),
+            },
+        }
+
+    @classmethod
+    def campaign_fixture(cls) -> dict:
+        identity = {
+            "dut_id": "DUT-P4-01",
+            "build_id": "P4BUILD01",
+            "bitstream_sha256": "a" * 64,
+            "profile": "prod2u-p4",
+        }
+        return {
+            "schema": "prod2u-p4-campaign-v2",
+            "campaign_id": "P4-20260712-01",
+            "campaign_identity": {**identity, "planned_rounds": 10},
+            "bmc": {"status": "out_of_scope", "reason": "BMC capture is not part of P4 offline evidence"},
+            "qualification": cls.qualification_fixture(),
+            "rounds": [cls.round_fixture(index, identity=identity) for index in range(1, 11)],
+            "evidence_bindings": [
+                {"round": index, "evidence_binding": cls.round_fixture(index, identity=identity)["evidence_binding"]}
+                for index in range(1, 11)
+            ],
+        }
+
+    def test_valid_ten_round_campaign_is_accepted_and_bmc_is_out_of_scope(self) -> None:
+        validator = load_p4_validator()
+
+        result = validator.validate_campaign(self.campaign_fixture())
+
+        self.assertEqual(result["status"], "pass", result["failures"])
+        self.assertEqual(result["campaign_id"], "P4-20260712-01")
+        self.assertEqual(result["round_count"], 10)
+        self.assertEqual(result["bmc"], "out_of_scope")
+
+    def test_campaign_requires_all_static_qualification_layers(self) -> None:
+        validator = load_p4_validator()
+        fixture = self.campaign_fixture()
+        del fixture["qualification"]["layers"]["formal"]
+
+        result = validator.validate_campaign(fixture)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("static_layer_missing:formal", result["failures"])
+
+    def test_campaign_rejects_static_and_dynamic_artifact_cross_binding_mismatch(self) -> None:
+        validator = load_p4_validator()
+        fixture = self.campaign_fixture()
+        fixture["qualification"]["layers"]["package"]["artifacts"]["package_inventory"]["sha256"] = "9" * 64
+
+        result = validator.validate_campaign(fixture)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("qualification_binding_mismatch:1:package_inventory", result["failures"])
+
+    def test_required_layers_must_pass_but_optional_layers_may_be_not_run(self) -> None:
+        validator = load_p4_validator()
+        fixture = self.campaign_fixture()
+        fixture["rounds"][0]["layers"]["required"]["program_sram"] = "not_run"
+
+        result = validator.validate_campaign(fixture)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("required_layer_not_pass:1:program_sram", result["failures"])
+
+    def test_campaign_requires_contiguous_rounds_and_identical_identity(self) -> None:
+        validator = load_p4_validator()
+        fixture = self.campaign_fixture()
+        fixture["rounds"][4]["round"] = 6
+        fixture["rounds"][5]["identity"]["build_id"] = "OTHERBUILD"
+
+        result = validator.validate_campaign(fixture)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("round_sequence_not_1_to_10", result["failures"])
+        self.assertIn("identity_mismatch:6:build_id", result["failures"])
+
+    def test_fan_statuses_window_continuity_and_ptc_rpm_boundaries_are_checked(self) -> None:
+        validator = load_p4_validator()
+        fixture = self.campaign_fixture()
+        fixture["rounds"][0]["fan"]["FAN3"]["FG5"] = "unknown"
+        fixture["rounds"][1]["windows"][2]["start_s"] = 99
+        fixture["rounds"][2]["rpm"]["status"] = "qualified"
+        fixture["rounds"][3]["ptc"]["measurement"] = "pass"
+
+        result = validator.validate_campaign(fixture)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("invalid_fan_status:1:FAN3:FG5", result["failures"])
+        self.assertIn("window_not_continuous:2", result["failures"])
+        self.assertIn("rpm_not_qualified:3", result["failures"])
+        self.assertIn("ptc_measurement_must_be_not_run:4", result["failures"])
+
+    def test_correlation_requires_spearman_threshold_and_high_setting_margin(self) -> None:
+        validator = load_p4_validator()
+        fixture = self.campaign_fixture()
+        fixture["rounds"][0]["correlation"]["spearman_rho"] = 0.59
+        fixture["rounds"][1]["correlation"]["high_mean_rpm"] = 1300
+
+        result = validator.validate_campaign(fixture)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("spearman_declared_mismatch:1", result["failures"])
+        self.assertIn("high_setting_mean_mismatch:2", result["failures"])
+
+    def test_direct_evidence_requires_identity_fields_and_checks_computed_spearman(self) -> None:
+        validator = load_p4_validator()
+        round_data = self.round_fixture(1)
+        evidence = {
+            "schema": "prod2u-p4-evidence-v2",
+            "evidence_id": "P4-20260712-01-R01",
+            "campaign_id": "P4-20260712-01",
+            "campaign_identity": {**round_data["identity"], "planned_rounds": 10},
+            "bmc": {"status": "out_of_scope", "reason": "offline"},
+            **round_data,
+        }
+        evidence["correlation"]["samples"] = [
+            {"fan_setting_percent": setting, "rpm": rpm}
+            for setting, rpm in ((20, 1000), (40, 1500), (60, 2100), (80, 2800))
+        ]
+        evidence["correlation"]["spearman_rho"] = 1.0
+        del evidence["campaign_id"]
+
+        result = validator.validate_evidence(evidence)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("missing_required:evidence:campaign_id", result["failures"])
+
+    def test_final_gate_rejects_missing_status_even_when_layers_are_valid(self) -> None:
+        validator = load_p4_validator()
+        gate = {
+            "schema": "prod2u-p4-final-gate-v2",
+            "campaign_id": "P4-20260712-01",
+            "bmc": {"status": "out_of_scope", "reason": "offline"},
+            "layers": {"required": {"software_model": "pass"}, "optional": {}},
+            "round_count": 10,
+            "failures": [],
+        }
+
+        result = validator.validate_final_gate(gate)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("missing_required:final_gate:status", result["failures"])
+
+    def test_schema_files_describe_the_three_v2_documents(self) -> None:
+        for name, schema_id in (
+            ("prod2u_p4_evidence.schema.json", "prod2u-p4-evidence-v2"),
+            ("prod2u_p4_final_gate.schema.json", "prod2u-p4-final-gate-v2"),
+            ("prod2u_p4_campaign.schema.json", "prod2u-p4-campaign-v2"),
+        ):
+            with self.subTest(name=name):
+                schema = json.loads((ROOT / "schemas" / name).read_text(encoding="utf-8"))
+                self.assertEqual(schema["$id"], schema_id)
+
+
+def load_p4_validator():
+    validator_path = ROOT / "tools" / "prod2u_p4_validate.py"
+    if not validator_path.is_file():
+        raise AssertionError(f"missing v2 validator: {validator_path}")
+    spec = importlib.util.spec_from_file_location("prod2u_p4_validate_test", validator_path)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load Prod2U P4 validator")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     unittest.main()
     unittest.main()

+ 11 - 1
tests/unit/test_uart_receipts.py

@@ -471,6 +471,8 @@ class UartReceiptsTests(unittest.TestCase):
                     "mode": "PROGRAM_SRAM",
                     "mode": "PROGRAM_SRAM",
                     "operator": "manual",
                     "operator": "manual",
                     "programmed_at": "2026-07-01T00:00:00Z",
                     "programmed_at": "2026-07-01T00:00:00Z",
+                    "jtag_speed_hz": 200000,
+                    "board_power_present_before_program": True,
                     "bitstream_sha256": compute_file_hash(bitstream),
                     "bitstream_sha256": compute_file_hash(bitstream),
                     "td_receipt_sha256": compute_file_hash(td_receipt),
                     "td_receipt_sha256": compute_file_hash(td_receipt),
                 }
                 }
@@ -605,7 +607,13 @@ class UartReceiptsTests(unittest.TestCase):
                 "debug_rx_ball": "P10",
                 "debug_rx_ball": "P10",
                 "debug_tx_ball": "R10",
                 "debug_tx_ball": "R10",
             },
             },
-            "programming": {"mode": "PROGRAM_SRAM", "manual_programming": True, "bitstream": {"path": str(bitstream), "sha256": compute_file_hash(bitstream)}},
+            "programming": {
+                "mode": "PROGRAM_SRAM",
+                "manual_programming": True,
+                "jtag_speed_hz": 200000,
+                "board_power_present_before_program": True,
+                "bitstream": {"path": str(bitstream), "sha256": compute_file_hash(bitstream)},
+            },
             "collector": {
             "collector": {
                 "host_port": "COM8",
                 "host_port": "COM8",
                 "debug_port": "COM7",
                 "debug_port": "COM7",
@@ -630,6 +638,8 @@ class UartReceiptsTests(unittest.TestCase):
                     "mode": "PROGRAM_SRAM",
                     "mode": "PROGRAM_SRAM",
                     "manual_programming": True,
                     "manual_programming": True,
                     "programmed_at": "2026-07-01T00:00:00Z",
                     "programmed_at": "2026-07-01T00:00:00Z",
+                    "jtag_speed_hz": 200000,
+                    "board_power_present_before_program": True,
                     "attestation": {"path": str(sram_attestation), "sha256": compute_file_hash(sram_attestation)},
                     "attestation": {"path": str(sram_attestation), "sha256": compute_file_hash(sram_attestation)},
                 },
                 },
                 "host_command_sequence": {"status": "pass", "commands": commands},
                 "host_command_sequence": {"status": "pass", "commands": commands},

+ 460 - 0
tools/package_prod2u_p4.ps1

@@ -0,0 +1,460 @@
+param(
+    [Parameter(Mandatory = $true)][string]$OutputDir,
+    [Parameter(Mandatory = $true)][string]$NormalBitstream,
+    [Parameter(Mandatory = $true)][string]$TraceBitstream,
+    [Parameter(Mandatory = $true)][string]$NormalTdReceipt,
+    [Parameter(Mandatory = $true)][string]$TraceTdReceipt,
+    [Parameter(Mandatory = $true)][string]$NormalSourceManifest,
+    [Parameter(Mandatory = $true)][string]$TraceSourceManifest,
+    [Parameter(Mandatory = $true)][string]$ProtocolJUnit,
+    [Parameter(Mandatory = $true)][string]$RtlSimReceipt,
+    [Parameter(Mandatory = $true)][string]$FormalReceipt,
+    [Parameter(Mandatory = $true)][string]$StaticReceipt
+)
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = "Stop"
+$env:PYTHONDONTWRITEBYTECODE = "1"
+
+$repo = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
+$profile = "prod2u-fan-tach-binary921-v2"
+$profileId = 4
+
+function Get-Sha256([string]$Path) {
+    return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
+}
+
+function Assert-RequiredFile([string]$Path, [string]$Label) {
+    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
+        throw "$Label is missing: $Path"
+    }
+}
+
+function Read-Json([string]$Path, [string]$Label) {
+    Assert-RequiredFile $Path $Label
+    try {
+        return Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json
+    } catch {
+        throw "$Label is not valid JSON: $Path"
+    }
+}
+
+function Assert-Hex([string]$Value, [int]$Length, [string]$Label) {
+    if ($Value -notmatch ("^[0-9A-Fa-f]{{{0}}}$" -f $Length)) {
+        throw "$Label is invalid"
+    }
+}
+
+function Copy-Required([string]$Source, [string]$Destination) {
+    Assert-RequiredFile $Source "Required package source"
+    $parent = Split-Path -Parent $Destination
+    if ($parent) {
+        New-Item -ItemType Directory -Force -Path $parent | Out-Null
+    }
+    Copy-Item -LiteralPath $Source -Destination $Destination -Force
+}
+
+function Resolve-Python3 {
+    $venvPython = Join-Path $repo ".codex\venv\Scripts\python.exe"
+    if (Test-Path -LiteralPath $venvPython -PathType Leaf) {
+        return [ordered]@{ exe = $venvPython; prefix = @() }
+    }
+    $python = Get-Command python.exe -ErrorAction SilentlyContinue
+    if ($python) {
+        return [ordered]@{ exe = $python.Source; prefix = @() }
+    }
+    $py = Get-Command py.exe -ErrorAction SilentlyContinue
+    if ($py) {
+        return [ordered]@{ exe = $py.Source; prefix = @("-3") }
+    }
+    throw "Python 3 is required for Profile 4 source-manifest and package selftests"
+}
+
+function Invoke-Python([object]$Python, [string[]]$Arguments, [string]$Label) {
+    $output = & $Python.exe @($Python.prefix) -B @Arguments 2>&1
+    if ($LASTEXITCODE -ne 0) {
+        throw "$Label failed: $($output -join [Environment]::NewLine)"
+    }
+    return ($output -join [Environment]::NewLine)
+}
+
+function Assert-SourceManifest([string]$Path, [string]$Variant, [object]$Python) {
+    $source = Read-Json $Path "$Variant source manifest"
+    if ($source.schema -ne "prod2u-source-manifest-v1") { throw "$Variant source manifest schema mismatch" }
+    if ($source.profile -ne $profile) { throw "$Variant source manifest profile mismatch" }
+    $buildId = ([string]$source.build_id).ToUpperInvariant()
+    $sourceHash = ([string]$source.source_manifest_sha256).ToLowerInvariant()
+    Assert-Hex $buildId 8 "$Variant build_id"
+    Assert-Hex $sourceHash 64 "$Variant source_manifest_sha256"
+    if ($buildId -ne $sourceHash.Substring(0, 8).ToUpperInvariant()) {
+        throw "$Variant build_id does not match source manifest hash prefix"
+    }
+    $validator = @'
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, sys.argv[3])
+from prod2u_build_identity import validate_source_manifest
+
+payload = json.loads(Path(sys.argv[1]).read_text(encoding='utf-8-sig'))
+result = validate_source_manifest(payload, root=Path(sys.argv[2]))
+print(json.dumps(result, sort_keys=True))
+raise SystemExit(0 if result['status'] == 'pass' else 1)
+'@
+    Invoke-Python $Python @("-c", $validator, $Path, $repo, (Join-Path $repo "tools")) "$Variant source manifest validation" | Out-Null
+    return [ordered]@{ build_id = $buildId; source_manifest_sha256 = $sourceHash }
+}
+
+function Assert-P4TdReceiptSchema([string]$Path) {
+    $schema = Read-Json $Path "Profile 4 TD receipt schema"
+    if ($schema.'$id' -ne "prod2u-p4-td-build-receipt-v1") { throw "Profile 4 TD receipt schema ID mismatch" }
+    if ($schema.properties.schema.const -ne "prod2u-td-build-receipt-v1") { throw "Profile 4 TD receipt schema contract mismatch" }
+    if ($null -eq $schema.oneOf -or $schema.oneOf.Count -ne 2) { throw "Profile 4 TD receipt schema variants are invalid" }
+}
+
+function Assert-TdReceipt(
+    [string]$Path,
+    [string]$Bitstream,
+    [string]$Variant,
+    [object]$Identity
+) {
+    $receipt = Read-Json $Path "$Variant TD receipt"
+    $expectedTop = "prod2u_fan_tach_binary921_v2_$Variant"
+    if ($receipt.schema -ne "prod2u-td-build-receipt-v1") { throw "$Variant TD receipt schema mismatch" }
+    if ($receipt.status -ne "pass") { throw "$Variant TD receipt status is not pass" }
+    if ($receipt.top -ne $expectedTop) { throw "$Variant TD receipt top mismatch" }
+    if ($receipt.top_module -ne ($expectedTop + "_top")) { throw "$Variant TD receipt top module mismatch" }
+    if ($receipt.pin_profile -ne $profile) { throw "$Variant TD receipt pin profile mismatch" }
+    if (([string]$receipt.build_id).ToUpperInvariant() -ne $Identity.build_id) { throw "$Variant TD receipt build_id mismatch" }
+    if (([string]$receipt.source_manifest_sha256).ToLowerInvariant() -ne $Identity.source_manifest_sha256) { throw "$Variant TD receipt source manifest hash mismatch" }
+    if ($null -eq $receipt.build_identity -or $receipt.build_identity.status -ne "pass") { throw "$Variant TD receipt build identity is not pass" }
+    if (([string]$receipt.build_identity.build_id).ToUpperInvariant() -ne $Identity.build_id) { throw "$Variant TD receipt build identity build_id mismatch" }
+    if (([string]$receipt.build_identity.source_manifest_sha256).ToLowerInvariant() -ne $Identity.source_manifest_sha256) { throw "$Variant TD receipt build identity source manifest hash mismatch" }
+    if ($null -eq $receipt.bitstream) { throw "$Variant TD receipt bitstream is missing" }
+    foreach ($required in @("resources", "timing", "timing_gate", "syn", "phy")) {
+        if ($null -eq $receipt.$required) { throw "$Variant TD receipt is missing $required" }
+    }
+    if ($receipt.timing_gate.status -ne "pass") { throw "$Variant TD receipt timing gate is not pass" }
+    if ([int]$receipt.syn.returncode -ne 0 -or [bool]$receipt.syn.log_has_error) { throw "$Variant TD receipt synthesis result is not clean" }
+    if ([int]$receipt.phy.returncode -ne 0 -or [bool]$receipt.phy.log_has_error) { throw "$Variant TD receipt physical result is not clean" }
+    $bitHash = Get-Sha256 $Bitstream
+    if (([string]$receipt.bitstream.sha256).ToLowerInvariant() -ne $bitHash) { throw "$Variant TD receipt bitstream hash mismatch" }
+    return [ordered]@{ sha256 = $bitHash; td_receipt_sha256 = Get-Sha256 $Path }
+}
+
+function Assert-ProtocolJUnit([string]$Path) {
+    Assert-RequiredFile $Path "Profile 4 protocol JUnit"
+    try {
+        [xml]$document = Get-Content -LiteralPath $Path -Raw -Encoding UTF8
+    } catch {
+        throw "Profile 4 protocol JUnit is invalid XML: $Path"
+    }
+    $suites = @($document.SelectNodes("//testsuite"))
+    if ($suites.Count -eq 0) { throw "Profile 4 protocol JUnit has no testsuite" }
+    $tests = 0
+    $failures = 0
+    $errors = 0
+    foreach ($suite in $suites) {
+        $tests += [int]$suite.tests
+        $failures += [int]$suite.failures
+        $errors += [int]$suite.errors
+    }
+    if ($tests -le 0 -or $failures -ne 0 -or $errors -ne 0) {
+        throw "Profile 4 protocol JUnit is not clean"
+    }
+    return [ordered]@{ tests = $tests; failures = $failures; errors = $errors; sha256 = Get-Sha256 $Path }
+}
+
+function Assert-RtlSimReceipt([string]$Path) {
+    $receipt = Read-Json $Path "Profile 4 RTL simulation receipt"
+    if ($receipt.status -ne "pass" -or $receipt.verification_layer -ne "rtl_sim_compat") {
+        throw "Profile 4 RTL simulation receipt is not pass"
+    }
+    $required = @(
+        "prod2u_p4_host_rx_tb",
+        "prod2u_p4_tx_scheduler_tb",
+        "prod2u_fan_tach_capture8_tb",
+        "prod2u_fan_pwm_bank_tb",
+        "prod2u_fan_tach_binary921_v2_core_tb"
+    )
+    foreach ($name in $required) {
+        $match = @($receipt.tests | Where-Object { $_.name -eq $name -and $_.status -eq "pass" })
+        if ($match.Count -ne 1) { throw "Profile 4 RTL required test is not pass: $name" }
+    }
+    return [ordered]@{ sha256 = Get-Sha256 $Path }
+}
+
+function Assert-FormalReceipt([string]$Path) {
+    $receipt = Read-Json $Path "Profile 4 formal receipt"
+    if ($receipt.status -ne "pass" -or $receipt.verification_layer -ne "formal") {
+        throw "Profile 4 formal receipt is not pass"
+    }
+    $target = @($receipt.targets | Where-Object {
+        $_.name -eq "prod2u_fan_data_path" -and $_.status -eq "pass" -and [int]$_.returncode -eq 0
+    })
+    if ($target.Count -ne 1) { throw "Profile 4 formal target is not pass: prod2u_fan_data_path" }
+    return [ordered]@{ sha256 = Get-Sha256 $Path }
+}
+
+function Assert-StaticReceipt([string]$Path) {
+    $receipt = Read-Json $Path "Profile 4 static receipt"
+    if ($receipt.status -ne "pass") { throw "Profile 4 static receipt is not pass" }
+    return [ordered]@{ sha256 = Get-Sha256 $Path }
+}
+
+function Invoke-Profile4SelfTest([string]$Root, [object]$Python, [string]$Label) {
+    $cli = Join-Path $Root "prod2u_p4_cli.py"
+    Assert-RequiredFile $cli "$Label Profile 4 CLI"
+    $output = Invoke-Python $Python @($cli, "selftest", "--package-root", $Root) "$Label Profile 4 selftest"
+    try {
+        $payload = $output | ConvertFrom-Json
+    } catch {
+        throw "$Label Profile 4 selftest did not return JSON"
+    }
+    if ($payload.status -ne "pass" -or $payload.profile -ne $profile -or [int]$payload.profile_id -ne $profileId -or
+        $payload.bmc_status -ne "out_of_scope" -or $payload.enumerated_com_ports -or $payload.dtr -or
+        $payload.rts -or $payload.flash_attempted -or $payload.hardware_opened -or $payload.program_sram_attempted) {
+        throw "$Label Profile 4 selftest contract mismatch"
+    }
+    return [ordered]@{ status = "pass"; output_sha256 = ([System.BitConverter]::ToString([System.Security.Cryptography.SHA256]::Create().ComputeHash([System.Text.Encoding]::UTF8.GetBytes($output))).Replace("-", "").ToLowerInvariant()) }
+}
+
+function Invoke-Profile4Bootstrap([string]$Root, [object]$Python, [string]$VenvDir, [string]$Label) {
+    $cli = Join-Path $Root "prod2u_p4_cli.py"
+    Assert-RequiredFile $cli "$Label Profile 4 CLI"
+    $output = Invoke-Python $Python @($cli, "bootstrap", "--package-root", $Root, "--venv-dir", $VenvDir) "$Label Profile 4 bootstrap"
+    try {
+        $payload = $output | ConvertFrom-Json
+    } catch {
+        throw "$Label Profile 4 bootstrap did not return JSON"
+    }
+    if ($payload.status -ne "pass" -or $payload.profile -ne $profile -or -not $payload.no_index -or
+        -not $payload.require_hashes -or $payload.hardware_opened) {
+        throw "$Label Profile 4 bootstrap contract mismatch"
+    }
+    $packagePath = [System.IO.Path]::GetFullPath($Root).TrimEnd('\')
+    $venvPath = [System.IO.Path]::GetFullPath([string]$payload.venv_dir)
+    if ($venvPath.StartsWith($packagePath + '\', [System.StringComparison]::OrdinalIgnoreCase) -or $venvPath -eq $packagePath) {
+        throw "$Label Profile 4 bootstrap placed its venv inside the immutable package"
+    }
+    return [ordered]@{ status = "pass"; output_sha256 = ([System.BitConverter]::ToString([System.Security.Cryptography.SHA256]::Create().ComputeHash([System.Text.Encoding]::UTF8.GetBytes($output))).Replace("-", "").ToLowerInvariant()) }
+}
+
+function Remove-PackageBytecode([string]$PackageRoot) {
+    Get-ChildItem -LiteralPath $PackageRoot -Recurse -File -Filter "*.pyc" | Where-Object {
+        $_.Directory.Name -eq "__pycache__"
+    } | ForEach-Object {
+        Remove-Item -LiteralPath $_.FullName -Force
+    }
+}
+
+# Validate every caller-provided asset before creating the output directory.
+Assert-RequiredFile $NormalBitstream "Normal bitstream"
+Assert-RequiredFile $TraceBitstream "Trace bitstream"
+Assert-RequiredFile $NormalTdReceipt "Normal TD receipt"
+Assert-RequiredFile $TraceTdReceipt "Trace TD receipt"
+Assert-RequiredFile $NormalSourceManifest "Normal source manifest"
+Assert-RequiredFile $TraceSourceManifest "Trace source manifest"
+Assert-RequiredFile $ProtocolJUnit "Profile 4 protocol JUnit"
+Assert-RequiredFile $RtlSimReceipt "Profile 4 RTL simulation receipt"
+Assert-RequiredFile $FormalReceipt "Profile 4 formal receipt"
+Assert-RequiredFile $StaticReceipt "Profile 4 static receipt"
+
+$python = Resolve-Python3
+$p4TdSchema = Join-Path $repo "schemas\prod2u_p4_td_build_receipt.schema.json"
+Assert-P4TdReceiptSchema $p4TdSchema
+$normalIdentity = Assert-SourceManifest $NormalSourceManifest "normal" $python
+$traceIdentity = Assert-SourceManifest $TraceSourceManifest "trace" $python
+if ($normalIdentity.build_id -eq $traceIdentity.build_id) { throw "Normal and trace build IDs must be independent" }
+$normalBuild = Assert-TdReceipt $NormalTdReceipt $NormalBitstream "normal" $normalIdentity
+$traceBuild = Assert-TdReceipt $TraceTdReceipt $TraceBitstream "trace" $traceIdentity
+$protocolQualification = Assert-ProtocolJUnit $ProtocolJUnit
+$rtlQualification = Assert-RtlSimReceipt $RtlSimReceipt
+$formalQualification = Assert-FormalReceipt $FormalReceipt
+$staticQualification = Assert-StaticReceipt $StaticReceipt
+
+$requirementsIn = Join-Path $repo "requirements\prod2u-p4-requirements.in"
+$requirementsLock = Join-Path $repo "requirements\prod2u-p4-requirements.lock"
+$wheel = Join-Path $repo "tools\changxin-temp-uart\dist\pyserial-3.5-py2.py3-none-any.whl"
+$image = Join-Path $repo "docs\images\prod2u-con77-con78-rs232-schematic.png"
+Assert-RequiredFile $requirementsIn "Profile 4 requirements input"
+Assert-RequiredFile $requirementsLock "Profile 4 hash-locked requirements"
+Assert-RequiredFile $wheel "Profile 4 wheelhouse wheel"
+Assert-RequiredFile $image "Profile 4 RS232 wiring screenshot"
+$wheelHash = Get-Sha256 $wheel
+if ((Get-Content -LiteralPath $requirementsLock -Raw -Encoding ASCII) -notmatch ("--hash=sha256:{0}" -f $wheelHash)) {
+    throw "Profile 4 requirements lock does not hash-lock the supplied wheel"
+}
+
+$profileTools = @(
+    "prod2u_p4_protocol.py",
+    "prod2u_p4_validate.py",
+    "prod2u_p4_cli.py",
+    "prod2u_p4_collector.py",
+    "prod2u_p4_campaign.py",
+    "prod2u_build_identity.py",
+    "prod2u_programmer.py",
+    "prod2u.ps1"
+)
+foreach ($name in $profileTools) {
+    Assert-RequiredFile (Join-Path $repo "tools\$name") "Profile 4 tool"
+}
+foreach ($name in @(
+    "prod2u_p4_evidence.schema.json",
+    "prod2u_p4_campaign.schema.json",
+    "prod2u_p4_final_gate.schema.json",
+    "prod2u_p4_td_build_receipt.schema.json",
+    "prod2u_p4_qualification.schema.json",
+    "prod2u_program_sram_receipt.schema.json"
+)) {
+    Assert-RequiredFile (Join-Path $repo "schemas\$name") "Profile 4 schema"
+}
+Assert-RequiredFile (Join-Path $repo "docs\prod2u-p4-start-here.zh-CN.md") "Profile 4 START-HERE"
+Assert-RequiredFile (Join-Path $repo "docs\prod2u-p4-program-sram-runbook.zh-CN.md") "Profile 4 PROGRAM_SRAM runbook"
+
+$outFull = [System.IO.Path]::GetFullPath($OutputDir)
+$timestamp = (Get-Date).ToUniversalTime().ToString("yyyyMMddTHHmmssZ")
+$packageName = "prod2u-p4-fantach-$timestamp"
+$finalPackage = Join-Path $outFull $packageName
+$finalZip = Join-Path $outFull ($packageName + ".zip")
+$finalSidecar = $finalZip + ".sha256.txt"
+foreach ($path in @($finalPackage, $finalZip, $finalSidecar)) {
+    if (Test-Path -LiteralPath $path) { throw "Atomic package destination already exists: $path" }
+}
+
+New-Item -ItemType Directory -Force -Path $outFull | Out-Null
+$nonce = [Guid]::NewGuid().ToString("N")
+$stage = Join-Path $outFull (".$packageName-stage-$nonce")
+$zipStage = Join-Path $outFull (".$packageName-archive-$nonce.zip")
+$sidecarStage = $zipStage + ".sha256.txt"
+New-Item -ItemType Directory -Path $stage | Out-Null
+
+Copy-Required $NormalBitstream (Join-Path $stage "normal.bit")
+Copy-Required $TraceBitstream (Join-Path $stage "trace.bit")
+Copy-Required $NormalTdReceipt (Join-Path $stage "normal-td.json")
+Copy-Required $TraceTdReceipt (Join-Path $stage "trace-td.json")
+Copy-Required $NormalSourceManifest (Join-Path $stage "normal-source-manifest.json")
+Copy-Required $TraceSourceManifest (Join-Path $stage "trace-source-manifest.json")
+Copy-Required $ProtocolJUnit (Join-Path $stage "protocol-junit.xml")
+Copy-Required $RtlSimReceipt (Join-Path $stage "rtl-sim.json")
+Copy-Required $FormalReceipt (Join-Path $stage "formal.json")
+Copy-Required $StaticReceipt (Join-Path $stage "static.json")
+foreach ($name in $profileTools) {
+    Copy-Required (Join-Path $repo "tools\$name") (Join-Path $stage $name)
+}
+Copy-Required $requirementsIn (Join-Path $stage "requirements.in")
+Copy-Required $requirementsLock (Join-Path $stage "requirements.lock")
+Copy-Required $wheel (Join-Path $stage "wheelhouse\pyserial-3.5-py2.py3-none-any.whl")
+foreach ($name in @(
+    "prod2u_p4_evidence.schema.json",
+    "prod2u_p4_campaign.schema.json",
+    "prod2u_p4_final_gate.schema.json",
+    "prod2u_p4_td_build_receipt.schema.json",
+    "prod2u_p4_qualification.schema.json",
+    "prod2u_program_sram_receipt.schema.json"
+)) {
+    Copy-Required (Join-Path $repo "schemas\$name") (Join-Path $stage "schemas\$name")
+}
+Copy-Required (Join-Path $repo "docs\prod2u-p4-program-sram-runbook.zh-CN.md") (Join-Path $stage "prod2u-p4-program-sram-runbook.zh-CN.md")
+Copy-Required (Join-Path $repo "docs\prod2u-p4-start-here.zh-CN.md") (Join-Path $stage "START-HERE.zh-CN.md")
+Copy-Required $image (Join-Path $stage "images\prod2u-con77-con78-rs232-schematic.png")
+
+$manifest = [ordered]@{
+    schema = "prod2u-p4-package-manifest-v1"
+    status = "pass"
+    package_name = $packageName
+    created_at_utc = (Get-Date).ToUniversalTime().ToString("o")
+    profile = $profile
+    profile_id = $profileId
+    protocol = "binary921-v2"
+    bmc = [ordered]@{ status = "out_of_scope"; reason = "Profile 4 fan-tach package has no BMC receipt or runtime requirement." }
+    variants = [ordered]@{
+        normal = [ordered]@{ bitstream = [ordered]@{ path = "normal.bit"; sha256 = $normalBuild.sha256 }; td_receipt = [ordered]@{ path = "normal-td.json"; sha256 = $normalBuild.td_receipt_sha256 }; source_manifest = [ordered]@{ path = "normal-source-manifest.json"; build_id = $normalIdentity.build_id; sha256 = $normalIdentity.source_manifest_sha256 } }
+        trace = [ordered]@{ bitstream = [ordered]@{ path = "trace.bit"; sha256 = $traceBuild.sha256 }; td_receipt = [ordered]@{ path = "trace-td.json"; sha256 = $traceBuild.td_receipt_sha256 }; source_manifest = [ordered]@{ path = "trace-source-manifest.json"; build_id = $traceIdentity.build_id; sha256 = $traceIdentity.source_manifest_sha256 } }
+    }
+    qualification_inputs = [ordered]@{
+        protocol_junit = [ordered]@{ path = "protocol-junit.xml"; sha256 = $protocolQualification.sha256; tests = $protocolQualification.tests }
+        rtl_sim = [ordered]@{ path = "rtl-sim.json"; sha256 = $rtlQualification.sha256 }
+        formal = [ordered]@{ path = "formal.json"; sha256 = $formalQualification.sha256 }
+        static = [ordered]@{ path = "static.json"; sha256 = $staticQualification.sha256 }
+    }
+    programming = [ordered]@{ operation = "PROGRAM_SRAM"; speed_hz = 200000; power_cycle_required = $false; automatic_retry = $false }
+    transport = [ordered]@{ connector = "CON78"; port = "COM5"; baud = 921600; external_level = "RS232"; board_tx_to_adapter_rx = 1; board_rx_to_adapter_tx = 2; ground = "3/4"; usb_ttl_forbidden = $true }
+    fan_tach = [ordered]@{
+        connector = "CON25"
+        fan = "FAN3"
+        pwm3 = "B1"
+        fg5 = "C1"
+        fg6 = "C2"
+        requested_percent_semantics = "fan_connector_high_duty_percent"
+        cpld_high_level_effect = "npn_on_connector_pwm_low"
+        cpld_high_duty_mapping = "100_minus_requested_percent"
+    }
+    campaign = [ordered]@{
+        round_count = 10
+        order = @(
+            [ordered]@{ variant = "trace"; rounds = "1-5" },
+            [ordered]@{ variant = "normal"; rounds = "6-10" }
+        )
+        final_variant = "normal"
+        fan3_percent_ladder = @(0, 20, 40, 60, 80, 100)
+        settle_windows_per_step = 2
+        retained_windows_per_step = 5
+        tach_window_seconds = 1
+        ptc_channels = @(1, 2, 3, 4, 5, 6)
+        ptc_percent = 10
+        ptc_hold_seconds = 2
+        timeout_fallback_required = $true
+        disable_required = $true
+    }
+    immutable_inventory_excludes = @("venv", "runtime", "evidence", "__pycache__", "*.pyc")
+}
+$manifest | ConvertTo-Json -Depth 32 | Set-Content -LiteralPath (Join-Path $stage "manifest.json") -Encoding UTF8
+
+$inventory = @()
+Get-ChildItem -LiteralPath $stage -Recurse -File | Sort-Object FullName | ForEach-Object {
+    $relative = $_.FullName.Substring($stage.Length).TrimStart('\').Replace('\', '/')
+    if ($relative -eq "sha256-inventory.json") { return }
+    if ($relative -match '(^|/)__pycache__/|\.pyc$|^(venv|runtime|evidence)/') { throw "Immutable package inventory contains forbidden runtime artifact: $relative" }
+    $inventory += [ordered]@{ path = $relative; size = $_.Length; sha256 = Get-Sha256 $_.FullName }
+}
+[ordered]@{
+    schema = "prod2u-p4-package-sha256-inventory-v1"
+    package_name = $packageName
+    inventory = $inventory
+} | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath (Join-Path $stage "sha256-inventory.json") -Encoding UTF8
+
+$folderRuntimeParent = Join-Path $outFull (".$packageName-folder-runtime-$nonce")
+$folderRuntime = Join-Path $folderRuntimeParent ".venv"
+$folderBootstrap = Invoke-Profile4Bootstrap $stage $python $folderRuntime "Package folder"
+$folderPython = Join-Path $folderRuntime "Scripts\python.exe"
+$folderSelfTest = Invoke-Profile4SelfTest $stage ([ordered]@{ exe = $folderPython; prefix = @() }) "Package folder"
+Remove-PackageBytecode $stage
+Remove-Item -LiteralPath $folderRuntimeParent -Recurse -Force
+
+Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipStage -Force
+$zipHash = Get-Sha256 $zipStage
+Set-Content -LiteralPath $sidecarStage -Encoding ASCII -Value ("{0}  {1}" -f $zipHash, (Split-Path -Leaf $finalZip))
+$extractRoot = Join-Path ([System.IO.Path]::GetTempPath()) ("$packageName-selftest-$nonce")
+Expand-Archive -LiteralPath $zipStage -DestinationPath $extractRoot -Force
+$zipRuntimeParent = Join-Path ([System.IO.Path]::GetTempPath()) ("$packageName-runtime-$nonce")
+$zipRuntime = Join-Path $zipRuntimeParent ".venv"
+$zipBootstrap = Invoke-Profile4Bootstrap $extractRoot $python $zipRuntime "Extracted zip"
+$zipPython = Join-Path $zipRuntime "Scripts\python.exe"
+$zipSelfTest = Invoke-Profile4SelfTest $extractRoot ([ordered]@{ exe = $zipPython; prefix = @() }) "Extracted zip"
+Remove-Item -LiteralPath $extractRoot -Recurse -Force
+Remove-Item -LiteralPath $zipRuntimeParent -Recurse -Force
+
+Move-Item -LiteralPath $stage -Destination $finalPackage
+Move-Item -LiteralPath $zipStage -Destination $finalZip
+Move-Item -LiteralPath $sidecarStage -Destination $finalSidecar
+
+[ordered]@{
+    status = "pass"
+    package_folder = $finalPackage
+    package_zip = $finalZip
+    package_zip_sha256 = $zipHash
+    selftest = [ordered]@{ folder = $folderSelfTest.status; zip = $zipSelfTest.status }
+    bootstrap = [ordered]@{ folder = $folderBootstrap.status; zip = $zipBootstrap.status }
+} | ConvertTo-Json -Depth 8

+ 166 - 10
tools/pid_harness.py

@@ -299,6 +299,112 @@ TD_TOP_PROFILES = {
         ],
         ],
         "authority_boundary": "SRAM-only production-two-uart-bmc-replay-binary921 evidence. BMC replay uses UART1 L10/M9, combined Host+Debug binary921 uses UART2 M10/N11 at 921600, and real HEAT/FAN/FG/INSTALL pinout is retained. JTAG uses J3 and PROGRAM_SRAM only. It does not claim live BMC, flash, real thermal performance, production PTC/FAN qualification, or PID closed-loop pass.",
         "authority_boundary": "SRAM-only production-two-uart-bmc-replay-binary921 evidence. BMC replay uses UART1 L10/M9, combined Host+Debug binary921 uses UART2 M10/N11 at 921600, and real HEAT/FAN/FG/INSTALL pinout is retained. JTAG uses J3 and PROGRAM_SRAM only. It does not claim live BMC, flash, real thermal performance, production PTC/FAN qualification, or PID closed-loop pass.",
     },
     },
+    "prod2u_fan_tach_binary921_v2_normal": {
+        "mode": "implementation",
+        "display_name": "Prod2U Profile 4 Normal fan tach and connector-effective PWM control",
+        "top_module": "prod2u_fan_tach_binary921_v2_normal_top",
+        "source_prj": "td/prod2u_fan_tach_binary921_v2_normal.prj",
+        "build_subdir": "prod2u_fan_tach_binary921_v2_normal",
+        "syn_script": "prod2u_fan_tach_binary921_v2_normal.tcl",
+        "phy_script": "prod2u_fan_tach_binary921_v2_normal.tcl",
+        "bitstream": "prod2u_fan_tach_binary921_v2_normal.bit",
+        "area_report": "prod2u_fan_tach_binary921_v2_normal_phy.area",
+        "timing_report": "prod2u_fan_tach_binary921_v2_normal_pr.timing",
+        "pin_profile": "prod2u-fan-tach-binary921-v2",
+        "protocol": "binary921-v2",
+        "runtime_profile_id": 4,
+        "variant": "normal",
+        "transport": "combined_host_debug_uart",
+        "bmc_status": "out_of_scope",
+        "bmc_source": "out_of_scope",
+        "tx_ball": "L10",
+        "rx_ball": "M9",
+        "host_uart_tx_ball": "M10",
+        "host_uart_rx_ball": "N11",
+        "host_uart_baud": 921600,
+        "host_uart_clks_per_bit": 27,
+        "debug_uart_baud": 921600,
+        "live_bmc_link_status": "out_of_scope",
+        "requires_verified_real_fan_ptc_pin_map": True,
+        "runtime_profile": "prod2u-fan-tach-binary921-v2",
+        "source_manifest_inputs": [
+            "src/rtl/uart_rx_8n1.v",
+            "src/rtl/uart_tx_8n1.v",
+            "src/rtl/binary921_crc16.v",
+            "src/rtl/binary921_frame_tx.v",
+            "src/rtl/prod2u_por.v",
+            "src/rtl/prod2u_p4_host_rx.v",
+            "src/rtl/prod2u_p4_tx_scheduler.v",
+            "src/rtl/prod2u_fan_tach_capture8.v",
+            "src/rtl/prod2u_fan_pwm_bank.v",
+            "src/rtl/prod2u_fan_tach_binary921_v2_core.v",
+            "src/top/prod2u_fan_tach_binary921_v2_normal_top.v",
+            "constraints/prod2u_fan_tach_binary921_v2.adc",
+            "constraints/pid_study_01.sdc",
+            "td/prod2u_fan_tach_binary921_v2_normal.prj",
+            "td/syn/prod2u_fan_tach_binary921_v2_normal.tcl",
+            "td/phy/prod2u_fan_tach_binary921_v2_normal.tcl",
+            "config/pin_inventory.fcb_fpga_mcu0611.json",
+            "tools/prod2u_p4_protocol.py",
+            "tools/prod2u_build_identity.py",
+            "tools/pid_harness.py",
+            "tools/pin_inventory.py",
+        ],
+        "authority_boundary": "SRAM-only Profile 4 Normal evidence for UART2 Host+Debug, connector-effective FAN PWM, raw 8-channel FG counts, PTC command actuation, timeout, and DISABLE. UART1/BMC, RPM calibration, electrical duty accuracy, thermal performance, PID, flash, and nonvolatile programming are out of scope.",
+    },
+    "prod2u_fan_tach_binary921_v2_trace": {
+        "mode": "implementation",
+        "display_name": "Prod2U Profile 4 Trace fan tach and connector-effective PWM control",
+        "top_module": "prod2u_fan_tach_binary921_v2_trace_top",
+        "source_prj": "td/prod2u_fan_tach_binary921_v2_trace.prj",
+        "build_subdir": "prod2u_fan_tach_binary921_v2_trace",
+        "syn_script": "prod2u_fan_tach_binary921_v2_trace.tcl",
+        "phy_script": "prod2u_fan_tach_binary921_v2_trace.tcl",
+        "bitstream": "prod2u_fan_tach_binary921_v2_trace.bit",
+        "area_report": "prod2u_fan_tach_binary921_v2_trace_phy.area",
+        "timing_report": "prod2u_fan_tach_binary921_v2_trace_pr.timing",
+        "pin_profile": "prod2u-fan-tach-binary921-v2",
+        "protocol": "binary921-v2",
+        "runtime_profile_id": 4,
+        "variant": "trace",
+        "transport": "combined_host_debug_uart",
+        "bmc_status": "out_of_scope",
+        "bmc_source": "out_of_scope",
+        "tx_ball": "L10",
+        "rx_ball": "M9",
+        "host_uart_tx_ball": "M10",
+        "host_uart_rx_ball": "N11",
+        "host_uart_baud": 921600,
+        "host_uart_clks_per_bit": 27,
+        "debug_uart_baud": 921600,
+        "live_bmc_link_status": "out_of_scope",
+        "requires_verified_real_fan_ptc_pin_map": True,
+        "runtime_profile": "prod2u-fan-tach-binary921-v2",
+        "source_manifest_inputs": [
+            "src/rtl/uart_rx_8n1.v",
+            "src/rtl/uart_tx_8n1.v",
+            "src/rtl/binary921_crc16.v",
+            "src/rtl/binary921_frame_tx.v",
+            "src/rtl/prod2u_por.v",
+            "src/rtl/prod2u_p4_host_rx.v",
+            "src/rtl/prod2u_p4_tx_scheduler.v",
+            "src/rtl/prod2u_fan_tach_capture8.v",
+            "src/rtl/prod2u_fan_pwm_bank.v",
+            "src/rtl/prod2u_fan_tach_binary921_v2_core.v",
+            "src/top/prod2u_fan_tach_binary921_v2_trace_top.v",
+            "constraints/prod2u_fan_tach_binary921_v2.adc",
+            "constraints/pid_study_01.sdc",
+            "td/prod2u_fan_tach_binary921_v2_trace.prj",
+            "td/syn/prod2u_fan_tach_binary921_v2_trace.tcl",
+            "td/phy/prod2u_fan_tach_binary921_v2_trace.tcl",
+            "config/pin_inventory.fcb_fpga_mcu0611.json",
+            "tools/prod2u_p4_protocol.py",
+            "tools/prod2u_build_identity.py",
+            "tools/pid_harness.py",
+            "tools/pin_inventory.py",
+        ],
+        "authority_boundary": "SRAM-only Profile 4 Trace evidence with 10 Hz bounded binary snapshots in addition to the Normal control contract. UART1/BMC, RPM calibration, electrical duty accuracy, thermal performance, PID, flash, and nonvolatile programming are out of scope.",
+    },
 }
 }
 TD_GENERATED_SUFFIXES = {
 TD_GENERATED_SUFFIXES = {
     ".area",
     ".area",
@@ -1193,6 +1299,44 @@ def hdl_testbenches() -> list[dict[str, Any]]:
             "name": "prod2u_por_tb",
             "name": "prod2u_por_tb",
             "sources": ["src/rtl/prod2u_por.v", "tests/sim/prod2u_por_tb.v"],
             "sources": ["src/rtl/prod2u_por.v", "tests/sim/prod2u_por_tb.v"],
         },
         },
+        {
+            "name": "prod2u_p4_host_rx_tb",
+            "sources": [
+                "src/rtl/binary921_crc16.v",
+                "src/rtl/prod2u_p4_host_rx.v",
+                "tests/sim/prod2u_p4_host_rx_tb.v",
+            ],
+        },
+        {
+            "name": "prod2u_p4_tx_scheduler_tb",
+            "sources": [
+                "src/rtl/prod2u_p4_tx_scheduler.v",
+                "tests/sim/prod2u_p4_tx_scheduler_tb.v",
+            ],
+        },
+        {
+            "name": "prod2u_fan_tach_capture8_tb",
+            "sources": [
+                "src/rtl/prod2u_fan_tach_capture8.v",
+                "tests/sim/prod2u_fan_tach_capture8_tb.v",
+            ],
+        },
+        {
+            "name": "prod2u_fan_pwm_bank_tb",
+            "sources": [
+                "src/rtl/prod2u_fan_pwm_bank.v",
+                "tests/sim/prod2u_fan_pwm_bank_tb.v",
+            ],
+        },
+        {
+            "name": "prod2u_fan_tach_binary921_v2_core_tb",
+            "sources": [
+                "src/rtl/prod2u_fan_tach_capture8.v",
+                "src/rtl/prod2u_fan_pwm_bank.v",
+                "src/rtl/prod2u_fan_tach_binary921_v2_core.v",
+                "tests/sim/prod2u_fan_tach_binary921_v2_core_tb.v",
+            ],
+        },
         {"name": "bmc_uart_phy_bridge_tb", "sources": ["src/rtl/bmc_uart_phy_bridge.v", "tests/sim/bmc_uart_phy_bridge_tb.v"]},
         {"name": "bmc_uart_phy_bridge_tb", "sources": ["src/rtl/bmc_uart_phy_bridge.v", "tests/sim/bmc_uart_phy_bridge_tb.v"]},
         {"name": "bmc_uart_ascii_poll_tb", "sources": ["src/rtl/bmc_uart_ascii_poll.v", "tests/sim/bmc_uart_ascii_poll_tb.v"]},
         {"name": "bmc_uart_ascii_poll_tb", "sources": ["src/rtl/bmc_uart_ascii_poll.v", "tests/sim/bmc_uart_ascii_poll_tb.v"]},
         {"name": "bmc_dimm_frame_parser_tb", "sources": ["src/rtl/bmc_dimm_frame_parser.v", "tests/sim/bmc_dimm_frame_parser_tb.v"]},
         {"name": "bmc_dimm_frame_parser_tb", "sources": ["src/rtl/bmc_dimm_frame_parser.v", "tests/sim/bmc_dimm_frame_parser_tb.v"]},
@@ -1301,6 +1445,7 @@ def formal_targets() -> list[dict[str, Any]]:
         {"name": "invalid_channel_no_actuator", "sby": "tests/formal/invalid_channel_no_actuator.sby"},
         {"name": "invalid_channel_no_actuator", "sby": "tests/formal/invalid_channel_no_actuator.sby"},
         {"name": "disable_clears_history", "sby": "tests/formal/disable_clears_history.sby"},
         {"name": "disable_clears_history", "sby": "tests/formal/disable_clears_history.sby"},
         {"name": "thermal_fault_requests_fan_fallback", "sby": "tests/formal/thermal_fault_requests_fan_fallback.sby"},
         {"name": "thermal_fault_requests_fan_fallback", "sby": "tests/formal/thermal_fault_requests_fan_fallback.sby"},
+        {"name": "prod2u_fan_data_path", "sby": "tests/formal/prod2u_fan_data_path.sby"},
     ]
     ]
 
 
 
 
@@ -1588,12 +1733,7 @@ def formal_payload(run: bool, engine: str = "sby") -> dict[str, Any]:
         "engine": engine,
         "engine": engine,
         "fact_class": "project_defined_strategy",
         "fact_class": "project_defined_strategy",
         "authority_boundary": "Formal checks prove bounded design properties only when the selected engine actually runs; they are not board or thermal proof.",
         "authority_boundary": "Formal checks prove bounded design properties only when the selected engine actually runs; they are not board or thermal proof.",
-        "properties": [
-            "fault_implies_ptc_off",
-            "invalid_channel_no_actuator",
-            "disable_clears_history",
-            "thermal_fault_requests_fan_fallback",
-        ],
+        "properties": [target["name"] for target in formal_targets()],
     }
     }
     if engine != "sby":
     if engine != "sby":
         return {"status": "fail", "reason": f"unsupported formal engine: {engine}", **payload}
         return {"status": "fail", "reason": f"unsupported formal engine: {engine}", **payload}
@@ -1963,10 +2103,24 @@ def cmd_replay(args: argparse.Namespace) -> int:
     return 0
     return 0
 
 
 
 
-def cmd_static(_: argparse.Namespace) -> int:
+def cmd_static(args: argparse.Namespace) -> int:
     result = run_python("verify_pid_study.py")
     result = run_python("verify_pid_study.py")
-    print(result.stdout, end="")
-    print(result.stderr, end="", file=sys.stderr)
+    payload = {
+        "status": status(result.returncode),
+        "verification_layer": "static",
+        "origin": "project_defined_required_verification_layer",
+        "command": list(result.args) if isinstance(result.args, (list, tuple)) else [str(result.args)],
+        "returncode": result.returncode,
+        "stdout": result.stdout,
+        "stderr": result.stderr,
+    }
+    if getattr(args, "report_file", None):
+        write_json_report(payload, args.report_file)
+    if getattr(args, "json", False):
+        print(json.dumps(payload, indent=2))
+    else:
+        print(result.stdout, end="")
+        print(result.stderr, end="", file=sys.stderr)
     return result.returncode
     return result.returncode
 
 
 
 
@@ -3418,7 +3572,7 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
     profile = TD_TOP_PROFILES[top]
     profile = TD_TOP_PROFILES[top]
     receipt_metadata = (
     receipt_metadata = (
         {"schema": "prod2u-td-build-receipt-v1"}
         {"schema": "prod2u-td-build-receipt-v1"}
-        if top == "prod2u_bmc_replay_binary921"
+        if top == "prod2u_bmc_replay_binary921" or profile.get("runtime_profile_id") == 4
         else {}
         else {}
     )
     )
 
 
@@ -3892,6 +4046,8 @@ def build_parser() -> argparse.ArgumentParser:
     replay.set_defaults(func=cmd_replay)
     replay.set_defaults(func=cmd_replay)
 
 
     static = sub.add_parser("static", help="run static project checks")
     static = sub.add_parser("static", help="run static project checks")
+    static.add_argument("--json", action="store_true")
+    static.add_argument("--report-file", type=Path)
     static.set_defaults(func=cmd_static)
     static.set_defaults(func=cmd_static)
 
 
     toolchain = sub.add_parser("toolchain", help="probe local verification/debug toolchain")
     toolchain = sub.add_parser("toolchain", help="probe local verification/debug toolchain")

+ 26 - 2
tools/pin_inventory.py

@@ -281,6 +281,7 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
         "formal-uart1-bmc-replay-binary921",
         "formal-uart1-bmc-replay-binary921",
         "production-two-uart-bmc-replay-binary921",
         "production-two-uart-bmc-replay-binary921",
         "prod2u-bmc-replay-binary921",
         "prod2u-bmc-replay-binary921",
+        "prod2u-fan-tach-binary921-v2",
     }
     }
     if profile not in supported_profiles:
     if profile not in supported_profiles:
         return {
         return {
@@ -300,9 +301,11 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
     reserved_uart_use_policy = "reserved_unused"
     reserved_uart_use_policy = "reserved_unused"
     uart_aliases: dict[str, str] = {}
     uart_aliases: dict[str, str] = {}
     allowed_reserved_balls: set[str] = set()
     allowed_reserved_balls: set[str] = set()
+    profile4_fan_tach = profile == "prod2u-fan-tach-binary921-v2"
     production_profile = profile in {
     production_profile = profile in {
         "production-two-uart-bmc-replay-binary921",
         "production-two-uart-bmc-replay-binary921",
         "prod2u-bmc-replay-binary921",
         "prod2u-bmc-replay-binary921",
+        "prod2u-fan-tach-binary921-v2",
     }
     }
     if profile in {"temp-uart-ptc-remap", "debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
     if profile in {"temp-uart-ptc-remap", "debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
         uart_assignments = dict(LOCKED_DEBUG_UART_ASSIGNMENTS)
         uart_assignments = dict(LOCKED_DEBUG_UART_ASSIGNMENTS)
@@ -378,8 +381,25 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
                     "combined_debug_host_uart_rx": "host_uart_rx",
                     "combined_debug_host_uart_rx": "host_uart_rx",
                 }
                 }
             )
             )
+        if profile4_fan_tach:
+            bmc_source = "out_of_scope"
+            live_bmc_link_status = "out_of_scope"
+            reserved_uart_use_policy = "intentional_uart1_idle_uart2_host"
+            uart_aliases = {
+                "idle_uart1_tx": "bmc_uart_tx",
+                "ignored_uart1_rx": "bmc_uart_rx",
+                "combined_debug_host_uart_tx": "host_uart_tx",
+                "combined_debug_host_uart_rx": "host_uart_rx",
+            }
         allowed_reserved_balls = {"L10", "M9", "M10", "N11"}
         allowed_reserved_balls = {"L10", "M9", "M10", "N11"}
-        if production_profile:
+        if profile4_fan_tach:
+            boundary = (
+                "Prod2U Profile 4 production pin profile: HEAT/FAN/FG/INSTALL stay on the PDF/inventory pins, "
+                "UART2 M10/N11 is the combined Host+Debug binary921-v2 port, and UART1 L10/M9 is retained only "
+                "as an idle TX and ignored RX electrical boundary. BMC is out of scope. J3 is PROGRAM_SRAM-only. "
+                "It does not qualify RPM calibration, PWM electrical accuracy, PTC thermal performance, PID, flash, or nonvolatile programming."
+            )
+        elif production_profile:
             boundary = (
             boundary = (
                 "Production two-UART BMC-replay binary921 profile for J3 SRAM-only bring-up: HEAT/FAN/FG/INSTALL stay on PDF/inventory pins, "
                 "Production two-UART BMC-replay binary921 profile for J3 SRAM-only bring-up: HEAT/FAN/FG/INSTALL stay on PDF/inventory pins, "
                 "BMC replay uses UART1 L10/M9 at 115200, and a combined Host+Debug binary921 port uses UART2 M10/N11 at 921600. "
                 "BMC replay uses UART1 L10/M9 at 115200, and a combined Host+Debug binary921 port uses UART2 M10/N11 at 921600. "
@@ -411,7 +431,11 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
     }
     }
     uses_reserved_future_uart = bool(used_balls & reserved_balls)
     uses_reserved_future_uart = bool(used_balls & reserved_balls)
     errors = list(conflict.get("errors") or [])
     errors = list(conflict.get("errors") or [])
-    if uses_reserved_future_uart and reserved_uart_use_policy != "intentional_uart1_uart2_bmc_replay_host":
+    allowed_reserved_policies = {
+        "intentional_uart1_uart2_bmc_replay_host",
+        "intentional_uart1_idle_uart2_host",
+    }
+    if uses_reserved_future_uart and reserved_uart_use_policy not in allowed_reserved_policies:
         errors.append("uses_reserved_future_uart")
         errors.append("uses_reserved_future_uart")
     status = "pass" if conflict["status"] == "pass" and not errors else "fail"
     status = "pass" if conflict["status"] == "pass" and not errors else "fail"
     return {
     return {

+ 252 - 12
tools/prod2u.ps1

@@ -1,22 +1,157 @@
 param(
 param(
     [Parameter(Position = 0)]
     [Parameter(Position = 0)]
-    [ValidateSet("selftest", "preflight", "program-only", "collect-only", "all")]
+    [ValidateSet(
+        "bootstrap",
+        "selftest",
+        "preflight",
+        "program-only",
+        "collect-only",
+        "all",
+        "query-fans",
+        "set-fan",
+        "set-ptc",
+        "disable",
+        "accept",
+        "validate-td-receipt"
+    )]
     [string]$Command = "selftest",
     [string]$Command = "selftest",
+    [ValidateSet("auto", "profile3", "profile4")]
+    [string]$Profile = "auto",
     [string]$CombinedPort = "COM5",
     [string]$CombinedPort = "COM5",
     [string]$Bitstream = ".\fw.bit",
     [string]$Bitstream = ".\fw.bit",
     [string]$TdReceipt = ".\td.json",
     [string]$TdReceipt = ".\td.json",
     [string]$SourceManifest = ".\source-manifest.json",
     [string]$SourceManifest = ".\source-manifest.json",
     [string]$BmcReplayReceipt = ".\bmc-replay-session.json",
     [string]$BmcReplayReceipt = ".\bmc-replay-session.json",
-    [string]$OutputDir = ".\evidence-prod2u",
+    [string]$OutputDir = "",
     [string]$TdRoot = "",
     [string]$TdRoot = "",
     [double]$DurationSeconds = 5.0,
     [double]$DurationSeconds = 5.0,
     [double]$ReadyTimeoutSeconds = 30.0,
     [double]$ReadyTimeoutSeconds = 30.0,
-    [double]$PreProgramObserveSeconds = 0.1
+    [double]$PreProgramObserveSeconds = 0.1,
+    [ValidateSet("normal", "trace")]
+    [string]$Variant = "normal",
+    [string]$BuildId = "",
+    [string]$Sha256 = "",
+    [ValidateRange(1, 4)]
+    [int]$Fan = 3,
+    [ValidateRange(1, 6)]
+    [int]$Ptc = 1,
+    [ValidateRange(0, 100)]
+    [int]$Percent = 0,
+    [string]$CampaignId = "",
+    [string]$DutId = "",
+    [string]$NormalBitstream = ".\normal.bit",
+    [string]$NormalTdReceipt = ".\normal-td.json",
+    [string]$NormalSourceManifest = ".\normal-source-manifest.json",
+    [string]$NormalBuildId = "",
+    [string]$NormalSha256 = "",
+    [string]$TraceBitstream = ".\trace.bit",
+    [string]$TraceTdReceipt = ".\trace-td.json",
+    [string]$TraceSourceManifest = ".\trace-source-manifest.json",
+    [string]$TraceBuildId = "",
+    [string]$TraceSha256 = "",
+    [string]$VenvDir = ""
 )
 )
 
 
 $ErrorActionPreference = "Stop"
 $ErrorActionPreference = "Stop"
+$env:PYTHONDONTWRITEBYTECODE = "1"
 $root = Split-Path -Parent $MyInvocation.MyCommand.Path
 $root = Split-Path -Parent $MyInvocation.MyCommand.Path
-$cli = Join-Path $root "prod2u_cli.py"
+$packageInventory = Join-Path $root "sha256-inventory.json"
+if (-not $OutputDir) {
+    if (Test-Path -LiteralPath $packageInventory -PathType Leaf) {
+        $OutputDir = Join-Path (Split-Path -Parent $root) ((Split-Path -Leaf $root) + "-evidence")
+    } else {
+        $OutputDir = ".\evidence-prod2u"
+    }
+}
+
+function Get-PackageSha256([string]$Path) {
+    return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
+}
+
+function Test-ImmutablePackage([string]$PackageRoot, [string]$InventoryPath, [string]$ExpectedSchema) {
+    $failures = @()
+    try {
+        $document = Get-Content -LiteralPath $InventoryPath -Raw -Encoding UTF8 | ConvertFrom-Json
+    } catch {
+        return @("package_inventory_invalid_json")
+    }
+    if ($document.schema -ne $ExpectedSchema -or $null -eq $document.inventory) {
+        return @("package_inventory_schema_mismatch")
+    }
+    $expected = @{}
+    foreach ($row in @($document.inventory)) {
+        $relative = ([string]$row.path).Replace('\', '/')
+        if (-not $relative -or [System.IO.Path]::IsPathRooted($relative) -or
+            $relative.Split('/') -contains ".." -or $relative -eq "sha256-inventory.json") {
+            $failures += "package_inventory_entry_invalid:$relative"
+            continue
+        }
+        if ($expected.ContainsKey($relative)) {
+            $failures += "package_inventory_duplicate:$relative"
+            continue
+        }
+        $expected[$relative] = $row
+    }
+    Get-ChildItem -LiteralPath $PackageRoot -Recurse -File | ForEach-Object {
+        $relative = $_.FullName.Substring($PackageRoot.Length).TrimStart('\').Replace('\', '/')
+        if ($relative -eq "sha256-inventory.json") { return }
+        if (-not $expected.ContainsKey($relative)) {
+            $failures += "package_inventory_unlisted_file:$relative"
+            return
+        }
+        $row = $expected[$relative]
+        if ([int64]$row.size -ne $_.Length) {
+            $failures += "package_inventory_size_mismatch:$relative"
+        }
+        if (([string]$row.sha256).ToLowerInvariant() -ne (Get-PackageSha256 $_.FullName)) {
+            $failures += "package_inventory_sha256_mismatch:$relative"
+        }
+        $expected.Remove($relative)
+    }
+    foreach ($relative in $expected.Keys) {
+        $failures += "package_inventory_missing_file:$relative"
+    }
+    return @($failures | Sort-Object -Unique)
+}
+
+$packageProfile = $null
+if (Test-Path -LiteralPath $packageInventory -PathType Leaf) {
+    try {
+        $packageHeader = Get-Content -LiteralPath $packageInventory -Raw -Encoding UTF8 | ConvertFrom-Json
+    } catch {
+        $packageHeader = $null
+    }
+    if ($null -ne $packageHeader) {
+        if ($packageHeader.schema -eq "prod2u-p4-package-sha256-inventory-v1") {
+            $packageProfile = "profile4"
+        } elseif ($packageHeader.schema -eq "prod2u-package-sha256-inventory-v1") {
+            $packageProfile = "profile3"
+        }
+    }
+    $expectedSchema = if ($packageProfile -eq "profile4") {
+        "prod2u-p4-package-sha256-inventory-v1"
+    } elseif ($packageProfile -eq "profile3") {
+        "prod2u-package-sha256-inventory-v1"
+    } else {
+        "unknown-package-inventory-schema"
+    }
+    $packageFailures = @(Test-ImmutablePackage $root $packageInventory $expectedSchema)
+    if ($packageFailures.Count -ne 0) {
+        [ordered]@{
+            schema = if ($packageProfile -eq "profile3") { "prod2u-preflight-v1" } else { "prod2u-p4-package-preflight-v1" }
+            status = if ($packageProfile -eq "profile3") { "fail_preflight" } else { "fail" }
+            profile = if ($packageProfile -eq "profile3") { "prod2u-bmc-replay-binary921" } else { "prod2u-fan-tach-binary921-v2" }
+            hardware_opened = $false
+            program_sram_attempted = $false
+            enumerated_com_ports = $false
+            failures = $packageFailures
+        } | ConvertTo-Json -Depth 8
+        exit 1
+    }
+}
+
+$legacyCli = Join-Path $root "prod2u_cli.py"
+$profile4Cli = Join-Path $root "prod2u_p4_cli.py"
 $pythonCandidates = @(
 $pythonCandidates = @(
     (Join-Path $root ".codex\venv\Scripts\python.exe"),
     (Join-Path $root ".codex\venv\Scripts\python.exe"),
     (Join-Path (Split-Path -Parent $root) ".codex\venv\Scripts\python.exe"),
     (Join-Path (Split-Path -Parent $root) ".codex\venv\Scripts\python.exe"),
@@ -34,20 +169,125 @@ foreach ($candidate in $pythonCandidates) {
 }
 }
 if (-not $python) { throw "Python 3 is required for the Prod2U harness" }
 if (-not $python) { throw "Python 3 is required for the Prod2U harness" }
 
 
-$arguments = @($cli, $Command)
-if ($Command -ne "selftest") {
+$profile3Commands = @("selftest", "validate-td-receipt", "preflight", "program-only", "collect-only", "all")
+$profile4Commands = @("bootstrap", "selftest", "preflight", "program-only", "query-fans", "set-fan", "set-ptc", "disable", "accept")
+$overlappingCommands = @($profile3Commands | Where-Object { $profile4Commands -contains $_ })
+
+if ($Profile -eq "auto") {
+    if ($packageProfile -eq "profile3") {
+        if (-not ($profile3Commands -contains $Command)) { throw "Profile 3 package does not support command: $Command" }
+        $useProfile4 = $false
+    } elseif ($packageProfile -eq "profile4") {
+        if (-not ($profile4Commands -contains $Command)) { throw "Profile 4 package does not support command: $Command" }
+        $useProfile4 = $true
+    } else {
+        # Source-tree overlap defaults to the active Profile 4 route.
+        $useProfile4 = ($overlappingCommands -contains $Command) -or ($profile4Commands -contains $Command)
+    }
+} elseif ($Profile -eq "profile3") {
+    if ($packageProfile -and $packageProfile -ne "profile3") { throw "Explicit profile3 conflicts with the immutable Profile 4 package" }
+    if (-not ($profile3Commands -contains $Command)) {
+        throw "Profile 3 does not support command: $Command"
+    }
+    $useProfile4 = $false
+} elseif ($Profile -eq "profile4") {
+    if ($packageProfile -and $packageProfile -ne "profile4") { throw "Explicit profile4 conflicts with the immutable Profile 3 package" }
+    if (-not ($profile4Commands -contains $Command)) {
+        throw "Profile 4 does not support command: $Command"
+    }
+    $useProfile4 = $true
+} else {
+    throw "Unsupported profile: $Profile"
+}
+
+if (-not $useProfile4) {
+    $arguments = @($legacyCli, $Command)
+    if ($Command -eq "validate-td-receipt") {
+        $arguments += @("--td-receipt", $TdReceipt)
+    } elseif ($Command -ne "selftest") {
+        $arguments += @(
+            "--combined-port", $CombinedPort,
+            "--bitstream", $Bitstream,
+            "--td-receipt", $TdReceipt,
+            "--source-manifest", $SourceManifest,
+            "--bmc-replay-receipt", $BmcReplayReceipt,
+            "--output-dir", $OutputDir,
+            "--duration-sec", $DurationSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture),
+            "--ready-timeout-sec", $ReadyTimeoutSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture),
+            "--pre-program-observe-sec", $PreProgramObserveSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture)
+        )
+        if ($TdRoot) { $arguments += @("--td-root", $TdRoot) }
+    }
+    & $python -B @arguments
+    exit $LASTEXITCODE
+}
+
+if (-not (Test-Path -LiteralPath $profile4Cli)) {
+    throw "Profile 4 CLI is missing: $profile4Cli"
+}
+
+$arguments = @($profile4Cli, $Command)
+if ($Command -eq "bootstrap") {
+    $arguments += @("--package-root", $root)
+    if ($VenvDir) { $arguments += @("--venv-dir", $VenvDir) }
+} elseif ($Command -eq "selftest") {
+    if (Test-Path -LiteralPath $packageInventory -PathType Leaf) {
+        $arguments += @("--package-root", $root)
+    }
+} elseif ($Command -eq "accept") {
+    foreach ($required in @(
+        @{ Name = "TdRoot"; Value = $TdRoot },
+        @{ Name = "CampaignId"; Value = $CampaignId },
+        @{ Name = "DutId"; Value = $DutId },
+        @{ Name = "NormalBuildId"; Value = $NormalBuildId },
+        @{ Name = "NormalSha256"; Value = $NormalSha256 },
+        @{ Name = "TraceBuildId"; Value = $TraceBuildId },
+        @{ Name = "TraceSha256"; Value = $TraceSha256 }
+    )) {
+        if (-not $required.Value) { throw "$($required.Name) is required for Profile 4 accept" }
+    }
     $arguments += @(
     $arguments += @(
-        "--combined-port", $CombinedPort,
+        "--td-root", $TdRoot,
+        "--output-dir", $OutputDir,
+        "--trace-build-id", $TraceBuildId,
+        "--trace-bitstream", $TraceBitstream,
+        "--trace-sha256", $TraceSha256,
+        "--trace-td-receipt", $TraceTdReceipt,
+        "--trace-source-manifest", $TraceSourceManifest,
+        "--normal-build-id", $NormalBuildId,
+        "--normal-bitstream", $NormalBitstream,
+        "--normal-sha256", $NormalSha256,
+        "--normal-td-receipt", $NormalTdReceipt,
+        "--normal-source-manifest", $NormalSourceManifest,
+        "--campaign-id", $CampaignId,
+        "--dut-id", $DutId,
+        "--package-root", $root
+    )
+} else {
+    foreach ($required in @(
+        @{ Name = "TdRoot"; Value = $TdRoot },
+        @{ Name = "BuildId"; Value = $BuildId },
+        @{ Name = "Sha256"; Value = $Sha256 }
+    )) {
+        if (-not $required.Value) { throw "$($required.Name) is required for Profile 4 $Command" }
+    }
+    $arguments += @(
+        "--variant", $Variant,
+        "--build-id", $BuildId,
         "--bitstream", $Bitstream,
         "--bitstream", $Bitstream,
+        "--sha256", $Sha256,
         "--td-receipt", $TdReceipt,
         "--td-receipt", $TdReceipt,
         "--source-manifest", $SourceManifest,
         "--source-manifest", $SourceManifest,
-        "--bmc-replay-receipt", $BmcReplayReceipt,
+        "--td-root", $TdRoot,
         "--output-dir", $OutputDir,
         "--output-dir", $OutputDir,
-        "--duration-sec", $DurationSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture),
-        "--ready-timeout-sec", $ReadyTimeoutSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture),
-        "--pre-program-observe-sec", $PreProgramObserveSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture)
+        "--run-id", ("prod2u-p4-{0}" -f $Command)
     )
     )
-    if ($TdRoot) { $arguments += @("--td-root", $TdRoot) }
+    if ($Command -eq "set-fan") {
+        $arguments += @("--fan", $Fan, "--percent", $Percent)
+    } elseif ($Command -eq "set-ptc") {
+        $arguments += @("--ptc", $Ptc, "--percent", $Percent)
+    }
 }
 }
+
 & $python -B @arguments
 & $python -B @arguments
 exit $LASTEXITCODE
 exit $LASTEXITCODE

+ 401 - 0
tools/prod2u_p4_campaign.py

@@ -0,0 +1,401 @@
+#!/usr/bin/env python3
+"""Deterministic Prod2U Profile 4 ten-round campaign orchestration."""
+
+from __future__ import annotations
+
+import json
+import hashlib
+import math
+from dataclasses import asdict, dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, Mapping, Protocol, Sequence
+
+
+PROFILE = "prod2u-fan-tach-binary921-v2"
+FAN_SETTINGS = (0, 20, 40, 60, 80, 100)
+SETTLE_WINDOWS = 2
+SAMPLE_WINDOWS = 5
+PTC_CHANNELS = tuple(range(1, 7))
+PTC_PERCENT = 10
+PTC_DURATION_S = 2.0
+
+
+@dataclass(frozen=True)
+class RoundPlan:
+    round: int
+    variant_round: int
+    variant: str
+    attempt: int = 1
+    retry_count: int = 0
+    power_cycle: bool = False
+
+
+class RoundController(Protocol):
+    watchdog_safe: bool
+
+    def set_fan(self, channel: int, percent: int) -> None: ...
+    def sample_fans(self) -> Mapping[str, Any]: ...
+    def set_ptc(self, channel: int, percent: int) -> None: ...
+    def sleep(self, seconds: float) -> None: ...
+    def verify_timeout_fallback(self) -> Mapping[str, Any]: ...
+    def disable(self) -> None: ...
+    def evidence_summary(self) -> Mapping[str, Any]: ...
+
+
+def utc_now() -> str:
+    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _sha256_file(path: Path) -> str:
+    digest = hashlib.sha256()
+    with Path(path).open("rb") as stream:
+        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def build_evidence_binding(
+    *,
+    programmer_receipt: Path,
+    pre_program_raw: Path,
+    combined_rx_raw: Path,
+    raw_transcript: Path,
+    td_receipt: Path,
+    source_manifest: Path,
+    package_manifest: Path,
+    package_inventory: Path,
+    identity: Mapping[str, Any],
+    programmer_receipt_status: str = "pass",
+    programmer_receipt_payload: Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+    """Hash and preserve the immutable inputs required by the strict P4 gate."""
+    paths = {
+        "programmer_receipt": programmer_receipt,
+        "pre_program_raw": pre_program_raw,
+        "combined_rx_raw": combined_rx_raw,
+        "raw_transcript": raw_transcript,
+        "td_receipt": td_receipt,
+        "source_manifest": source_manifest,
+        "package_manifest": package_manifest,
+        "package_inventory": package_inventory,
+    }
+    binding: dict[str, Any] = {}
+    for name, candidate in paths.items():
+        path = Path(candidate)
+        artifact: dict[str, Any] = {"path": path.as_posix(), "sha256": _sha256_file(path)}
+        if name == "programmer_receipt":
+            artifact["status"] = programmer_receipt_status
+            if programmer_receipt_payload is not None:
+                artifact["receipt"] = dict(programmer_receipt_payload)
+        elif name == "source_manifest":
+            try:
+                manifest = json.loads(path.read_text(encoding="utf-8-sig"))
+            except (OSError, UnicodeError, json.JSONDecodeError):
+                manifest = None
+            if isinstance(manifest, Mapping) and isinstance(manifest.get("source_manifest_sha256"), str):
+                artifact["declared_sha256"] = manifest["source_manifest_sha256"]
+        binding[name] = artifact
+    binding["identity"] = dict(identity)
+    return binding
+
+
+def build_round_plans() -> list[RoundPlan]:
+    return [
+        RoundPlan(round=index, variant_round=((index - 1) % 5) + 1, variant="trace" if index <= 5 else "normal")
+        for index in range(1, 11)
+    ]
+
+
+def _ranks(values: Sequence[float]) -> list[float]:
+    ordered = sorted((value, index) for index, value in enumerate(values))
+    result = [0.0] * len(values)
+    start = 0
+    while start < len(ordered):
+        end = start + 1
+        while end < len(ordered) and ordered[end][0] == ordered[start][0]:
+            end += 1
+        rank = (start + 1 + end) / 2.0
+        for _, original_index in ordered[start:end]:
+            result[original_index] = rank
+        start = end
+    return result
+
+
+def spearman_rho(x_values: Sequence[float], y_values: Sequence[float]) -> float | None:
+    if len(x_values) != len(y_values) or len(x_values) < 2:
+        return None
+    x_ranks = _ranks(x_values)
+    y_ranks = _ranks(y_values)
+    x_mean = sum(x_ranks) / len(x_ranks)
+    y_mean = sum(y_ranks) / len(y_ranks)
+    numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_ranks, y_ranks))
+    x_denominator = math.sqrt(sum((x - x_mean) ** 2 for x in x_ranks))
+    y_denominator = math.sqrt(sum((y - y_mean) ** 2 for y in y_ranks))
+    if x_denominator == 0 or y_denominator == 0:
+        return None
+    return numerator / (x_denominator * y_denominator)
+
+
+def _detection_status(rows: Sequence[Mapping[str, Any]], signal: str) -> str:
+    nonzero_by_setting = []
+    all_high_edges: list[int] = []
+    for setting in (80, 100):
+        edges = [
+            int(_mapping.get(signal, {}).get("window_edges", 0))
+            for _mapping in rows
+            if _mapping.get("fan_setting_percent") == setting
+        ]
+        all_high_edges.extend(edges)
+        nonzero_by_setting.append(sum(value > 0 for value in edges))
+    if nonzero_by_setting and max(nonzero_by_setting) >= 4:
+        return "detected"
+    if all_high_edges and all(value == 0 for value in all_high_edges):
+        return "absent"
+    return "intermittent"
+
+
+def execute_round(controller: RoundController, plan: RoundPlan) -> dict[str, Any]:
+    """Run one no-retry fan/PTC round and always establish a safe rollback."""
+    retained: list[dict[str, Any]] = []
+    windows: list[dict[str, Any]] = []
+    operation_error: str | None = None
+    rollback: dict[str, Any]
+    timeout_result: dict[str, Any] = {"status": "not_run", "timeout_active": False}
+    window_index = 0
+    try:
+        for setting in FAN_SETTINGS:
+            controller.set_fan(3, setting)
+            for _ in range(SETTLE_WINDOWS):
+                observed = controller.sample_fans()
+                windows.append(
+                    {
+                        "index": window_index,
+                        "start_s": float(window_index),
+                        "end_s": float(window_index + 1),
+                        "continuous": True,
+                        "phase": "settle",
+                        "snapshot_seq": int(observed["snapshot_seq"]),
+                        "overflow_mask": int(observed["overflow_mask"]),
+                    }
+                )
+                window_index += 1
+            for _ in range(SAMPLE_WINDOWS):
+                observed = controller.sample_fans()
+                row = {
+                    "fan_setting_percent": setting,
+                    "snapshot_seq": int(observed["snapshot_seq"]),
+                    "overflow_mask": int(observed["overflow_mask"]),
+                    "FG5": dict(observed.get("FG5", {})),
+                    "FG6": dict(observed.get("FG6", {})),
+                }
+                retained.append(row)
+                windows.append(
+                    {
+                        "index": window_index,
+                        "start_s": float(window_index),
+                        "end_s": float(window_index + 1),
+                        "continuous": True,
+                        "phase": "sample",
+                        "snapshot_seq": int(observed["snapshot_seq"]),
+                        "overflow_mask": int(observed["overflow_mask"]),
+                    }
+                )
+                window_index += 1
+
+        for channel in PTC_CHANNELS:
+            controller.set_ptc(channel, PTC_PERCENT)
+            controller.sleep(PTC_DURATION_S)
+            controller.set_ptc(channel, 0)
+        timeout_result = dict(controller.verify_timeout_fallback())
+    except Exception as exc:  # The rollback below must run for every hardware failure.
+        operation_error = f"{type(exc).__name__}: {exc}"
+    try:
+        controller.disable()
+        rollback = {"status": "pass", "mechanism": "DISABLE"}
+    except Exception as exc:
+        if getattr(controller, "watchdog_safe", False):
+            rollback = {"status": "pass", "mechanism": "watchdog", "disable_error": f"{type(exc).__name__}: {exc}"}
+        else:
+            rollback = {"status": "fail", "mechanism": "none", "disable_error": f"{type(exc).__name__}: {exc}"}
+
+    control = dict(controller.evidence_summary())
+    fan_status = {
+        "FG5": _detection_status(retained, "FG5"),
+        "FG6": _detection_status(retained, "FG6"),
+    }
+    correlation_samples: list[dict[str, float]] = []
+    for setting in FAN_SETTINGS:
+        rows = [row for row in retained if row["fan_setting_percent"] == setting]
+        rpm_values = [
+            float(max(int(row["FG5"].get("rpm", 0)), int(row["FG6"].get("rpm", 0))))
+            for row in rows
+        ]
+        mean_rpm = sum(rpm_values) / len(rpm_values) if rpm_values else 0.0
+        correlation_samples.append({"fan_setting_percent": float(setting), "rpm": mean_rpm})
+    trend_samples = [sample for sample in correlation_samples if sample["fan_setting_percent"] > 0]
+    rho = spearman_rho(
+        [sample["fan_setting_percent"] for sample in trend_samples],
+        [sample["rpm"] for sample in trend_samples],
+    )
+    if rho is not None:
+        rho = round(rho, 12)
+    by_setting = {int(sample["fan_setting_percent"]): sample["rpm"] for sample in correlation_samples}
+    low_mean = (by_setting[20] + by_setting[40]) / 2.0
+    high_mean = (by_setting[80] + by_setting[100]) / 2.0
+    significant = high_mean >= low_mean + max(100.0, low_mean * 0.10)
+    overflow_failures = []
+    for signal, bit in (("FG5", 4), ("FG6", 5)):
+        if fan_status[signal] == "detected" and any(int(row["overflow_mask"]) & (1 << bit) for row in retained):
+            overflow_failures.append(f"tach_overflow:{signal}")
+    layers = {
+        "required": {
+            "host_ack": "pass" if control.get("all_acks_matched") is True else "fail",
+            "pwm_state": "pass"
+            if int(control.get("fan_commit_acks", 0)) >= 6
+            and int(control.get("ptc_commit_acks", 0)) >= 12
+            and int(control.get("disable_commit_acks", 0)) >= 1
+            else "fail",
+            "fan3_tach_trend": "pass"
+            if "detected" in fan_status.values() and rho is not None and rho >= 0.60 and significant and not overflow_failures
+            else "fail",
+            "timeout_fallback": "pass"
+            if timeout_result.get("status") == "pass"
+            and timeout_result.get("timeout_active") is True
+            and control.get("timeout_verified") is True
+            else "fail",
+            "disable": "pass" if int(control.get("disable_commit_acks", 0)) >= 1 else "fail",
+            "ptc_command_path": "pass" if int(control.get("ptc_commit_acks", 0)) >= 12 else "fail",
+        },
+        "optional": {},
+    }
+    failures = []
+    if operation_error:
+        failures.append(f"round_action_failed:{operation_error}")
+    if rollback["status"] != "pass":
+        failures.append("rollback_not_established")
+    if rho is None or rho < 0.60:
+        failures.append("trend_spearman_below_threshold")
+    if not significant:
+        failures.append("trend_high_setting_not_significantly_higher")
+    failures.extend(overflow_failures)
+    failures.extend(
+        f"required_layer_not_pass:{name}"
+        for name, status in layers["required"].items()
+        if status != "pass"
+    )
+
+    return {
+        "status": "pass" if not failures else "fail",
+        **asdict(plan),
+        "layers": layers,
+        "fan": {"FAN3": fan_status},
+        "windows": windows,
+        "correlation": {
+            "spearman_rho": rho,
+            "low_mean_rpm": low_mean,
+            "high_mean_rpm": high_mean,
+            "high_significantly_higher": significant,
+            "samples": correlation_samples,
+        },
+        "rpm": {
+            "status": "not_qualified",
+            "reason": "FG-derived RPM is uncalibrated and is used only for trend detection",
+            "calibration_status": "uncalibrated",
+        },
+        "ptc": {"actuation": operation_error is None, "measurement": "not_run"},
+        "timeout": timeout_result,
+        "control": control,
+        "rollback": rollback,
+        "failures": failures,
+        "raw_samples": retained,
+    }
+
+
+def _append_journal(path: Path, record: Mapping[str, Any]) -> None:
+    with path.open("a", encoding="utf-8", newline="\n") as stream:
+        stream.write(json.dumps(dict(record), sort_keys=True, separators=(",", ":")) + "\n")
+        stream.flush()
+
+
+def run_campaign(
+    *,
+    output_root: Path,
+    campaign_id: str,
+    identity: Mapping[str, Any],
+    qualification: Mapping[str, Any],
+    round_executor: Callable[[RoundPlan, Path], Mapping[str, Any]],
+) -> dict[str, Any]:
+    """Create a unique append-only journal, then run rounds until the first failure."""
+    if not campaign_id or Path(campaign_id).name != campaign_id:
+        raise ValueError("campaign_id must be a non-empty path-safe name")
+    output_root = Path(output_root)
+    output_root.mkdir(parents=True, exist_ok=True)
+    campaign_dir = output_root / campaign_id
+    campaign_dir.mkdir(exist_ok=False)
+    journal_path = campaign_dir / "journal.jsonl"
+    created = {
+        "event": "campaign_created",
+        "at": utc_now(),
+        "campaign_id": campaign_id,
+        "profile": PROFILE,
+        "attempt": 1,
+        "retry_count": 0,
+        "power_cycle": False,
+        "planned_rounds": 10,
+        "bmc_status": "out_of_scope",
+        "qualification_status": qualification.get("status"),
+        "qualification_sha256": hashlib.sha256(
+            json.dumps(dict(qualification), sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
+        ).hexdigest(),
+    }
+    with journal_path.open("x", encoding="utf-8", newline="\n") as stream:
+        stream.write(json.dumps(created, sort_keys=True, separators=(",", ":")) + "\n")
+        stream.flush()
+
+    rounds: list[dict[str, Any]] = []
+    for plan in build_round_plans():
+        round_dir = campaign_dir / f"round-{plan.round:02d}-{plan.variant}"
+        round_dir.mkdir()
+        _append_journal(journal_path, {"event": "round_started", "at": utc_now(), **asdict(plan)})
+        try:
+            raw_result = dict(round_executor(plan, round_dir))
+        except Exception as exc:
+            raw_result = {"status": "fail", "failures": [f"round_executor_exception:{type(exc).__name__}:{exc}"]}
+        result = {
+            **raw_result,
+            "round": plan.round,
+            "variant": plan.variant,
+            "variant_round": plan.variant_round,
+            "attempt": 1,
+            "retry_count": 0,
+            "power_cycle": False,
+            "identity": dict(raw_result.get("identity", identity)),
+        }
+        rounds.append(result)
+        (round_dir / "evidence.json").write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+        _append_journal(
+            journal_path,
+            {"event": "round_finished", "at": utc_now(), "round": plan.round, "variant": plan.variant, "status": result.get("status")},
+        )
+        if result.get("status") != "pass":
+            break
+
+    status = "pass" if len(rounds) == 10 and all(item.get("status") == "pass" for item in rounds) else "fail"
+    payload = {
+        "schema": "prod2u-p4-campaign-v2",
+        "status": status,
+        "campaign_id": campaign_id,
+        "campaign_identity": {**dict(identity), "planned_rounds": 10},
+        "bmc": {"status": "out_of_scope", "reason": "Profile 4 has no BMC UART or BMC receipt dependency"},
+        "qualification": dict(qualification),
+        "round_count": len(rounds),
+        "rounds": rounds,
+        "evidence_bindings": [
+            {"round": item.get("round"), "evidence_binding": item.get("evidence_binding")}
+            for item in rounds
+        ],
+    }
+    (campaign_dir / "campaign.json").write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    _append_journal(journal_path, {"event": "campaign_finished", "at": utc_now(), "status": status, "round_count": len(rounds)})
+    return payload

ファイルの差分が大きいため隠しています
+ 1535 - 0
tools/prod2u_p4_cli.py


+ 353 - 0
tools/prod2u_p4_collector.py

@@ -0,0 +1,353 @@
+#!/usr/bin/env python3
+"""Raw-first COM5 collector for Prod2U Profile 4 binary921 v2."""
+
+from __future__ import annotations
+
+import json
+import time
+from collections.abc import Mapping
+from pathlib import Path
+from typing import Any, Callable
+
+from prod2u_p4_protocol import FrameType, P4Frame, decode_ready, decode_stream
+
+
+PROFILE = "prod2u-fan-tach-binary921-v2"
+PORT = "COM5"
+BAUD = 921600
+VARIANT_IDS = {"normal": 0, "trace": 1}
+PROGRAM_MARKERS = (
+    "download_start",
+    "chip_validation",
+    "bit_to_vec_start",
+    "bit_to_vec_finish",
+    "program_start",
+    "program_finish",
+    "download_finish",
+)
+PROGRAM_RECEIPT_SECTIONS = (
+    "request",
+    "bitstream",
+    "staging",
+    "execution",
+    "parser",
+    "safety",
+    "tool",
+    "mutex",
+    "process_cleanup",
+    "artifacts",
+)
+EXECUTION_FIELDS = (
+    "exit_code",
+    "timed_out",
+    "attempt_count",
+    "retry_count",
+    "power_cycle_count",
+    "command_execution_attempted",
+    "timeout_seconds",
+    "started_at",
+    "finished_at",
+    "duration_seconds",
+)
+
+
+def open_com5(serial_factory: Callable[[], Any] | None = None) -> Any:
+    if serial_factory is None:
+        try:
+            import serial  # type: ignore
+        except ImportError as exc:
+            raise RuntimeError("pyserial is required for live Profile 4 collection") from exc
+        serial_factory = serial.Serial
+    endpoint = serial_factory()
+    endpoint.port = PORT
+    endpoint.baudrate = BAUD
+    endpoint.bytesize = 8
+    endpoint.parity = "N"
+    endpoint.stopbits = 1
+    endpoint.timeout = 0.01
+    endpoint.write_timeout = 0.1
+    endpoint.rtscts = False
+    endpoint.dsrdtr = False
+    endpoint.dtr = False
+    endpoint.rts = False
+    endpoint.open()
+    return endpoint
+
+
+def _drain_available(endpoint: Any) -> bytes:
+    raw = bytearray()
+    while True:
+        chunk = endpoint.read(4096)
+        if not chunk:
+            return bytes(raw)
+        raw.extend(chunk)
+
+
+def _variant_matches(ready_variant: int, variant: str) -> bool:
+    if variant not in VARIANT_IDS:
+        raise ValueError("variant must be normal or trace")
+    return ready_variant == VARIANT_IDS[variant]
+
+
+def _frame_record(frame: P4Frame, *, phase: str) -> dict[str, Any]:
+    record: dict[str, Any] = {
+        "source": "wire",
+        "phase": phase,
+        "version": frame.version,
+        "profile_id": frame.profile_id,
+        "frame_type": int(frame.frame_type),
+        "frame_type_name": frame.frame_type.name,
+        "seq": frame.seq,
+        "timestamp_tick": frame.timestamp_tick,
+        "payload_hex": frame.payload.hex(),
+        "raw_hex": frame.raw.hex(),
+    }
+    if frame.frame_type == FrameType.READY:
+        ready = decode_ready(frame)
+        record["ready"] = {
+            "build_id": f"{ready.build_id:08X}",
+            "variant_id": ready.variant,
+            "startup_reason": ready.startup_reason,
+            "startup_seq": ready.startup_seq,
+            "capability_flags": ready.capability_flags,
+            "variant": "trace" if ready.variant == 1 else "normal",
+        }
+    return record
+
+
+def _decode_records(raw: bytes, *, phase: str) -> list[dict[str, Any]]:
+    frames, _ = decode_stream(raw)
+    return [_frame_record(frame, phase=phase) for frame in frames]
+
+
+def _is_nonempty_string(value: Any) -> bool:
+    return isinstance(value, str) and bool(value.strip())
+
+
+def _program_sram_receipt_failures(receipt: Any) -> list[str]:
+    if not isinstance(receipt, Mapping):
+        return ["receipt_not_mapping"]
+    failures: list[str] = []
+    if receipt.get("schema") != "prod2u-program-sram-receipt-v1":
+        failures.append("schema_mismatch")
+    if receipt.get("status") != "pass":
+        failures.append("status_not_pass")
+    if not _is_nonempty_string(receipt.get("run_id")):
+        failures.append("run_id_missing_or_empty")
+    if not _is_nonempty_string(receipt.get("authority_boundary")):
+        failures.append("authority_boundary_missing_or_empty")
+    for section in PROGRAM_RECEIPT_SECTIONS:
+        if not isinstance(receipt.get(section), Mapping):
+            failures.append(f"section_missing_or_malformed:{section}")
+    if failures:
+        return failures
+
+    request = receipt["request"]
+    if (
+        request.get("operation") != "PROGRAM_SRAM"
+        or request.get("target_chip") != "EF2L45"
+        or request.get("cable_index") != 0
+        or request.get("speed_code") != 2
+        or request.get("speed_hz") != 200000
+        or request.get("attempt_limit") != 1
+        or request.get("power_cycle_allowed") is not False
+    ):
+        failures.append("request_not_single_program_sram")
+
+    execution = receipt["execution"]
+    if not execution:
+        failures.append("execution_empty")
+    else:
+        missing_execution = [field for field in EXECUTION_FIELDS if field not in execution]
+        if missing_execution:
+            failures.append("execution_fields_missing:" + ",".join(missing_execution))
+        elif (
+            execution.get("exit_code") != 0
+            or execution.get("timed_out") is not False
+            or execution.get("attempt_count") != 1
+            or execution.get("retry_count") != 0
+            or execution.get("power_cycle_count") != 0
+            or execution.get("command_execution_attempted") is not True
+            or execution.get("timeout_seconds") != 60
+            or not _is_nonempty_string(execution.get("started_at"))
+            or not _is_nonempty_string(execution.get("finished_at"))
+            or not isinstance(execution.get("duration_seconds"), (int, float))
+            or isinstance(execution.get("duration_seconds"), bool)
+            or execution["duration_seconds"] < 0
+        ):
+            failures.append("execution_not_one_clean_attempt")
+
+    parser = receipt["parser"]
+    if (
+        parser.get("status") != "pass"
+        or parser.get("exit_code_trusted") is not False
+        or parser.get("ordered_markers") != list(PROGRAM_MARKERS)
+        or parser.get("ordered_markers_complete") is not True
+        or parser.get("observed_markers") != list(PROGRAM_MARKERS)
+        or not isinstance(parser.get("observed_marker_lines"), list)
+        or len(parser["observed_marker_lines"]) != len(PROGRAM_MARKERS)
+        or any(not isinstance(line, int) or isinstance(line, bool) or line < 1 for line in parser["observed_marker_lines"])
+        or parser.get("error_markers") != []
+        or parser.get("failures") != []
+        or not _is_nonempty_string(parser.get("transcript_sha256"))
+    ):
+        failures.append("parser_transaction_not_complete")
+
+    bitstream = receipt["bitstream"]
+    staging = receipt["staging"]
+    if (
+        not all(_is_nonempty_string(bitstream.get(name)) for name in ("path", "sha256", "build_id"))
+        or not all(_is_nonempty_string(staging.get(name)) for name in ("expected_path", "observed_path"))
+        or staging.get("matches_expected_path") is not True
+    ):
+        failures.append("bitstream_or_staging_incomplete")
+
+    safety = receipt["safety"]
+    if (
+        safety.get("external_programming_command_executed") is not True
+        or any(
+            safety.get(name) is not False
+            for name in (
+                "flash_attempted",
+                "programs_nonvolatile",
+                "power_cycle_attempted",
+                "driver_install_attempted",
+                "toggles_dtr_rts",
+                "real_ptc_fan_action_attempted",
+            )
+        )
+    ):
+        failures.append("safety_not_clean")
+
+    tool = receipt["tool"]
+    mutex = receipt["mutex"]
+    cleanup = receipt["process_cleanup"]
+    artifacts = receipt["artifacts"]
+    if not all(_is_nonempty_string(tool.get(name)) for name in ("path", "td_root", "td_bin")):
+        failures.append("tool_incomplete")
+    if mutex.get("name") != r"Global\Prod2UProgramSram" or mutex.get("acquired") is not True:
+        failures.append("mutex_not_acquired")
+    if cleanup.get("status") != "pass" or cleanup.get("remaining") != [] or cleanup.get("wait_seconds") != 5.0:
+        failures.append("process_cleanup_not_complete")
+    if not all(isinstance(artifacts.get(name), Mapping) for name in ("tcl", "stdout", "stderr", "log_delta")):
+        failures.append("artifacts_missing_or_malformed")
+    if not isinstance(artifacts.get("log_delta_sources"), list) or len(artifacts["log_delta_sources"]) != 1:
+        failures.append("log_delta_sources_not_exactly_one")
+    return failures
+
+
+def _require_valid_program_sram_receipt(receipt: Any) -> dict[str, Any]:
+    if not isinstance(receipt, Mapping):
+        raise RuntimeError("PROGRAM_SRAM receipt invalid: receipt_not_mapping")
+    failures = _program_sram_receipt_failures(receipt)
+    if failures:
+        raise RuntimeError("PROGRAM_SRAM receipt invalid: " + ", ".join(failures))
+    return dict(receipt)
+
+
+def collect_programmed_session(
+    *,
+    output_dir: Path,
+    build_id: int,
+    variant: str,
+    programmer: Callable[[], dict[str, Any]],
+    serial_factory: Callable[[], Any] | None = None,
+    ready_timeout_s: float = 5.0,
+    after_ready: Callable[[Any], Any] | None = None,
+) -> dict[str, Any]:
+    """Open COM first, run one programmer callback, then require a post-program READY."""
+    if isinstance(build_id, bool) or not isinstance(build_id, int) or not 0 <= build_id <= 0xFFFFFFFF:
+        raise ValueError("build_id must be a 32-bit integer")
+    if ready_timeout_s <= 0:
+        raise ValueError("ready_timeout_s must be positive")
+    _variant_matches(0, variant)
+    output_dir = Path(output_dir)
+    output_dir.mkdir(parents=True, exist_ok=False)
+    endpoint = open_com5(serial_factory)
+    pre_program_raw = b""
+    post_chunks: list[bytes] = []
+    programmer_receipt: dict[str, Any] | None = None
+    accepted_frame: P4Frame | None = None
+    command_result: Any = None
+    command_wire = b""
+    try:
+        pre_program_raw = _drain_available(endpoint)
+        programmer_receipt = _require_valid_program_sram_receipt(programmer())
+        deadline = time.monotonic() + ready_timeout_s
+        post_buffer = bytearray()
+        remainder = b""
+        while time.monotonic() < deadline:
+            chunk = endpoint.read(4096)
+            if not chunk:
+                time.sleep(0.001)
+                continue
+            post_chunks.append(bytes(chunk))
+            post_buffer.extend(chunk)
+            frames, remainder = decode_stream(remainder + chunk)
+            for frame in frames:
+                if frame.frame_type != FrameType.READY:
+                    continue
+                ready = decode_ready(frame)
+                if ready.build_id == build_id and _variant_matches(ready.variant, variant):
+                    accepted_frame = frame
+                    break
+            if accepted_frame is not None:
+                break
+        if accepted_frame is None:
+            raise TimeoutError("fresh matching READY was not observed after PROGRAM_SRAM")
+        if after_ready is not None:
+            command_result = after_ready(endpoint)
+            if isinstance(command_result, dict):
+                command_rx_wire = command_result.pop("_wire_raw", b"")
+                command_wire = bytes(command_result.pop("_wire_tx", b""))
+                if command_rx_wire:
+                    post_chunks.append(bytes(command_rx_wire))
+                    post_buffer.extend(command_rx_wire)
+            tail = _drain_available(endpoint)
+            if tail:
+                post_chunks.append(tail)
+                post_buffer.extend(tail)
+    finally:
+        endpoint.close()
+        combined = pre_program_raw + b"".join(post_chunks)
+        (output_dir / "pre-program.raw").write_bytes(pre_program_raw)
+        (output_dir / "post-program.raw").write_bytes(b"".join(post_chunks))
+        (output_dir / "combined-rx.raw").write_bytes(combined)
+        (output_dir / "host-command-wire.bin").write_bytes(command_wire)
+        transcript = _decode_records(pre_program_raw, phase="pre_program") + _decode_records(
+            b"".join(post_chunks), phase="post_program"
+        )
+        (output_dir / "wire-transcript.json").write_text(
+            json.dumps(transcript, indent=2, sort_keys=True) + "\n", encoding="utf-8"
+        )
+
+    ready = decode_ready(accepted_frame)
+    return {
+        "schema": "prod2u-p4-collector-v2",
+        "status": "pass",
+        "profile": PROFILE,
+        "profile_id": 4,
+        "protocol_version": 2,
+        "transport": {"port": PORT, "baud": BAUD, "data_bits": 8, "parity": "N", "stop_bits": 1},
+        "ready": {
+            "seq": accepted_frame.seq,
+            "build_id": f"{ready.build_id:08X}",
+            "variant_id": ready.variant,
+            "startup_reason": ready.startup_reason,
+            "startup_seq": ready.startup_seq,
+            "capability_flags": ready.capability_flags,
+            "variant": variant,
+            "fresh": True,
+        },
+        "programmer_receipt": programmer_receipt,
+        "command_result": command_result,
+        "post_program_chunks": post_chunks,
+        "bmc": {"status": "out_of_scope", "opened": False, "receipt_required": False},
+        "safety": {
+            "enumerates_com_ports": False,
+            "toggles_dtr_rts": False,
+            "flash_attempted": False,
+            "retry_count": 0,
+            "power_cycle_attempted": False,
+        },
+    }

+ 583 - 0
tools/prod2u_p4_protocol.py

@@ -0,0 +1,583 @@
+#!/usr/bin/env python3
+"""Prod2U Profile4 binary921 v2 wire protocol helpers.
+
+The module is intentionally free of serial I/O and clocks. Callers provide
+timestamps to the pure timeout-state functions so the same behavior can be
+used by collectors, replay tools, and deterministic tests.
+
+All multi-byte fields are little-endian. Payload layouts are:
+
+* HOST_CMD (4): cmd:u8, channel:u8, value:u8, flags:u8.
+* HOST_ACK (8): ok:u8, cmd:u8, status:u8, detail:u8, state_hash:u16,
+  response_type:u8, result_flags:u8. The envelope seq is the request seq.
+* READY (12): build_id:u32, variant:u8, startup_reason:u8, startup_seq:u8,
+  reserved:u8=0, capability_flags:u32.
+* STATUS_RESPONSE (24): status:u8, last_command_status:u8, flags:u8,
+  variant:u8, command_count:u16, reserved:u16=0,
+  watchdog_ticks_remaining:u32, tach_snapshot_seq:u32,
+  trace_drop_count:u32, parser_error_count:u32.
+* FAN_TELEMETRY (28): snapshot_seq:u32, window_ticks:u32,
+  overflow_mask:u8, fan_install_mask:u8, reserved:u16=0,
+  edge_counts[8]:u16. RPM is not carried on wire.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+from enum import IntEnum
+from typing import Iterable
+
+
+MAGIC = b"\xA5\x5A"
+VERSION = 2
+PROFILE_ID = 4
+HEADER_LEN = 14
+CRC_LEN = 2
+MAX_PAYLOAD_LEN = 255
+HOST_CMD_PAYLOAD_LEN = 4
+HOST_ACK_PAYLOAD_LEN = 8
+READY_PAYLOAD_LEN = 12
+STATUS_RESPONSE_PAYLOAD_LEN = 24
+FAN_TELEMETRY_PAYLOAD_LEN = 28
+FAN_CHANNEL_COUNT = 8
+COMMAND_TIMEOUT_US = 2_000
+
+
+class P4FrameError(ValueError):
+    """Raised when a Profile4 frame cannot be decoded safely."""
+
+
+class FrameType(IntEnum):
+    READY = 0x01
+    HOST_CMD = 0x05
+    HOST_ACK = 0x06
+    FAN_TELEMETRY = 0x0D
+    STATUS_RESPONSE = 0x0E
+    TRACE_SNAPSHOT = 0x0F
+
+
+class CommandId(IntEnum):
+    SET_PTC = 0x20
+    SET_FAN = 0x21
+    GET_SENSOR = 0x22
+    GET_MAP = 0x23
+    GET_STATUS = 0x24
+    SET_PID_REQUESTED = 0x25
+    DISABLE = 0x26
+    GET_FAN_TELEMETRY = 0x27
+
+
+class StatusCode(IntEnum):
+    OK = 0x00
+    UNSUPPORTED_IN_PROFILE = 0x01
+    BAD_FLAGS = 0x02
+    BAD_LENGTH = 0x03
+    BAD_CHANNEL = 0x04
+    BAD_VALUE = 0x05
+    SEQ_CONFLICT = 0x06
+    SEQ_JUMP = 0x07
+    QUEUE_FULL = 0x08
+
+
+class TimeoutPhase(IntEnum):
+    IDLE = 0
+    PENDING = 1
+    ACKED = 2
+    TIMED_OUT = 3
+
+
+@dataclass(frozen=True)
+class P4Frame:
+    version: int
+    profile_id: int
+    frame_type: FrameType
+    seq: int
+    timestamp_tick: int
+    payload: bytes
+    crc16: int
+    raw: bytes
+
+
+@dataclass(frozen=True)
+class HostCommand:
+    command: CommandId
+    channel: int
+    value: int
+    flags: int
+
+
+@dataclass(frozen=True)
+class HostAck:
+    ok: bool
+    command: CommandId
+    status: StatusCode
+    detail: int
+    state_hash16: int
+    response_type: FrameType | int
+    result_flags: int
+    request_seq: int | None
+
+
+@dataclass(frozen=True)
+class Ready:
+    build_id: int
+    variant: int
+    startup_reason: int
+    startup_seq: int
+    capability_flags: int
+
+
+@dataclass(frozen=True)
+class Status:
+    status: StatusCode
+    last_command_status: StatusCode
+    flags: int
+    variant: int
+    command_count: int
+    watchdog_ticks_remaining: int
+    tach_snapshot_seq: int
+    trace_drop_count: int
+    parser_error_count: int
+
+
+@dataclass(frozen=True)
+class RpmEstimate:
+    window_edges: int
+    rpm: int
+    calibrated: bool = False
+    calibration_status: str = "uncalibrated"
+
+
+@dataclass(frozen=True)
+class FanTelemetry:
+    snapshot_seq: int
+    window_ticks: int
+    overflow_mask: int
+    fan_install_mask: int
+    edge_counts: tuple[int, ...]
+    rpm: tuple[int, ...]
+    calibrated: bool = False
+    calibration_status: str = "uncalibrated"
+
+
+@dataclass(frozen=True)
+class CommandTimeoutState:
+    phase: TimeoutPhase = TimeoutPhase.IDLE
+    request_seq: int | None = None
+    started_at_us: int | None = None
+    deadline_us: int | None = None
+    completed_at_us: int | None = None
+
+
+def crc16_ccitt(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
+    """Return CRC-16/CCITT-FALSE for *data*."""
+    crc = initial & 0xFFFF
+    for byte in bytes(data):
+        crc ^= byte << 8
+        for _ in range(8):
+            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
+    return crc
+
+
+def _u8(value: int, name: str) -> int:
+    if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
+        raise ValueError(f"{name} must fit in one byte")
+    return value
+
+
+def _u16(value: int, name: str) -> int:
+    if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFF:
+        raise ValueError(f"{name} must fit in 16 bits")
+    return value
+
+
+def _u32(value: int, name: str) -> int:
+    if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFFFFFF:
+        raise ValueError(f"{name} must fit in 32 bits")
+    return value
+
+
+def encode_frame(
+    *,
+    frame_type: FrameType | int,
+    seq: int,
+    timestamp_tick: int,
+    payload: bytes | bytearray | Iterable[int],
+) -> bytes:
+    payload_bytes = bytes(payload)
+    if len(payload_bytes) > MAX_PAYLOAD_LEN:
+        raise ValueError("payload too long for binary921 v2")
+    try:
+        typed_frame = FrameType(int(frame_type))
+    except (TypeError, ValueError) as exc:
+        raise ValueError(f"unknown Profile4 frame type: {frame_type}") from exc
+    seq = _u32(seq, "seq")
+    timestamp_tick = _u32(timestamp_tick, "timestamp_tick")
+    body = bytes([VERSION, PROFILE_ID, int(typed_frame)])
+    body += seq.to_bytes(4, "little")
+    body += timestamp_tick.to_bytes(4, "little")
+    body += bytes([len(payload_bytes)]) + payload_bytes
+    return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
+
+
+def decode_frame(frame: bytes | bytearray) -> P4Frame:
+    raw = bytes(frame)
+    if len(raw) < HEADER_LEN:
+        raise P4FrameError("short Profile4 frame")
+    if raw[:2] != MAGIC:
+        raise P4FrameError("bad Profile4 magic")
+    if raw[2] != VERSION:
+        raise P4FrameError(f"unsupported binary921 version {raw[2]}")
+    if raw[3] != PROFILE_ID:
+        raise P4FrameError(f"unexpected binary921 profile {raw[3]}")
+    payload_len = raw[13]
+    expected_len = HEADER_LEN + payload_len + CRC_LEN
+    if len(raw) != expected_len:
+        raise P4FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}")
+    expected_crc = crc16_ccitt(raw[2:-2])
+    actual_crc = int.from_bytes(raw[-2:], "little")
+    if actual_crc != expected_crc:
+        raise P4FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}")
+    try:
+        frame_type = FrameType(raw[4])
+    except ValueError as exc:
+        raise P4FrameError(f"unknown Profile4 frame type 0x{raw[4]:02x}") from exc
+    return P4Frame(
+        version=raw[2],
+        profile_id=raw[3],
+        frame_type=frame_type,
+        seq=int.from_bytes(raw[5:9], "little"),
+        timestamp_tick=int.from_bytes(raw[9:13], "little"),
+        payload=raw[14:-2],
+        crc16=actual_crc,
+        raw=raw,
+    )
+
+
+def decode_stream(data: bytes | bytearray) -> tuple[list[P4Frame], bytes]:
+    """Decode all valid frames, skipping noise and corrupt complete frames."""
+    buf = bytes(data)
+    frames: list[P4Frame] = []
+    offset = 0
+    while True:
+        magic_at = buf.find(MAGIC, offset)
+        if magic_at < 0:
+            remaining = buf[offset:]
+            return frames, remaining[-1:] if remaining.endswith(MAGIC[:1]) else b""
+        if len(buf) - magic_at < HEADER_LEN + CRC_LEN:
+            return frames, buf[magic_at:]
+        end = magic_at + HEADER_LEN + buf[magic_at + 13] + CRC_LEN
+        if end > len(buf):
+            next_magic = buf.find(MAGIC, magic_at + 1)
+            if next_magic < 0:
+                return frames, buf[magic_at:]
+            offset = next_magic
+            continue
+        try:
+            frames.append(decode_frame(buf[magic_at:end]))
+            offset = end
+        except P4FrameError:
+            offset = magic_at + 1
+
+
+def _payload(value: P4Frame | bytes | bytearray, frame_type: FrameType, length: int, words: str) -> bytes:
+    if isinstance(value, P4Frame):
+        if value.frame_type != frame_type:
+            raise ValueError(f"expected {frame_type.name} frame")
+        payload = value.payload
+    else:
+        payload = bytes(value)
+    if len(payload) != length:
+        raise ValueError(f"{frame_type.name} payload must be exactly {words}")
+    return payload
+
+
+def build_host_command(
+    *,
+    seq: int,
+    command: CommandId | int,
+    channel: int = 0,
+    value: int = 0,
+    flags: int = 0,
+    timestamp_tick: int = 0,
+) -> bytes:
+    try:
+        command = CommandId(int(command))
+    except (TypeError, ValueError) as exc:
+        raise ValueError(f"unknown Profile4 command: {command}") from exc
+    payload = bytes([int(command), _u8(channel, "channel"), _u8(value, "value"), _u8(flags, "flags")])
+    return encode_frame(
+        frame_type=FrameType.HOST_CMD,
+        seq=seq,
+        timestamp_tick=timestamp_tick,
+        payload=payload,
+    )
+
+
+def decode_host_command(value: P4Frame | bytes | bytearray) -> HostCommand:
+    payload = _payload(value, FrameType.HOST_CMD, HOST_CMD_PAYLOAD_LEN, "four bytes")
+    try:
+        command = CommandId(payload[0])
+    except ValueError as exc:
+        raise ValueError(f"unknown Profile4 command: 0x{payload[0]:02x}") from exc
+    return HostCommand(command=command, channel=payload[1], value=payload[2], flags=payload[3])
+
+
+def build_host_ack(
+    *,
+    seq: int,
+    ok: bool,
+    command: CommandId | int,
+    status: StatusCode | int,
+    detail: int = 0,
+    state_hash16: int = 0,
+    response_type: FrameType | int = 0,
+    result_flags: int = 0,
+    timestamp_tick: int = 0,
+) -> bytes:
+    command = CommandId(int(command))
+    status = StatusCode(int(status))
+    if not isinstance(ok, bool):
+        raise ValueError("ok must be a bool")
+    payload = bytes([int(ok), int(command), int(status), _u8(detail, "detail")])
+    payload += _u16(state_hash16, "state_hash16").to_bytes(2, "little")
+    payload += bytes([_u8(int(response_type), "response_type"), _u8(result_flags, "result_flags")])
+    return encode_frame(
+        frame_type=FrameType.HOST_ACK,
+        seq=seq,
+        timestamp_tick=timestamp_tick,
+        payload=payload,
+    )
+
+
+def decode_host_ack(value: P4Frame | bytes | bytearray) -> HostAck:
+    request_seq = value.seq if isinstance(value, P4Frame) else None
+    payload = _payload(value, FrameType.HOST_ACK, HOST_ACK_PAYLOAD_LEN, "eight bytes")
+    if payload[0] not in (0, 1):
+        raise ValueError("HOST_ACK ok must be 0 or 1")
+    try:
+        command = CommandId(payload[1])
+        status = StatusCode(payload[2])
+    except ValueError as exc:
+        raise ValueError("HOST_ACK contains an unknown command or status") from exc
+    try:
+        response_type: FrameType | int = FrameType(payload[6])
+    except ValueError:
+        response_type = payload[6]
+    return HostAck(
+        ok=payload[0] == 1,
+        command=command,
+        status=status,
+        detail=payload[3],
+        state_hash16=int.from_bytes(payload[4:6], "little"),
+        response_type=response_type,
+        result_flags=payload[7],
+        request_seq=request_seq,
+    )
+
+
+def encode_ready(
+    *,
+    seq: int,
+    timestamp_tick: int,
+    build_id: int,
+    variant: int,
+    startup_reason: int,
+    startup_seq: int,
+    capability_flags: int,
+) -> bytes:
+    if variant not in (0, 1):
+        raise ValueError("variant must be 0 (normal) or 1 (trace)")
+    payload = _u32(build_id, "build_id").to_bytes(4, "little")
+    payload += bytes([_u8(variant, "variant")])
+    payload += bytes([_u8(startup_reason, "startup_reason")])
+    payload += bytes([_u8(startup_seq, "startup_seq"), 0])
+    payload += _u32(capability_flags, "capability_flags").to_bytes(4, "little")
+    return encode_frame(frame_type=FrameType.READY, seq=seq, timestamp_tick=timestamp_tick, payload=payload)
+
+
+def decode_ready(value: P4Frame | bytes | bytearray) -> Ready:
+    payload = _payload(value, FrameType.READY, READY_PAYLOAD_LEN, "twelve bytes")
+    if payload[7] != 0:
+        raise ValueError("READY reserved byte must be zero")
+    if payload[4] not in (0, 1):
+        raise ValueError("READY variant must be 0 (normal) or 1 (trace)")
+    return Ready(
+        build_id=int.from_bytes(payload[0:4], "little"),
+        variant=payload[4],
+        startup_reason=payload[5],
+        startup_seq=payload[6],
+        capability_flags=int.from_bytes(payload[8:12], "little"),
+    )
+
+
+def encode_status(
+    *,
+    seq: int,
+    timestamp_tick: int,
+    status: StatusCode | int,
+    last_command_status: StatusCode | int = StatusCode.OK,
+    flags: int = 0,
+    variant: int = 0,
+    command_count: int = 0,
+    watchdog_ticks_remaining: int = 0,
+    tach_snapshot_seq: int = 0,
+    trace_drop_count: int = 0,
+    parser_error_count: int = 0,
+) -> bytes:
+    status = StatusCode(int(status))
+    last_command_status = StatusCode(int(last_command_status))
+    if variant not in (0, 1):
+        raise ValueError("variant must be 0 (normal) or 1 (trace)")
+    payload = bytes(
+        [
+            int(status),
+            int(last_command_status),
+            _u8(flags, "flags"),
+            _u8(variant, "variant"),
+        ]
+    )
+    payload += _u16(command_count, "command_count").to_bytes(2, "little")
+    payload += b"\x00\x00"
+    payload += _u32(watchdog_ticks_remaining, "watchdog_ticks_remaining").to_bytes(4, "little")
+    payload += _u32(tach_snapshot_seq, "tach_snapshot_seq").to_bytes(4, "little")
+    payload += _u32(trace_drop_count, "trace_drop_count").to_bytes(4, "little")
+    payload += _u32(parser_error_count, "parser_error_count").to_bytes(4, "little")
+    return encode_frame(
+        frame_type=FrameType.STATUS_RESPONSE,
+        seq=seq,
+        timestamp_tick=timestamp_tick,
+        payload=payload,
+    )
+
+
+def decode_status(value: P4Frame | bytes | bytearray) -> Status:
+    payload = _payload(
+        value,
+        FrameType.STATUS_RESPONSE,
+        STATUS_RESPONSE_PAYLOAD_LEN,
+        "twenty-four bytes",
+    )
+    try:
+        status = StatusCode(payload[0])
+        last_command_status = StatusCode(payload[1])
+    except ValueError as exc:
+        raise ValueError("STATUS contains an unknown status code") from exc
+    if payload[6:8] != b"\x00\x00":
+        raise ValueError("STATUS_RESPONSE reserved bytes must be zero")
+    if payload[3] not in (0, 1):
+        raise ValueError("STATUS_RESPONSE variant must be 0 (normal) or 1 (trace)")
+    return Status(
+        status=status,
+        last_command_status=last_command_status,
+        flags=payload[2],
+        variant=payload[3],
+        command_count=int.from_bytes(payload[4:6], "little"),
+        watchdog_ticks_remaining=int.from_bytes(payload[8:12], "little"),
+        tach_snapshot_seq=int.from_bytes(payload[12:16], "little"),
+        trace_drop_count=int.from_bytes(payload[16:20], "little"),
+        parser_error_count=int.from_bytes(payload[20:24], "little"),
+    )
+
+
+def rpm_from_edges(window_edges: int) -> RpmEstimate:
+    edges = _u16(window_edges, "edges")
+    return RpmEstimate(window_edges=edges, rpm=edges * 30)
+
+
+def encode_fan_telemetry(
+    *,
+    seq: int,
+    timestamp_tick: int,
+    snapshot_seq: int,
+    window_ticks: int,
+    overflow_mask: int,
+    fan_install_mask: int,
+    edge_counts: Iterable[int],
+) -> bytes:
+    edges = tuple(edge_counts)
+    if len(edges) != FAN_CHANNEL_COUNT:
+        raise ValueError("FAN_TELEMETRY requires exactly eight edge counts")
+    checked_edges = tuple(_u16(edge, f"edge_counts[{index}]") for index, edge in enumerate(edges))
+    payload = _u32(snapshot_seq, "snapshot_seq").to_bytes(4, "little")
+    payload += _u32(window_ticks, "window_ticks").to_bytes(4, "little")
+    payload += bytes([_u8(overflow_mask, "overflow_mask")])
+    payload += bytes([_u8(fan_install_mask, "fan_install_mask")])
+    payload += b"\x00\x00"
+    payload += b"".join(edge.to_bytes(2, "little") for edge in checked_edges)
+    return encode_frame(
+        frame_type=FrameType.FAN_TELEMETRY,
+        seq=seq,
+        timestamp_tick=timestamp_tick,
+        payload=payload,
+    )
+
+
+def decode_fan_telemetry(value: P4Frame | bytes | bytearray) -> FanTelemetry:
+    payload = _payload(
+        value,
+        FrameType.FAN_TELEMETRY,
+        FAN_TELEMETRY_PAYLOAD_LEN,
+        "twenty-eight bytes",
+    )
+    if payload[10:12] != b"\x00\x00":
+        raise ValueError("FAN_TELEMETRY reserved bytes must be zero")
+    edge_counts = tuple(
+        int.from_bytes(payload[offset : offset + 2], "little")
+        for offset in range(12, FAN_TELEMETRY_PAYLOAD_LEN, 2)
+    )
+    return FanTelemetry(
+        snapshot_seq=int.from_bytes(payload[0:4], "little"),
+        window_ticks=int.from_bytes(payload[4:8], "little"),
+        overflow_mask=payload[8],
+        fan_install_mask=payload[9],
+        edge_counts=edge_counts,
+        rpm=tuple(edge * 30 for edge in edge_counts),
+    )
+
+
+def start_timeout(
+    state: CommandTimeoutState,
+    *,
+    request_seq: int,
+    now_us: int,
+    timeout_us: int = COMMAND_TIMEOUT_US,
+) -> CommandTimeoutState:
+    del state
+    request_seq = _u32(request_seq, "request_seq")
+    now_us = _nonnegative_time(now_us, "now_us")
+    timeout_us = _nonnegative_time(timeout_us, "timeout_us")
+    if timeout_us == 0:
+        raise ValueError("timeout_us must be positive")
+    return CommandTimeoutState(
+        phase=TimeoutPhase.PENDING,
+        request_seq=request_seq,
+        started_at_us=now_us,
+        deadline_us=now_us + timeout_us,
+    )
+
+
+def poll_timeout(state: CommandTimeoutState, *, now_us: int) -> CommandTimeoutState:
+    now_us = _nonnegative_time(now_us, "now_us")
+    if state.phase != TimeoutPhase.PENDING:
+        return state
+    if state.deadline_us is None:
+        raise ValueError("pending timeout state has no deadline")
+    if now_us < state.deadline_us:
+        return state
+    return replace(state, phase=TimeoutPhase.TIMED_OUT, completed_at_us=now_us)
+
+
+def observe_ack(state: CommandTimeoutState, *, request_seq: int, now_us: int) -> CommandTimeoutState:
+    request_seq = _u32(request_seq, "request_seq")
+    now_us = _nonnegative_time(now_us, "now_us")
+    checked = poll_timeout(state, now_us=now_us)
+    if checked.phase != TimeoutPhase.PENDING or checked.request_seq != request_seq:
+        return checked
+    return replace(checked, phase=TimeoutPhase.ACKED, completed_at_us=now_us)
+
+
+def _nonnegative_time(value: int, name: str) -> int:
+    if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+        raise ValueError(f"{name} must be a non-negative integer")
+    return value

+ 704 - 0
tools/prod2u_p4_validate.py

@@ -0,0 +1,704 @@
+#!/usr/bin/env python3
+"""Offline validator for the Prod2U P4 evidence, campaign, and final gate JSON."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import re
+import sys
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+
+SCHEMAS = {
+    "evidence": "prod2u-p4-evidence-v2",
+    "campaign": "prod2u-p4-campaign-v2",
+    "final_gate": "prod2u-p4-final-gate-v2",
+}
+FAN_STATUSES = {"detected", "absent", "intermittent"}
+LAYER_STATUSES = {"pass", "fail", "blocked", "not_run"}
+SPEARMAN_MIN = 0.60
+ROUND_COUNT = 10
+FAN_SETTINGS = (0, 20, 40, 60, 80, 100)
+TREND_SETTINGS = (20, 40, 60, 80, 100)
+LOW_SETTINGS = (20, 40)
+HIGH_SETTINGS = (80, 100)
+SAMPLES_PER_SETTING = 5
+SETTLE_WINDOWS_PER_SETTING = 2
+WINDOWS_PER_ROUND = len(FAN_SETTINGS) * (SAMPLES_PER_SETTING + SETTLE_WINDOWS_PER_SETTING)
+REQUIRED_DYNAMIC_LAYERS = (
+    "program_sram",
+    "fresh_ready",
+    "host_ack",
+    "pwm_state",
+    "fan3_tach_trend",
+    "timeout_fallback",
+    "disable",
+    "ptc_command_path",
+)
+REQUIRED_STATIC_LAYERS = (
+    "source",
+    "protocol",
+    "rtl",
+    "formal",
+    "td_normal",
+    "td_trace",
+    "package",
+)
+STATIC_LAYER_ARTIFACTS = {
+    "source": ("normal_source_manifest", "trace_source_manifest"),
+    "protocol": ("protocol_junit",),
+    "rtl": ("rtl_sim_receipt",),
+    "formal": ("formal_receipt",),
+    "td_normal": ("normal_td_receipt",),
+    "td_trace": ("trace_td_receipt",),
+    "package": ("package_manifest", "package_inventory", "static_receipt"),
+}
+SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
+IDENTITY_FIELDS = ("dut_id", "build_id", "bitstream_sha256", "variant", "profile", "source_manifest_sha256")
+BOUND_ARTIFACTS = (
+    "programmer_receipt",
+    "pre_program_raw",
+    "combined_rx_raw",
+    "raw_transcript",
+    "td_receipt",
+    "source_manifest",
+    "package_manifest",
+    "package_inventory",
+)
+EVIDENCE_REQUIRED = (
+    "schema",
+    "evidence_id",
+    "campaign_id",
+    "campaign_identity",
+    "round",
+    "identity",
+    "bmc",
+    "layers",
+    "fan",
+    "windows",
+    "raw_samples",
+    "correlation",
+    "rpm",
+    "ptc",
+    "evidence_binding",
+)
+FINAL_GATE_REQUIRED = (
+    "schema",
+    "status",
+    "campaign_id",
+    "campaign_identity",
+    "bmc",
+    "qualification",
+    "layers",
+    "round_count",
+    "evidence_bindings",
+    "failures",
+)
+
+
+def _mapping(value: Any) -> Mapping[str, Any]:
+    return value if isinstance(value, Mapping) else {}
+
+
+def _number(value: Any) -> float | None:
+    if isinstance(value, bool) or not isinstance(value, (int, float)):
+        return None
+    result = float(value)
+    return result if math.isfinite(result) else None
+
+
+def _rank(values: Sequence[float]) -> list[float]:
+    ordered = sorted((value, index) for index, value in enumerate(values))
+    ranks = [0.0] * len(values)
+    position = 0
+    while position < len(ordered):
+        end = position + 1
+        while end < len(ordered) and ordered[end][0] == ordered[position][0]:
+            end += 1
+        average = (position + 1 + end) / 2.0
+        for _, index in ordered[position:end]:
+            ranks[index] = average
+        position = end
+    return ranks
+
+
+def spearman_rho(x_values: Sequence[float], y_values: Sequence[float]) -> float | None:
+    """Return Spearman rank correlation without scipy or another dependency."""
+    if len(x_values) != len(y_values) or len(x_values) < 2:
+        return None
+    x_rank = _rank(x_values)
+    y_rank = _rank(y_values)
+    x_mean = sum(x_rank) / len(x_rank)
+    y_mean = sum(y_rank) / len(y_rank)
+    numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_rank, y_rank))
+    x_denominator = math.sqrt(sum((x - x_mean) ** 2 for x in x_rank))
+    y_denominator = math.sqrt(sum((y - y_mean) ** 2 for y in y_rank))
+    if x_denominator == 0 or y_denominator == 0:
+        return None
+    return numerator / (x_denominator * y_denominator)
+
+
+def _validate_layers(layers: Any, round_number: int | None = None) -> list[str]:
+    failures: list[str] = []
+    payload = _mapping(layers)
+    required = _mapping(payload.get("required"))
+    optional = _mapping(payload.get("optional"))
+    prefix = f"{round_number}:" if round_number is not None else ""
+    if not required:
+        failures.append(f"required_layers_missing:{prefix[:-1] if prefix else 'campaign'}")
+    for name in REQUIRED_DYNAMIC_LAYERS:
+        if name not in required:
+            failures.append(f"required_layer_missing:{prefix}{name}" if prefix else f"required_layer_missing:campaign:{name}")
+    for name, status in required.items():
+        if status not in LAYER_STATUSES:
+            failures.append(f"invalid_layer_status:{prefix}{name}")
+        elif status != "pass":
+            failures.append(f"required_layer_not_pass:{prefix}{name}")
+    for name, status in optional.items():
+        if status not in LAYER_STATUSES:
+            failures.append(f"invalid_optional_layer_status:{prefix}{name}")
+    return failures
+
+
+def _validate_windows(windows: Any, round_number: int) -> list[str]:
+    failures: list[str] = []
+    if not isinstance(windows, list) or not windows:
+        return [f"windows_missing:{round_number}"]
+    if len(windows) != WINDOWS_PER_ROUND:
+        failures.append(f"windows_count:{round_number}:{len(windows)}")
+    previous_end: float | None = None
+    previous_index: int | None = None
+    previous_snapshot_seq: int | None = None
+    for expected_index, item in enumerate(windows):
+        window = _mapping(item)
+        index = window.get("index", window.get("window_index"))
+        start = _number(window.get("start_s"))
+        end = _number(window.get("end_s"))
+        continuous = window.get("continuous")
+        snapshot_seq = window.get("snapshot_seq")
+        overflow_mask = window.get("overflow_mask")
+        if not isinstance(index, int) or isinstance(index, bool) or start is None or end is None or end <= start:
+            failures.append(f"invalid_window:{round_number}")
+            continue
+        if continuous is not True or (previous_end is not None and not math.isclose(start, previous_end, abs_tol=1e-9)):
+            failures.append(f"window_not_continuous:{round_number}")
+        if index != expected_index or (previous_index is not None and index != previous_index + 1):
+            failures.append(f"window_index_not_contiguous:{round_number}")
+        if not isinstance(snapshot_seq, int) or isinstance(snapshot_seq, bool) or not 0 <= snapshot_seq <= 0xFFFFFFFF:
+            failures.append(f"window_snapshot_seq_invalid:{round_number}:{expected_index}")
+        elif previous_snapshot_seq is not None and snapshot_seq != ((previous_snapshot_seq + 1) & 0xFFFFFFFF):
+            failures.append(f"window_snapshot_seq_not_contiguous:{round_number}")
+        if not isinstance(overflow_mask, int) or isinstance(overflow_mask, bool) or not 0 <= overflow_mask <= 0xFF:
+            failures.append(f"window_overflow_mask_invalid:{round_number}:{expected_index}")
+        previous_end = end
+        previous_index = index
+        if isinstance(snapshot_seq, int) and not isinstance(snapshot_seq, bool):
+            previous_snapshot_seq = snapshot_seq
+    return list(dict.fromkeys(failures))
+
+
+def _validate_correlation(correlation: Any, round_number: int) -> list[str]:
+    failures: list[str] = []
+    payload = _mapping(correlation)
+    samples = payload.get("samples")
+    if not isinstance(samples, list) or len(samples) != len(FAN_SETTINGS):
+        failures.append(f"trend_samples_must_cover_all_settings:{round_number}")
+        samples = []
+    by_setting: dict[float, float] = {}
+    for sample in samples:
+        row = _mapping(sample)
+        x = _number(row.get("fan_setting_percent", row.get("fan_percent")))
+        y = _number(row.get("rpm"))
+        if x is None or y is None:
+            failures.append(f"invalid_correlation_sample:{round_number}")
+            continue
+        if x in by_setting:
+            failures.append(f"duplicate_correlation_setting:{round_number}:{int(x)}")
+        by_setting[x] = y
+    if tuple(by_setting) != FAN_SETTINGS:
+        failures.append(f"trend_settings_must_be_0_20_40_60_80_100:{round_number}")
+
+    x_values = [float(setting) for setting in TREND_SETTINGS if float(setting) in by_setting]
+    y_values = [by_setting[setting] for setting in x_values]
+    computed = spearman_rho(x_values, y_values) if len(x_values) == len(TREND_SETTINGS) else None
+    declared = _number(payload.get("spearman_rho"))
+    if computed is None:
+        failures.append(f"spearman_not_computable:{round_number}")
+    elif declared is None:
+        failures.append(f"spearman_declared_missing:{round_number}")
+    elif not math.isclose(declared, computed, abs_tol=1e-6):
+        failures.append(f"spearman_declared_mismatch:{round_number}")
+    if computed is None or computed < SPEARMAN_MIN:
+        failures.append(f"spearman_below_threshold:{round_number}")
+    low = _number(payload.get("low_mean_rpm"))
+    high = _number(payload.get("high_mean_rpm"))
+    expected_low = (
+        sum(by_setting[float(setting)] for setting in LOW_SETTINGS) / len(LOW_SETTINGS)
+        if all(float(setting) in by_setting for setting in LOW_SETTINGS)
+        else None
+    )
+    expected_high = (
+        sum(by_setting[float(setting)] for setting in HIGH_SETTINGS) / len(HIGH_SETTINGS)
+        if all(float(setting) in by_setting for setting in HIGH_SETTINGS)
+        else None
+    )
+    if low is None or expected_low is None or not math.isclose(low, expected_low, abs_tol=1e-9):
+        failures.append(f"low_setting_mean_mismatch:{round_number}")
+    if high is None or expected_high is None or not math.isclose(high, expected_high, abs_tol=1e-9):
+        failures.append(f"high_setting_mean_mismatch:{round_number}")
+    significant = payload.get("high_significantly_higher") is True
+    if expected_low is None or expected_high is None or not significant or expected_high < expected_low + max(100.0, expected_low * 0.10):
+        failures.append(f"high_setting_not_significantly_higher:{round_number}")
+    return failures
+
+
+def _validate_raw_samples(raw_samples: Any, fan3: Mapping[str, Any], round_number: int) -> list[str]:
+    failures: list[str] = []
+    expected_total = len(FAN_SETTINGS) * SAMPLES_PER_SETTING
+    if not isinstance(raw_samples, list):
+        return [f"raw_samples_missing:{round_number}"]
+    if len(raw_samples) != expected_total:
+        failures.append(f"raw_samples_count:{round_number}:{len(raw_samples)}")
+
+    rows_by_setting: dict[int, list[Mapping[str, Any]]] = {setting: [] for setting in FAN_SETTINGS}
+    valid_rows: list[Mapping[str, Any]] = []
+    for row_index, item in enumerate(raw_samples):
+        row = _mapping(item)
+        setting = row.get("fan_setting_percent")
+        if not isinstance(setting, int) or isinstance(setting, bool) or setting not in rows_by_setting:
+            failures.append(f"raw_sample_setting_invalid:{round_number}:{row_index}")
+        else:
+            rows_by_setting[setting].append(row)
+
+        snapshot_seq = row.get("snapshot_seq")
+        if not isinstance(snapshot_seq, int) or isinstance(snapshot_seq, bool) or snapshot_seq < 0:
+            failures.append(f"snapshot_seq_invalid:{round_number}:{row_index}")
+
+        overflow_mask = row.get("overflow_mask")
+        if not isinstance(overflow_mask, int) or isinstance(overflow_mask, bool) or not 0 <= overflow_mask <= 0xFF:
+            failures.append(f"overflow_mask_invalid:{round_number}:{row_index}")
+
+        for signal in ("FG5", "FG6"):
+            channel = _mapping(row.get(signal))
+            edges = channel.get("window_edges")
+            if not isinstance(edges, int) or isinstance(edges, bool) or edges < 0:
+                failures.append(f"window_edges_invalid:{round_number}:{row_index}:{signal}")
+        valid_rows.append(row)
+
+    for setting in FAN_SETTINGS:
+        count = len(rows_by_setting[setting])
+        if count != SAMPLES_PER_SETTING:
+            failures.append(f"raw_samples_setting_count:{round_number}:{setting}:{count}")
+
+    for setting, setting_rows in rows_by_setting.items():
+        setting_sequences = [
+            row.get("snapshot_seq")
+            for row in setting_rows
+            if isinstance(row.get("snapshot_seq"), int) and not isinstance(row.get("snapshot_seq"), bool)
+        ]
+        if len(setting_sequences) == SAMPLES_PER_SETTING:
+            for previous, current in zip(setting_sequences, setting_sequences[1:]):
+                if current != ((previous + 1) & 0xFFFFFFFF):
+                    failures.append(f"snapshot_seq_not_contiguous:{round_number}")
+                    break
+
+    computed_statuses: dict[str, str] = {}
+    for signal, bit_index in (("FG5", 4), ("FG6", 5)):
+        nonzero_counts = []
+        high_edges: list[int] = []
+        for setting in HIGH_SETTINGS:
+            edges = [
+                int(_mapping(row.get(signal)).get("window_edges", 0))
+                for row in rows_by_setting[setting]
+                if isinstance(_mapping(row.get(signal)).get("window_edges"), int)
+                and not isinstance(_mapping(row.get(signal)).get("window_edges"), bool)
+            ]
+            high_edges.extend(edges)
+            nonzero_counts.append(sum(value > 0 for value in edges))
+        if any(count >= 4 for count in nonzero_counts):
+            computed = "detected"
+        elif len(high_edges) == len(HIGH_SETTINGS) * SAMPLES_PER_SETTING and all(value == 0 for value in high_edges):
+            computed = "absent"
+        else:
+            computed = "intermittent"
+        computed_statuses[signal] = computed
+
+        declared = fan3.get(signal)
+        if declared in FAN_STATUSES and declared != computed:
+            failures.append(f"fan_status_mismatch:{round_number}:FAN3:{signal}:{computed}")
+        if computed == "detected" and any(
+            isinstance(row.get("overflow_mask"), int) and row["overflow_mask"] & (1 << bit_index)
+            for row in valid_rows
+        ):
+            failures.append(f"detected_channel_overflow:{round_number}:{signal}")
+
+    if "detected" not in computed_statuses.values():
+        failures.append(f"fan3_signal_not_detected:{round_number}")
+    return failures
+
+
+def _validate_binding_artifact(binding: Any, name: str, round_number: int) -> list[str]:
+    failures: list[str] = []
+    payload = _mapping(binding)
+    if not payload:
+        return [f"missing_binding:{name}:{round_number}"]
+    path = payload.get("path")
+    digest = payload.get("sha256")
+    if not isinstance(path, str) or not path:
+        failures.append(f"binding_path_invalid:{round_number}:{name}")
+    if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
+        failures.append(f"binding_sha256_invalid:{round_number}:{name}")
+    if name == "programmer_receipt" and payload.get("status") != "pass":
+        failures.append(f"programmer_receipt_not_pass:{round_number}")
+    receipt = payload.get("receipt")
+    if isinstance(receipt, Mapping) and receipt.get("status") != "pass":
+        failures.append(f"programmer_receipt_payload_not_pass:{round_number}")
+    return failures
+
+
+def _validate_static_qualification(qualification: Any) -> list[str]:
+    failures: list[str] = []
+    payload = _mapping(qualification)
+    if not payload:
+        return ["static_qualification_missing"]
+    if payload.get("schema") != "prod2u-p4-static-qualification-v1":
+        failures.append("static_qualification_schema_mismatch")
+    if payload.get("status") != "pass":
+        failures.append("static_qualification_not_pass")
+    if payload.get("profile") != "prod2u-fan-tach-binary921-v2" or payload.get("profile_id") != 4:
+        failures.append("static_qualification_profile_mismatch")
+    declared_failures = payload.get("failures")
+    if not isinstance(declared_failures, list):
+        failures.append("static_qualification_failures_invalid")
+    elif declared_failures:
+        failures.append("static_qualification_declares_failures")
+    layers = _mapping(payload.get("layers"))
+    for layer_name in REQUIRED_STATIC_LAYERS:
+        layer = _mapping(layers.get(layer_name))
+        if not layer:
+            failures.append(f"static_layer_missing:{layer_name}")
+            continue
+        if layer.get("status") != "pass":
+            failures.append(f"static_layer_not_pass:{layer_name}")
+        artifacts = _mapping(layer.get("artifacts"))
+        for artifact_name in STATIC_LAYER_ARTIFACTS[layer_name]:
+            if artifact_name not in artifacts:
+                failures.append(f"static_artifact_missing:{layer_name}:{artifact_name}")
+                continue
+            for failure in _validate_binding_artifact(artifacts.get(artifact_name), artifact_name, 0):
+                failures.append(f"static_{failure}")
+    return failures
+
+
+def _qualification_artifact_sha256(qualification: Any, layer: str, artifact: str) -> str | None:
+    payload = _mapping(qualification)
+    layer_payload = _mapping(_mapping(payload.get("layers")).get(layer))
+    artifact_payload = _mapping(_mapping(layer_payload.get("artifacts")).get(artifact))
+    digest = artifact_payload.get("sha256")
+    return str(digest).casefold() if isinstance(digest, str) and SHA256_RE.fullmatch(digest) else None
+
+
+def _validate_qualification_binding(
+    qualification: Any,
+    evidence_binding: Any,
+    variant: Any,
+    round_number: int,
+) -> list[str]:
+    failures: list[str] = []
+    binding = _mapping(evidence_binding)
+    if variant not in {"normal", "trace"}:
+        return [f"qualification_binding_variant_invalid:{round_number}"]
+    expected = {
+        "source_manifest": _qualification_artifact_sha256(
+            qualification, "source", f"{variant}_source_manifest"
+        ),
+        "td_receipt": _qualification_artifact_sha256(
+            qualification, f"td_{variant}", f"{variant}_td_receipt"
+        ),
+        "package_manifest": _qualification_artifact_sha256(
+            qualification, "package", "package_manifest"
+        ),
+        "package_inventory": _qualification_artifact_sha256(
+            qualification, "package", "package_inventory"
+        ),
+    }
+    for artifact_name, expected_hash in expected.items():
+        actual_hash = _mapping(binding.get(artifact_name)).get("sha256")
+        if expected_hash is None or not isinstance(actual_hash, str) or actual_hash.casefold() != expected_hash:
+            failures.append(f"qualification_binding_mismatch:{round_number}:{artifact_name}")
+    return failures
+
+
+def _validate_evidence_binding(binding: Any, identity: Mapping[str, Any], round_number: int) -> list[str]:
+    failures: list[str] = []
+    payload = _mapping(binding)
+    if not payload:
+        return [f"missing_required:evidence:evidence_binding:{round_number}"]
+    for name in BOUND_ARTIFACTS:
+        failures.extend(_validate_binding_artifact(payload.get(name), name, round_number))
+    bound_identity = _mapping(payload.get("identity"))
+    if not bound_identity:
+        failures.append(f"binding_identity_missing:{round_number}")
+    variant_identity = _mapping(identity.get("variants")).get(bound_identity.get("variant"))
+    for name in IDENTITY_FIELDS:
+        expected = identity.get(name)
+        if name in ("build_id", "bitstream_sha256") and isinstance(variant_identity, Mapping):
+            expected = variant_identity.get(name, expected)
+        if name in identity and expected is not None and bound_identity.get(name) != expected:
+            failures.append(f"binding_identity_mismatch:{round_number}:{name}")
+    source_manifest = _mapping(payload.get("source_manifest"))
+    expected_source_hash = identity.get("source_manifest_sha256")
+    if expected_source_hash:
+        declared_source_hash = source_manifest.get("declared_sha256")
+        if declared_source_hash is not None:
+            if declared_source_hash != expected_source_hash:
+                failures.append(f"source_manifest_binding_mismatch:{round_number}")
+        elif source_manifest.get("sha256") != expected_source_hash:
+            failures.append(f"source_manifest_binding_mismatch:{round_number}")
+    return failures
+
+
+def validate_evidence(evidence: Mapping[str, Any]) -> dict[str, Any]:
+    failures: list[str] = []
+    failures.extend(f"missing_required:evidence:{name}" for name in EVIDENCE_REQUIRED if name not in evidence)
+    if evidence.get("schema") != SCHEMAS["evidence"]:
+        failures.append("schema_mismatch")
+    round_number = evidence.get("round")
+    if not isinstance(round_number, int) or isinstance(round_number, bool) or not 1 <= round_number <= ROUND_COUNT:
+        failures.append("round_invalid")
+        round_number = 0
+    if _mapping(evidence.get("bmc")).get("status") != "out_of_scope":
+        failures.append("bmc_must_be_out_of_scope")
+    actual_identity = _mapping(evidence.get("identity"))
+    for name in IDENTITY_FIELDS:
+        if not actual_identity.get(name):
+            failures.append(f"identity_field_missing:{round_number}:{name}")
+    if evidence.get("variant") is not None and evidence.get("variant") != actual_identity.get("variant"):
+        failures.append(f"variant_identity_mismatch:{round_number}")
+    failures.extend(_validate_layers(evidence.get("layers"), round_number))
+    fan3 = _mapping(_mapping(evidence.get("fan")).get("FAN3"))
+    for signal in ("FG5", "FG6"):
+        if fan3.get(signal) not in FAN_STATUSES:
+            failures.append(f"invalid_fan_status:{round_number}:FAN3:{signal}")
+    failures.extend(_validate_windows(evidence.get("windows"), round_number))
+    failures.extend(_validate_raw_samples(evidence.get("raw_samples"), fan3, round_number))
+    failures.extend(_validate_correlation(evidence.get("correlation"), round_number))
+    if _mapping(evidence.get("rpm")).get("status") != "not_qualified":
+        failures.append(f"rpm_not_qualified:{round_number}")
+    ptc = _mapping(evidence.get("ptc"))
+    if ptc.get("actuation") is not True:
+        failures.append(f"ptc_actuation_must_be_true:{round_number}")
+    if ptc.get("measurement") != "not_run":
+        failures.append(f"ptc_measurement_must_be_not_run:{round_number}")
+    failures.extend(_validate_evidence_binding(evidence.get("evidence_binding"), actual_identity, round_number))
+    return {
+        "status": "pass" if not failures else "fail",
+        "round": round_number,
+        "failures": list(dict.fromkeys(failures)),
+    }
+
+
+def _identity_failures(expected: Mapping[str, Any], actual: Mapping[str, Any], round_number: int) -> list[str]:
+    failures: list[str] = []
+    for name in ("dut_id", "profile"):
+        if actual.get(name) != expected.get(name):
+            failures.append(f"identity_mismatch:{round_number}:{name}")
+    variant_identity = _mapping(expected.get("variants")).get(actual.get("variant"))
+    for name in ("build_id", "bitstream_sha256", "source_manifest_sha256"):
+        expected_value = expected.get(name)
+        if name in ("build_id", "bitstream_sha256") and isinstance(variant_identity, Mapping):
+            expected_value = variant_identity.get(name, expected_value)
+        if expected_value is not None and actual.get(name) != expected_value:
+            failures.append(f"identity_mismatch:{round_number}:{name}")
+    return failures
+
+
+def validate_campaign(campaign: Mapping[str, Any]) -> dict[str, Any]:
+    failures: list[str] = []
+    if campaign.get("schema") != SCHEMAS["campaign"]:
+        failures.append("schema_mismatch")
+    campaign_identity = _mapping(campaign.get("campaign_identity"))
+    if campaign_identity.get("planned_rounds") != ROUND_COUNT:
+        failures.append("planned_rounds_must_be_10")
+    if _mapping(campaign.get("bmc")).get("status") != "out_of_scope":
+        failures.append("bmc_must_be_out_of_scope")
+    qualification = campaign.get("qualification")
+    failures.extend(_validate_static_qualification(qualification))
+    evidence_bindings = campaign.get("evidence_bindings")
+    if not isinstance(evidence_bindings, list) or len(evidence_bindings) != ROUND_COUNT:
+        failures.append("evidence_bindings_must_contain_10_rounds")
+    if "layers" in campaign:
+        failures.extend(_validate_layers(campaign.get("layers")))
+    rounds = campaign.get("rounds")
+    if not isinstance(rounds, list) or len(rounds) != ROUND_COUNT:
+        failures.append("round_count_must_be_10")
+        rounds = rounds if isinstance(rounds, list) else []
+    numbers = [round_item.get("round") for round_item in rounds if isinstance(round_item, Mapping)]
+    if numbers != list(range(1, ROUND_COUNT + 1)):
+        failures.append("round_sequence_not_1_to_10")
+    for position, round_item in enumerate(rounds, start=1):
+        if not isinstance(round_item, Mapping):
+            failures.append(f"round_not_object:{position}")
+            continue
+        round_number = round_item.get("round", position)
+        result = validate_evidence(
+            {
+                **round_item,
+                "schema": SCHEMAS["evidence"],
+                "evidence_id": f"{campaign.get('campaign_id', 'campaign')}-R{position:02d}",
+                "campaign_id": campaign.get("campaign_id"),
+                "campaign_identity": campaign_identity,
+                "bmc": campaign.get("bmc"),
+            }
+        )
+        failures.extend(result["failures"])
+        failures.extend(_identity_failures(campaign_identity, _mapping(round_item.get("identity")), position))
+        failures.extend(
+            _validate_qualification_binding(
+                qualification,
+                round_item.get("evidence_binding"),
+                _mapping(round_item.get("identity")).get("variant"),
+                position,
+            )
+        )
+        if round_item.get("variant") is not None and round_item.get("variant") != _mapping(round_item.get("identity")).get("variant"):
+            failures.append(f"variant_identity_mismatch:{position}")
+    if isinstance(evidence_bindings, list) and len(evidence_bindings) == ROUND_COUNT:
+        for position, item in enumerate(evidence_bindings, start=1):
+            wrapper = _mapping(item)
+            if wrapper.get("round") != position:
+                failures.append(f"evidence_binding_round_mismatch:{position}")
+            round_item = rounds[position - 1] if position <= len(rounds) and isinstance(rounds[position - 1], Mapping) else {}
+            expected_binding = _mapping(round_item.get("evidence_binding"))
+            if wrapper.get("evidence_binding") != expected_binding:
+                failures.append(f"evidence_binding_not_preserved:{position}")
+    return {
+        "status": "pass" if not failures else "fail",
+        "campaign_id": campaign.get("campaign_id"),
+        "round_count": len(rounds),
+        "bmc": _mapping(campaign.get("bmc")).get("status"),
+        "failures": list(dict.fromkeys(failures)),
+    }
+
+
+def validate_final_gate(gate: Mapping[str, Any]) -> dict[str, Any]:
+    failures: list[str] = []
+    failures.extend(f"missing_required:final_gate:{name}" for name in FINAL_GATE_REQUIRED if name not in gate)
+    if gate.get("schema") != SCHEMAS["final_gate"]:
+        failures.append("schema_mismatch")
+    if _mapping(gate.get("bmc")).get("status") != "out_of_scope":
+        failures.append("bmc_must_be_out_of_scope")
+    qualification = gate.get("qualification")
+    failures.extend(_validate_static_qualification(qualification))
+    failures.extend(_validate_layers(gate.get("layers")))
+    if gate.get("round_count") != ROUND_COUNT:
+        failures.append("round_count_must_be_10")
+    declared = gate.get("failures")
+    if not isinstance(declared, list):
+        failures.append("failures_must_be_array")
+    elif gate.get("status") == "pass" and declared:
+        failures.append("pass_gate_has_failures")
+    bindings = gate.get("evidence_bindings")
+    if not isinstance(bindings, list) or len(bindings) != ROUND_COUNT:
+        failures.append("evidence_bindings_must_contain_10_rounds")
+    else:
+        gate_identity = _mapping(gate.get("campaign_identity"))
+        for position, item in enumerate(bindings, start=1):
+            wrapper = _mapping(item)
+            if wrapper.get("round") != position:
+                failures.append(f"evidence_binding_round_mismatch:{position}")
+            failures.extend(_validate_evidence_binding(wrapper.get("evidence_binding"), gate_identity, position))
+            binding_identity = _mapping(_mapping(wrapper.get("evidence_binding")).get("identity"))
+            failures.extend(
+                _validate_qualification_binding(
+                    qualification,
+                    wrapper.get("evidence_binding"),
+                    binding_identity.get("variant"),
+                    position,
+                )
+            )
+    if gate.get("status") == "pass" and failures:
+        failures.append("final_gate_pass_inconsistent")
+    return {
+        "status": "pass" if not failures else "fail",
+        "campaign_id": gate.get("campaign_id"),
+        "bmc": _mapping(gate.get("bmc")).get("status"),
+        "failures": list(dict.fromkeys(failures)),
+    }
+
+
+def build_final_gate(campaign: Mapping[str, Any]) -> dict[str, Any]:
+    """Build the strict P4 final-gate document without performing live I/O."""
+    campaign_result = validate_campaign(campaign)
+    rounds = campaign.get("rounds") if isinstance(campaign.get("rounds"), list) else []
+    required_layers: dict[str, str] = {}
+    optional_layers: dict[str, str] = {}
+    for round_item in rounds:
+        layers = _mapping(round_item.get("layers")) if isinstance(round_item, Mapping) else {}
+        for name, status in _mapping(layers.get("required")).items():
+            if name not in required_layers:
+                required_layers[name] = status
+            elif required_layers[name] != "pass" or status != "pass":
+                required_layers[name] = "fail"
+        for name, status in _mapping(layers.get("optional")).items():
+            if name not in optional_layers:
+                optional_layers[name] = status
+    bindings = campaign.get("evidence_bindings")
+    if not isinstance(bindings, list):
+        bindings = []
+    return {
+        "schema": SCHEMAS["final_gate"],
+        "status": "pass" if campaign_result["status"] == "pass" else "fail",
+        "campaign_id": campaign.get("campaign_id"),
+        "campaign_identity": _mapping(campaign.get("campaign_identity")),
+        "bmc": _mapping(campaign.get("bmc")),
+        "qualification": _mapping(campaign.get("qualification")),
+        "layers": {"required": required_layers, "optional": optional_layers},
+        "round_count": len(rounds),
+        "evidence_bindings": bindings,
+        "failures": list(campaign_result["failures"]),
+        "summary": {"campaign_status": campaign_result["status"], "round_count": len(rounds)},
+    }
+
+
+def load_json(source: str | Path | Mapping[str, Any]) -> Mapping[str, Any]:
+    if isinstance(source, Mapping):
+        return source
+    payload = json.loads(Path(source).read_text(encoding="utf-8-sig"))
+    if not isinstance(payload, Mapping):
+        raise ValueError("document must be a JSON object")
+    return payload
+
+
+def validate_document(source: str | Path | Mapping[str, Any], kind: str | None = None) -> dict[str, Any]:
+    document = load_json(source)
+    selected = kind
+    if selected is None:
+        selected = next((name for name, schema_id in SCHEMAS.items() if document.get("schema") == schema_id), None)
+    if selected == "evidence":
+        return validate_evidence(document)
+    if selected == "campaign":
+        return validate_campaign(document)
+    if selected == "final_gate":
+        return validate_final_gate(document)
+    return {"status": "fail", "failures": ["unknown_schema"]}
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("document", type=Path)
+    parser.add_argument("--kind", choices=sorted(SCHEMAS), help="document kind; inferred from schema when omitted")
+    args = parser.parse_args(argv)
+    try:
+        result = validate_document(args.document, args.kind)
+    except (OSError, ValueError, json.JSONDecodeError) as exc:
+        result = {"status": "fail", "failures": [f"input_error:{exc}"]}
+    print(json.dumps(result, ensure_ascii=True, sort_keys=True))
+    return 0 if result.get("status") == "pass" else 1
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 590 - 93
tools/prod2u_programmer.py

@@ -5,14 +5,18 @@ from __future__ import annotations
 
 
 import argparse
 import argparse
 import ctypes
 import ctypes
+import getpass
 import hashlib
 import hashlib
 import json
 import json
+import locale
 import ntpath
 import ntpath
 import os
 import os
 import re
 import re
 import shutil
 import shutil
 import subprocess
 import subprocess
+import tempfile
 import time
 import time
+from ctypes import wintypes
 from datetime import datetime, timezone
 from datetime import datetime, timezone
 from pathlib import Path
 from pathlib import Path
 from typing import Any, Callable
 from typing import Any, Callable
@@ -61,6 +65,13 @@ PROGRAM_RE = re.compile(
 PROGRAM_TIMEOUT_SECONDS = 60
 PROGRAM_TIMEOUT_SECONDS = 60
 PROCESS_CLEANUP_WAIT_SECONDS = 5.0
 PROCESS_CLEANUP_WAIT_SECONDS = 5.0
 MUTEX_NAME = r"Global\Prod2UProgramSram"
 MUTEX_NAME = r"Global\Prod2UProgramSram"
+TD_PROCESS_EXECUTABLES = (
+    "td.exe",
+    "td_commands_prompt.exe",
+    "bw.exe",
+    "bw_commands_prompt.exe",
+    "hwserver.exe",
+)
 
 
 
 
 def utc_now() -> str:
 def utc_now() -> str:
@@ -156,84 +167,429 @@ class WindowsNamedMutex:
         return False
         return False
 
 
 
 
-def close_td_processes(td_root: Path) -> dict[str, Any]:
-    """Gracefully close, then bound-force-close, TD processes from one install root."""
-    root = str(td_root.resolve())
-    script = r'''
+class WindowsTdProcessAdapter:
+    """Read and control qualified Anlogic processes with PID-reuse checks."""
+
+    def __init__(self, runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run) -> None:
+        self.runner = runner
+
+    def _run_json(self, script: str, *, env: dict[str, str] | None = None) -> Any:
+        command_env = os.environ.copy()
+        if env:
+            command_env.update(env)
+        result = self.runner(
+            ["powershell.exe", "-NoProfile", "-Command", script],
+            capture_output=True,
+            text=True,
+            check=False,
+            timeout=15,
+            env=command_env,
+        )
+        if result.returncode != 0:
+            detail = result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}"
+            raise RuntimeError(detail)
+        try:
+            return json.loads(result.stdout)
+        except json.JSONDecodeError as exc:
+            raise RuntimeError(f"invalid process audit JSON: {exc}") from exc
+
+    def discover(self) -> list[dict[str, Any]]:
+        candidate_names = ", ".join(f"'{name}'" for name in TD_PROCESS_EXECUTABLES)
+        script = rf'''
+$ErrorActionPreference = 'Stop'
+$candidateNames = @({candidate_names})
+$records = @()
+$candidates = @(Get-CimInstance Win32_Process | Where-Object {{
+    $candidateNames -contains ([string]$_.Name).ToLowerInvariant()
+}} | Sort-Object ProcessId)
+foreach ($process in $candidates) {{
+    $record = [ordered]@{{
+        pid = [int]$process.ProcessId
+        name = [string]$process.Name
+        path = $null
+        user = $null
+        session_id = $null
+        parent_pid = $null
+        command_line = $null
+        start_time = $null
+        exe_sha256 = $null
+    }}
+    try {{
+        if ([string]::IsNullOrWhiteSpace([string]$process.ExecutablePath)) {{ throw 'path unavailable' }}
+        $record.path = [System.IO.Path]::GetFullPath([string]$process.ExecutablePath)
+        $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwner
+        if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{
+            throw ('owner unavailable: return={0}' -f $owner.ReturnValue)
+        }}
+        $record.user = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{
+            [string]$owner.User
+        }} else {{
+            '{0}\{1}' -f $owner.Domain, $owner.User
+        }})
+        $record.session_id = [int]$process.SessionId
+        $record.parent_pid = [int]$process.ParentProcessId
+        if ([string]::IsNullOrWhiteSpace([string]$process.CommandLine)) {{ throw 'command line unavailable' }}
+        $record.command_line = [string]$process.CommandLine
+        if ($null -eq $process.CreationDate) {{ throw 'start time unavailable' }}
+        $record.start_time = ([DateTime]$process.CreationDate).ToUniversalTime().ToString('o')
+        $record.exe_sha256 = (Get-FileHash -LiteralPath $record.path -Algorithm SHA256).Hash.ToLowerInvariant()
+    }} catch {{
+        $record.identity_error = $_.Exception.Message
+    }}
+    $records += [pscustomobject]$record
+}}
+[ordered]@{{ processes = @($records) }} | ConvertTo-Json -Compress -Depth 4
+'''
+        payload = self._run_json(script)
+        processes = payload.get("processes") if isinstance(payload, dict) else None
+        if not isinstance(processes, list):
+            raise RuntimeError("process discovery did not return an array")
+        return processes
+
+    def _identity_action(self, process: dict[str, Any], action: str) -> dict[str, Any]:
+        if action == "close":
+            action_script = "$native = Get-Process -Id $pidValue -ErrorAction Stop; $null = $native.CloseMainWindow()"
+        elif action == "probe":
+            action_script = ""
+        elif action == "force":
+            action_script = "Stop-Process -Id $pidValue -Force -ErrorAction Stop"
+        else:
+            raise ValueError(f"unknown process action: {action}")
+        script = rf'''
 $ErrorActionPreference = 'Stop'
 $ErrorActionPreference = 'Stop'
-if ([string]::IsNullOrWhiteSpace($env:PROD2U_TD_ROOT)) { throw 'PROD2U_TD_ROOT is required' }
-$root = [System.IO.Path]::GetFullPath($env:PROD2U_TD_ROOT).TrimEnd('\')
-$rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar
-$allowed = @('td','bw','bitwriter','chipwatcher','bw_commands_prompt')
-function Find-TdProcesses {
-    @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
-        try {
-            $path = $_.Path
-            $fullPath = [System.IO.Path]::GetFullPath($path)
-            $path -and
-                ($fullPath.Equals($root, [System.StringComparison]::OrdinalIgnoreCase) -or
-                    $fullPath.StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)) -and
-                ($allowed -contains $_.ProcessName.ToLowerInvariant())
-        } catch { $false }
-    })
-}
-$initial = Find-TdProcesses
-$graceful = @()
-foreach ($process in $initial) {
-    $null = $process.CloseMainWindow()
-    $graceful += ('{0}:{1}' -f $process.ProcessName, $process.Id)
-}
-Start-Sleep -Seconds 5
-$survivors = Find-TdProcesses
-$forced = @()
-foreach ($process in $survivors) {
-    Stop-Process -Id $process.Id -Force -ErrorAction Stop
-    $forced += ('{0}:{1}' -f $process.ProcessName, $process.Id)
-}
-Start-Sleep -Milliseconds 250
-$remaining = @(Find-TdProcesses | ForEach-Object { '{0}:{1}' -f $_.ProcessName, $_.Id })
-[ordered]@{
-    status = $(if ($remaining.Count -eq 0) { 'pass' } else { 'fail' })
-    td_root = $root
-    graceful_close_requested = $graceful
-    forced_terminated = $forced
-    wait_seconds = 5.0
-    remaining = $remaining
-} | ConvertTo-Json -Compress
+$pidValue = [int]$env:PROD2U_PROCESS_PID
+$expectedPath = [System.IO.Path]::GetFullPath($env:PROD2U_PROCESS_PATH)
+$expectedStart = $env:PROD2U_PROCESS_START
+$expectedOwner = $env:PROD2U_PROCESS_OWNER
+$expectedSession = [int]$env:PROD2U_PROCESS_SESSION
+$expectedParent = [int]$env:PROD2U_PROCESS_PARENT
+$expectedCommandLine = $env:PROD2U_PROCESS_COMMAND_LINE
+$expectedSha256 = $env:PROD2U_PROCESS_SHA256
+$current = Get-CimInstance Win32_Process -Filter ("ProcessId = {{0}}" -f $pidValue)
+if ($null -eq $current) {{
+    [ordered]@{{ status = 'not_running'; running = $false }} | ConvertTo-Json -Compress
+    exit 0
+}}
+if ([string]::IsNullOrWhiteSpace([string]$current.ExecutablePath)) {{ throw 'current process path unavailable' }}
+$currentPath = [System.IO.Path]::GetFullPath([string]$current.ExecutablePath)
+$currentStart = ([DateTime]$current.CreationDate).ToUniversalTime().ToString('o')
+$owner = Invoke-CimMethod -InputObject $current -MethodName GetOwner
+if ($owner.ReturnValue -ne 0 -or [string]::IsNullOrWhiteSpace([string]$owner.User)) {{
+    throw 'current process owner unavailable'
+}}
+$currentOwner = $(if ([string]::IsNullOrWhiteSpace([string]$owner.Domain)) {{
+    [string]$owner.User
+}} else {{
+    '{{0}}\{{1}}' -f $owner.Domain, $owner.User
+}})
+$currentSha256 = (Get-FileHash -LiteralPath $currentPath -Algorithm SHA256).Hash.ToLowerInvariant()
+if (-not $currentPath.Equals($expectedPath, [System.StringComparison]::OrdinalIgnoreCase) -or
+    -not $currentStart.Equals($expectedStart, [System.StringComparison]::Ordinal) -or
+    -not $currentOwner.Equals($expectedOwner, [System.StringComparison]::OrdinalIgnoreCase) -or
+    [int]$current.SessionId -ne $expectedSession -or
+    [int]$current.ParentProcessId -ne $expectedParent -or
+    -not ([string]$current.CommandLine).Equals($expectedCommandLine, [System.StringComparison]::Ordinal) -or
+    -not $currentSha256.Equals($expectedSha256, [System.StringComparison]::OrdinalIgnoreCase)) {{
+    throw 'process identity changed before action'
+}}
+{action_script}
+[ordered]@{{ status = 'ok'; running = $true }} | ConvertTo-Json -Compress
 '''
 '''
-    env = os.environ.copy()
-    env["PROD2U_TD_ROOT"] = root
-    result = subprocess.run(
-        ["powershell.exe", "-NoProfile", "-Command", script],
-        capture_output=True,
-        text=True,
-        check=False,
-        timeout=15,
-        env=env,
+        return self._run_json(
+            script,
+            env={
+                "PROD2U_PROCESS_PID": str(process["pid"]),
+                "PROD2U_PROCESS_PATH": str(process["path"]),
+                "PROD2U_PROCESS_START": str(process["start_time"]),
+                "PROD2U_PROCESS_OWNER": str(process["user"]),
+                "PROD2U_PROCESS_SESSION": str(process["session_id"]),
+                "PROD2U_PROCESS_PARENT": str(process["parent_pid"]),
+                "PROD2U_PROCESS_COMMAND_LINE": str(process["command_line"]),
+                "PROD2U_PROCESS_SHA256": str(process["exe_sha256"]),
+            },
+        )
+
+    def request_close(self, process: dict[str, Any]) -> None:
+        self._identity_action(process, "close")
+
+    def is_running(self, process: dict[str, Any]) -> bool:
+        return bool(self._identity_action(process, "probe").get("running"))
+
+    def force_stop(self, process: dict[str, Any]) -> None:
+        self._identity_action(process, "force")
+
+
+def _process_identity_errors(process: Any, *, td_root: str) -> tuple[dict[str, Any] | None, list[str]]:
+    if not isinstance(process, dict):
+        return None, ["identity_unreadable:unknown:record"]
+    pid = process.get("pid")
+    pid_label = str(pid) if isinstance(pid, int) and not isinstance(pid, bool) else "unknown"
+    errors: list[str] = []
+    if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
+        errors.append("identity_unreadable:unknown:pid")
+    name = process.get("name")
+    if not isinstance(name, str) or not name.strip():
+        errors.append(f"identity_unreadable:{pid_label}:name")
+    elif name.casefold() not in {candidate.casefold() for candidate in TD_PROCESS_EXECUTABLES}:
+        errors.append(f"unexpected_process_name:{pid_label}")
+    for field in ("path", "user", "command_line", "start_time", "exe_sha256"):
+        value = process.get(field)
+        if not isinstance(value, str) or not value.strip():
+            errors.append(f"identity_unreadable:{pid_label}:{field}")
+    identity_error = process.get("identity_error")
+    if identity_error:
+        errors.append(f"identity_unreadable:{pid_label}:adapter:{identity_error}")
+    path = process.get("path")
+    if isinstance(path, str) and path.strip():
+        canonical_path = ntpath.normcase(ntpath.normpath(path))
+        canonical_root = ntpath.normcase(ntpath.normpath(td_root)).rstrip("\\/")
+        root_prefix = canonical_root + "\\"
+        if not ntpath.isabs(path) or not canonical_path.startswith(root_prefix):
+            errors.append(f"unknown_process_path:{pid_label}")
+        if isinstance(name, str) and name.strip() and ntpath.basename(canonical_path) != name.casefold():
+            errors.append(f"process_name_path_mismatch:{pid_label}")
+    exe_sha256 = process.get("exe_sha256")
+    if isinstance(exe_sha256, str) and exe_sha256.strip() and not re.fullmatch(r"[0-9a-f]{64}", exe_sha256):
+        errors.append(f"identity_unreadable:{pid_label}:exe_sha256")
+    for field in ("session_id", "parent_pid"):
+        value = process.get(field)
+        if not isinstance(value, int) or isinstance(value, bool) or value < 0:
+            errors.append(f"identity_unreadable:{pid_label}:{field}")
+    if errors:
+        return None, errors
+    return {
+        "pid": int(pid),
+        "name": str(name),
+        "path": str(process["path"]),
+        "user": str(process["user"]),
+        "session_id": int(process["session_id"]),
+        "parent_pid": int(process["parent_pid"]),
+        "command_line": str(process["command_line"]),
+        "start_time": str(process["start_time"]),
+        "exe_sha256": str(process["exe_sha256"]),
+    }, []
+
+
+def _canonical_command_line(value: str) -> str:
+    return value.strip()
+
+
+def _validate_ownership_policy(policy: Any) -> list[str]:
+    if not isinstance(policy, dict):
+        return ["ownership_policy_missing"]
+    errors: list[str] = []
+    for field in ("owner", "command_line"):
+        if not isinstance(policy.get(field), str) or not policy[field].strip():
+            errors.append(f"ownership_policy_invalid:{field}")
+    for field in ("session_id", "parent_pid"):
+        value = policy.get(field)
+        if not isinstance(value, int) or isinstance(value, bool) or value < 0:
+            errors.append(f"ownership_policy_invalid:{field}")
+    binaries = policy.get("approved_binaries")
+    if not isinstance(binaries, list) or not binaries:
+        errors.append("ownership_policy_invalid:approved_binaries")
+    else:
+        for binary in binaries:
+            if not isinstance(binary, dict):
+                errors.append("ownership_policy_invalid:approved_binary")
+                continue
+            if not all(isinstance(binary.get(field), str) and binary[field].strip() for field in ("name", "path")):
+                errors.append("ownership_policy_invalid:approved_binary_identity")
+            if not isinstance(binary.get("exe_sha256"), str) or not SHA256_RE.fullmatch(binary["exe_sha256"]):
+                errors.append("ownership_policy_invalid:approved_binary_hash")
+    return list(dict.fromkeys(errors))
+
+
+def _is_harness_owned(process: dict[str, Any], policy: dict[str, Any]) -> bool:
+    binary_matches = any(
+        str(process["name"]).casefold() == str(binary["name"]).casefold()
+        and ntpath.normcase(ntpath.normpath(str(process["path"])))
+        == ntpath.normcase(ntpath.normpath(str(binary["path"])))
+        and str(process["exe_sha256"]).casefold() == str(binary["exe_sha256"]).casefold()
+        for binary in policy["approved_binaries"]
+    )
+    return (
+        binary_matches
+        and str(process["user"]).casefold() == str(policy["owner"]).casefold()
+        and process["session_id"] == policy["session_id"]
+        and process["parent_pid"] == policy["parent_pid"]
+        and _canonical_command_line(str(process["command_line"]))
+        == _canonical_command_line(str(policy["command_line"]))
     )
     )
-    if result.returncode != 0:
+
+
+def build_process_ownership_policy(*, executable: Path, command: list[str]) -> dict[str, Any]:
+    """Build the exact identity policy for a process launched by this harness."""
+    executable = executable.resolve()
+    if os.name == "nt":
+        session_id = ctypes.c_uint32()
+        kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+        kernel32.ProcessIdToSessionId.argtypes = [ctypes.c_uint32, ctypes.POINTER(ctypes.c_uint32)]
+        kernel32.ProcessIdToSessionId.restype = ctypes.c_bool
+        if not kernel32.ProcessIdToSessionId(os.getpid(), ctypes.byref(session_id)):
+            raise OSError(ctypes.get_last_error(), "ProcessIdToSessionId failed")
+        domain = os.environ.get("USERDOMAIN", "").strip()
+        username = os.environ.get("USERNAME", "").strip() or getpass.getuser()
+        owner = f"{domain}\\{username}" if domain else username
+        current_session = int(session_id.value)
+    else:
+        owner = getpass.getuser()
+        current_session = 0
+    return {
+        "owner": owner,
+        "session_id": current_session,
+        "parent_pid": os.getpid(),
+        "approved_binaries": [
+            {
+                "name": executable.name.casefold(),
+                "path": str(executable),
+                "exe_sha256": sha256_file(executable),
+            }
+        ],
+        "command_line": subprocess.list2cmdline(command),
+    }
+
+
+def close_td_processes(
+    td_root: Path,
+    *,
+    ownership_policy: dict[str, Any] | None = None,
+    process_adapter: Any | None = None,
+    sleeper: Callable[[float], None] = time.sleep,
+) -> dict[str, Any]:
+    """Terminate only processes proven to be owned by this harness invocation."""
+    root = str(td_root.resolve())
+    adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter()
+    discovered: list[dict[str, Any]] = []
+    harness_owned: list[dict[str, Any]] = []
+    blocking: list[dict[str, Any]] = []
+    graceful: list[dict[str, Any]] = []
+    forced: list[dict[str, Any]] = []
+    errors = _validate_ownership_policy(ownership_policy)
+
+    def result(status: str, *, remaining: list[dict[str, Any]] | None = None, audited: bool) -> dict[str, Any]:
         return {
         return {
-            "status": "fail",
+            "status": status,
             "td_root": root,
             "td_root": root,
-            "graceful_close_requested": [],
-            "forced_terminated": [],
+            "identity_audit_completed_before_action": audited,
+            "ownership_policy": ownership_policy,
+            "discovered_processes": discovered,
+            "harness_owned_processes": harness_owned,
+            "blocking_processes": blocking,
+            "graceful_close_requested": graceful,
+            "forced_terminated": forced,
             "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
             "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
-            "remaining": [],
-            "error": result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}",
+            "remaining": remaining or [],
+            "post_action_audit_completed": False,
+            "post_action_discovered_processes": [],
+            "post_action_harness_owned_processes": [],
+            "post_action_blocking_processes": [],
+            "residual_processes": [],
+            "post_action_errors": [],
+            "errors": list(dict.fromkeys(errors)),
         }
         }
+
+    if errors:
+        return result("fail", audited=False)
     try:
     try:
-        payload = json.loads(result.stdout)
-    except json.JSONDecodeError as exc:
-        return {
-            "status": "fail",
-            "td_root": root,
-            "graceful_close_requested": [],
-            "forced_terminated": [],
-            "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
-            "remaining": [],
-            "error": f"invalid process cleanup JSON: {exc}",
-        }
-    return payload
+        raw_processes = adapter.discover()
+    except Exception as exc:
+        errors.append(f"process_discovery_failed:{exc}")
+        return result("fail", audited=False)
+    if not isinstance(raw_processes, list):
+        errors.append("process_discovery_failed:not_an_array")
+        return result("fail", audited=False)
+    for raw_process in raw_processes:
+        process, process_errors = _process_identity_errors(raw_process, td_root=root)
+        errors.extend(process_errors)
+        if process is not None:
+            discovered.append(process)
+    if errors:
+        return result("fail", audited=False)
+    for process in discovered:
+        if _is_harness_owned(process, ownership_policy):
+            harness_owned.append(process)
+        else:
+            blocking.append(process)
+    if blocking:
+        errors.append("blocking_td_processes_present")
+        return result("fail", remaining=discovered, audited=True)
+
+    try:
+        for process in harness_owned:
+            adapter.request_close(process)
+            graceful.append(process)
+        if harness_owned:
+            sleeper(PROCESS_CLEANUP_WAIT_SECONDS)
+        for process in harness_owned:
+            if adapter.is_running(process):
+                adapter.force_stop(process)
+                forced.append(process)
+        raw_remaining = adapter.discover()
+    except Exception as exc:
+        errors.append(f"process_control_failed:{exc}")
+        return result("fail", audited=True)
+
+    remaining: list[dict[str, Any]] = []
+    if not isinstance(raw_remaining, list):
+        errors.append("final_process_discovery_failed:not_an_array")
+    else:
+        for raw_process in raw_remaining:
+            process, process_errors = _process_identity_errors(raw_process, td_root=root)
+            errors.extend(process_errors)
+            if process is not None:
+                remaining.append(process)
+    if remaining:
+        errors.append("qualified_processes_remaining")
+    return result("pass" if not errors else "fail", remaining=remaining, audited=True)
+
+
+def audit_td_processes(
+    td_root: Path,
+    *,
+    ownership_policy: dict[str, Any],
+    process_adapter: Any | None = None,
+) -> dict[str, Any]:
+    """Perform a non-destructive post-action audit of all TD candidates."""
+    root = str(td_root.resolve())
+    adapter = process_adapter if process_adapter is not None else WindowsTdProcessAdapter()
+    errors = _validate_ownership_policy(ownership_policy)
+    discovered: list[dict[str, Any]] = []
+    harness_owned: list[dict[str, Any]] = []
+    blocking: list[dict[str, Any]] = []
+    audit_completed = False
+    if not errors:
+        try:
+            raw_processes = adapter.discover()
+        except Exception as exc:
+            errors.append(f"post_action_process_discovery_failed:{exc}")
+            raw_processes = []
+        if not isinstance(raw_processes, list):
+            errors.append("post_action_process_discovery_failed:not_an_array")
+        else:
+            for raw_process in raw_processes:
+                process, process_errors = _process_identity_errors(raw_process, td_root=root)
+                errors.extend(process_errors)
+                if process is not None:
+                    discovered.append(process)
+            audit_completed = not errors
+    if not errors:
+        for process in discovered:
+            if _is_harness_owned(process, ownership_policy):
+                harness_owned.append(process)
+            else:
+                blocking.append(process)
+        if discovered:
+            errors.append("post_action_td_processes_remaining")
+    return {
+        "status": "pass" if not errors else "fail",
+        "post_action_audit_completed": audit_completed,
+        "post_action_discovered_processes": discovered,
+        "post_action_harness_owned_processes": harness_owned,
+        "post_action_blocking_processes": blocking,
+        "residual_processes": discovered,
+        "post_action_errors": list(dict.fromkeys(errors)),
+    }
 
 
 
 
 def _snapshot_bitwriter_logs(log_dir: Path) -> dict[str, dict[str, int]]:
 def _snapshot_bitwriter_logs(log_dir: Path) -> dict[str, dict[str, int]]:
@@ -331,6 +687,38 @@ class _JobExtendedLimitInformation(ctypes.Structure):
     ]
     ]
 
 
 
 
+class _StartupInfoW(ctypes.Structure):
+    _fields_ = [
+        ("cb", wintypes.DWORD),
+        ("lpReserved", wintypes.LPWSTR),
+        ("lpDesktop", wintypes.LPWSTR),
+        ("lpTitle", wintypes.LPWSTR),
+        ("dwX", wintypes.DWORD),
+        ("dwY", wintypes.DWORD),
+        ("dwXSize", wintypes.DWORD),
+        ("dwYSize", wintypes.DWORD),
+        ("dwXCountChars", wintypes.DWORD),
+        ("dwYCountChars", wintypes.DWORD),
+        ("dwFillAttribute", wintypes.DWORD),
+        ("dwFlags", wintypes.DWORD),
+        ("wShowWindow", wintypes.WORD),
+        ("cbReserved2", wintypes.WORD),
+        ("lpReserved2", ctypes.POINTER(wintypes.BYTE)),
+        ("hStdInput", wintypes.HANDLE),
+        ("hStdOutput", wintypes.HANDLE),
+        ("hStdError", wintypes.HANDLE),
+    ]
+
+
+class _ProcessInformation(ctypes.Structure):
+    _fields_ = [
+        ("hProcess", wintypes.HANDLE),
+        ("hThread", wintypes.HANDLE),
+        ("dwProcessId", wintypes.DWORD),
+        ("dwThreadId", wintypes.DWORD),
+    ]
+
+
 def windows_process_is_running(pid: int) -> bool:
 def windows_process_is_running(pid: int) -> bool:
     if os.name != "nt":
     if os.name != "nt":
         return False
         return False
@@ -376,6 +764,29 @@ def run_process_in_job(
     kernel32.SetInformationJobObject.restype = ctypes.c_bool
     kernel32.SetInformationJobObject.restype = ctypes.c_bool
     kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
     kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
     kernel32.AssignProcessToJobObject.restype = ctypes.c_bool
     kernel32.AssignProcessToJobObject.restype = ctypes.c_bool
+    kernel32.CreateProcessW.argtypes = [
+        wintypes.LPCWSTR,
+        wintypes.LPWSTR,
+        ctypes.c_void_p,
+        ctypes.c_void_p,
+        wintypes.BOOL,
+        wintypes.DWORD,
+        ctypes.c_void_p,
+        wintypes.LPCWSTR,
+        ctypes.POINTER(_StartupInfoW),
+        ctypes.POINTER(_ProcessInformation),
+    ]
+    kernel32.CreateProcessW.restype = wintypes.BOOL
+    kernel32.ResumeThread.argtypes = [wintypes.HANDLE]
+    kernel32.ResumeThread.restype = wintypes.DWORD
+    kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
+    kernel32.WaitForSingleObject.restype = wintypes.DWORD
+    kernel32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
+    kernel32.GetExitCodeProcess.restype = wintypes.BOOL
+    kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
+    kernel32.TerminateProcess.restype = wintypes.BOOL
+    kernel32.SetHandleInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD]
+    kernel32.SetHandleInformation.restype = wintypes.BOOL
     kernel32.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
     kernel32.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
     kernel32.TerminateJobObject.restype = ctypes.c_bool
     kernel32.TerminateJobObject.restype = ctypes.c_bool
     kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
     kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
@@ -389,31 +800,100 @@ def run_process_in_job(
         error = ctypes.get_last_error()
         error = ctypes.get_last_error()
         kernel32.CloseHandle(job)
         kernel32.CloseHandle(job)
         raise OSError(error, "SetInformationJobObject failed")
         raise OSError(error, "SetInformationJobObject failed")
-    stdout_pipe = subprocess.PIPE if capture_output else None
-    stderr_pipe = subprocess.PIPE if capture_output else None
-    process = subprocess.Popen(
-        command,
-        cwd=cwd,
-        stdout=stdout_pipe,
-        stderr=stderr_pipe,
-        text=text,
-    )
+    CREATE_SUSPENDED = 0x00000004
+    STARTF_USESTDHANDLES = 0x00000100
+    HANDLE_FLAG_INHERIT = 0x00000001
+    WAIT_OBJECT_0 = 0x00000000
+    WAIT_TIMEOUT = 0x00000102
+    INFINITE = 0xFFFFFFFF
+    stdout_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None
+    stderr_file = tempfile.TemporaryFile(mode="w+b") if capture_output else None
+    stdin_file = open(os.devnull, "rb") if capture_output else None
+    inherited_handles: list[int] = []
+    startup = _StartupInfoW()
+    startup.cb = ctypes.sizeof(startup)
+    if capture_output:
+        import msvcrt
+
+        startup.dwFlags = STARTF_USESTDHANDLES
+        startup.hStdInput = wintypes.HANDLE(msvcrt.get_osfhandle(stdin_file.fileno()))
+        startup.hStdOutput = wintypes.HANDLE(msvcrt.get_osfhandle(stdout_file.fileno()))
+        startup.hStdError = wintypes.HANDLE(msvcrt.get_osfhandle(stderr_file.fileno()))
+        inherited_handles = [
+            int(startup.hStdInput),
+            int(startup.hStdOutput),
+            int(startup.hStdError),
+        ]
+        for handle in inherited_handles:
+            if not kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT):
+                raise OSError(ctypes.get_last_error(), "SetHandleInformation failed")
+    process_info = _ProcessInformation()
+    command_line = ctypes.create_unicode_buffer(subprocess.list2cmdline(command))
+    created = False
     try:
     try:
-        if not kernel32.AssignProcessToJobObject(job, ctypes.c_void_p(int(process._handle))):
-            process.kill()
-            process.wait()
-            raise OSError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
-        try:
-            stdout, stderr = process.communicate(timeout=timeout)
-        except subprocess.TimeoutExpired as exc:
+        if not kernel32.CreateProcessW(
+            str(command[0]),
+            command_line,
+            None,
+            None,
+            bool(capture_output),
+            CREATE_SUSPENDED,
+            None,
+            cwd,
+            ctypes.byref(startup),
+            ctypes.byref(process_info),
+        ):
+            raise OSError(ctypes.get_last_error(), "CreateProcessW failed")
+        created = True
+        if not kernel32.AssignProcessToJobObject(job, process_info.hProcess):
+            error = ctypes.get_last_error()
+            kernel32.TerminateProcess(process_info.hProcess, 1)
+            kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
+            raise OSError(error, "AssignProcessToJobObject failed")
+        if kernel32.ResumeThread(process_info.hThread) == 0xFFFFFFFF:
+            error = ctypes.get_last_error()
+            kernel32.TerminateJobObject(job, 1)
+            kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
+            raise OSError(error, "ResumeThread failed")
+        wait_milliseconds = max(0, min(int(timeout * 1000), 0xFFFFFFFE))
+        wait_result = kernel32.WaitForSingleObject(process_info.hProcess, wait_milliseconds)
+        timed_out = wait_result == WAIT_TIMEOUT
+        if timed_out:
             kernel32.TerminateJobObject(job, 1)
             kernel32.TerminateJobObject(job, 1)
-            stdout, stderr = process.communicate()
-            raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr) from exc
-        result = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
+            kernel32.WaitForSingleObject(process_info.hProcess, INFINITE)
+        elif wait_result != WAIT_OBJECT_0:
+            raise OSError(ctypes.get_last_error(), "WaitForSingleObject failed")
+        exit_code = wintypes.DWORD()
+        if not kernel32.GetExitCodeProcess(process_info.hProcess, ctypes.byref(exit_code)):
+            raise OSError(ctypes.get_last_error(), "GetExitCodeProcess failed")
+        encoding = locale.getpreferredencoding(False)
+        stdout: str | bytes | None = None
+        stderr: str | bytes | None = None
+        if capture_output:
+            stdout_file.seek(0)
+            stderr_file.seek(0)
+            stdout_bytes = stdout_file.read()
+            stderr_bytes = stderr_file.read()
+            stdout = stdout_bytes.decode(encoding, errors="replace") if text else stdout_bytes
+            stderr = stderr_bytes.decode(encoding, errors="replace") if text else stderr_bytes
+        if timed_out:
+            raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr)
+        result = subprocess.CompletedProcess(command, int(exit_code.value), stdout, stderr)
         if check and result.returncode != 0:
         if check and result.returncode != 0:
             raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr)
             raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr)
         return result
         return result
     finally:
     finally:
+        for handle in inherited_handles:
+            kernel32.SetHandleInformation(wintypes.HANDLE(handle), HANDLE_FLAG_INHERIT, 0)
+        if created:
+            kernel32.CloseHandle(process_info.hThread)
+            kernel32.CloseHandle(process_info.hProcess)
+        if stdin_file is not None:
+            stdin_file.close()
+        if stdout_file is not None:
+            stdout_file.close()
+        if stderr_file is not None:
+            stderr_file.close()
         kernel32.CloseHandle(job)
         kernel32.CloseHandle(job)
 
 
 
 
@@ -440,7 +920,8 @@ def execute_program_sram(
     td_root: Path,
     td_root: Path,
     run_id: str,
     run_id: str,
     process_runner: Callable[..., subprocess.CompletedProcess[str]] = run_process_in_job,
     process_runner: Callable[..., subprocess.CompletedProcess[str]] = run_process_in_job,
-    cleanup_runner: Callable[[Path], dict[str, Any]] = close_td_processes,
+    cleanup_runner: Callable[..., dict[str, Any]] = close_td_processes,
+    residual_audit_runner: Callable[..., dict[str, Any]] = audit_td_processes,
     mutex_factory: Callable[[], Any] = WindowsNamedMutex,
     mutex_factory: Callable[[], Any] = WindowsNamedMutex,
 ) -> dict[str, Any]:
 ) -> dict[str, Any]:
     """Execute exactly one SRAM download and return a strict transaction receipt."""
     """Execute exactly one SRAM download and return a strict transaction receipt."""
@@ -466,11 +947,14 @@ def execute_program_sram(
     stdout_path = output_dir / "bitwriter-stdout.log"
     stdout_path = output_dir / "bitwriter-stdout.log"
     stderr_path = output_dir / "bitwriter-stderr.log"
     stderr_path = output_dir / "bitwriter-stderr.log"
     delta_path = output_dir / "bitwriter-log-delta.log"
     delta_path = output_dir / "bitwriter-log-delta.log"
+    tcl_cli_path = tcl_path.absolute().as_posix()
+    command = [str(bw_exe), tcl_cli_path]
+    ownership_policy = build_process_ownership_policy(executable=bw_exe, command=command)
     started_at = utc_now()
     started_at = utc_now()
     start_monotonic = time.monotonic()
     start_monotonic = time.monotonic()
 
 
     with mutex_factory():
     with mutex_factory():
-        cleanup = cleanup_runner(td_root)
+        cleanup = cleanup_runner(td_root, ownership_policy=ownership_policy)
         if cleanup.get("status") != "pass":
         if cleanup.get("status") != "pass":
             raise RuntimeError(f"TD process cleanup failed: {cleanup}")
             raise RuntimeError(f"TD process cleanup failed: {cleanup}")
 
 
@@ -497,9 +981,8 @@ def execute_program_sram(
         before = _snapshot_bitwriter_logs(log_dir)
         before = _snapshot_bitwriter_logs(log_dir)
         timed_out = False
         timed_out = False
         try:
         try:
-            tcl_cli_path = tcl_path.absolute().as_posix()
             completed = process_runner(
             completed = process_runner(
-                [str(bw_exe), tcl_cli_path],
+                command,
                 cwd=str(td_root / "bin"),
                 cwd=str(td_root / "bin"),
                 timeout=PROGRAM_TIMEOUT_SECONDS,
                 timeout=PROGRAM_TIMEOUT_SECONDS,
                 capture_output=True,
                 capture_output=True,
@@ -515,6 +998,18 @@ def execute_program_sram(
             stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
             stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
             stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
             stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
         delta_bytes, delta_sources, delta_issues = _read_bitwriter_log_deltas(log_dir, before)
         delta_bytes, delta_sources, delta_issues = _read_bitwriter_log_deltas(log_dir, before)
+        residual_audit = residual_audit_runner(td_root, ownership_policy=ownership_policy)
+
+    for field in (
+        "post_action_audit_completed",
+        "post_action_discovered_processes",
+        "post_action_harness_owned_processes",
+        "post_action_blocking_processes",
+        "residual_processes",
+        "post_action_errors",
+    ):
+        cleanup[field] = residual_audit.get(field)
+    cleanup["status"] = "pass" if residual_audit.get("status") == "pass" else "fail"
 
 
     stdout_path.write_text(stdout, encoding="utf-8", newline="\n")
     stdout_path.write_text(stdout, encoding="utf-8", newline="\n")
     stderr_path.write_text(stderr, encoding="utf-8", newline="\n")
     stderr_path.write_text(stderr, encoding="utf-8", newline="\n")
@@ -533,6 +1028,8 @@ def execute_program_sram(
         td_bin=str(td_root / "bin"),
         td_bin=str(td_root / "bin"),
     )
     )
     authoritative_marker_signature = _marker_signature(parser_text)
     authoritative_marker_signature = _marker_signature(parser_text)
+    if residual_audit.get("status") != "pass":
+        receipt["parser"]["failures"].append("post_action_process_audit_failed")
     if not delta_bytes:
     if not delta_bytes:
         receipt["parser"]["failures"].append("missing_bitwriter_log_delta")
         receipt["parser"]["failures"].append("missing_bitwriter_log_delta")
         receipt["parser"]["ordered_markers_complete"] = False
         receipt["parser"]["ordered_markers_complete"] = False