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

feat:bind-6400-host-ACK-profiles

root 3 месяцев назад
Родитель
Сommit
f503054327
39 измененных файлов с 2469 добавлено и 127 удалено
  1. 1 1
      contracts/6400/SHA256SUMS
  2. 247 14
      contracts/6400/host-contract.json
  3. 2 2
      deploy/amd64-release/README.zh-CN.md
  4. 1 1
      deploy/amd64-release/config/hthd.6400-mock.yaml
  5. 1 1
      deploy/amd64-release/config/hthd.6400-serial.yaml
  6. 1 1
      deploy/amd64-release/selftest.sh
  7. 1 1
      deploy/amd64-release/verify-install.sh
  8. 1 1
      deploy/examples/hthd.6400-mock.yaml
  9. 1 1
      deploy/examples/hthd.6400-replay.yaml
  10. 1 1
      deploy/examples/hthd.6400-serial.yaml
  11. 12 8
      docs/6400/migration.md
  12. 14 0
      generated/6400/golden-vectors.json
  13. 1126 0
      generated/6400/host-contract.json
  14. 8 0
      generated/6400/import-source.json
  15. 7 5
      internal/config/config.go
  16. 24 1
      internal/config/thermal_6400_test.go
  17. 16 3
      internal/protocol6400/frame.go
  18. 31 2
      internal/protocol6400/frame_test.go
  19. 11 2
      internal/protocol6400/generated_contract.go
  20. 34 11
      internal/thermalbackend/backend_test.go
  21. 28 0
      internal/thermalbackend/mock.go
  22. 21 4
      internal/thermalbackend/replay.go
  23. 3 3
      internal/thermalbackend/replay_fuzz_test.go
  24. 5 3
      internal/thermalbackend/serial_linux_test.go
  25. 1 1
      internal/thermalservice/service.go
  26. 12 7
      internal/thermalservice/service_test.go
  27. 40 16
      internal/thermaltransport/client_linux.go
  28. 133 5
      internal/thermaltransport/client_linux_test.go
  29. 11 2
      profiles/6400-control/profile.json
  30. 12 2
      profiles/6400-identification/profile.json
  31. 25 0
      profiles/6400-sim-debug/profile.json
  32. 9 0
      sdk/python/README.md
  33. 6 2
      sdk/python/hth_sdk/generated/thermal/contract.py
  34. 61 10
      sdk/python/hth_sdk/thermal.py
  35. 17 2
      sdk/python/tests/test_thermal.py
  36. 10 6
      tests/thermal_6400_uds_test.go
  37. 62 8
      tools/import_6400_contract.py
  38. 348 0
      tools/rtl_uart_cosim/run_hthd_6400_pty_rtl.py
  39. 125 0
      tools/rtl_uart_cosim/test_hthd_6400_pty_bridge.py

+ 1 - 1
contracts/6400/SHA256SUMS

@@ -1 +1 @@
-f1277d466369134b33e970899d6883d5fc5e0d63c8d975824a439c1b0d08b65d  host-contract.json
+971702eb7d7a113cd6d106d6f0486b8863194e06f15a3b97ed29067f3faf704f  host-contract.json

+ 247 - 14
contracts/6400/host-contract.json

@@ -1,4 +1,35 @@
 {
+  "canonical_profiles": {
+    "6400-control": {
+      "allowed_commands": [
+        "SET_TARGET",
+        "GET_SNAPSHOT"
+      ],
+      "production": true,
+      "simulation_only": false,
+      "stimulus": false
+    },
+    "6400-identification": {
+      "allowed_commands": [
+        "SET_TARGET",
+        "GET_SNAPSHOT",
+        "SET_STIMULUS"
+      ],
+      "production": false,
+      "simulation_only": false,
+      "stimulus": true
+    },
+    "6400-sim-debug": {
+      "allowed_commands": [
+        "SET_TARGET",
+        "GET_SNAPSHOT",
+        "SET_STIMULUS"
+      ],
+      "production": false,
+      "simulation_only": true,
+      "stimulus": true
+    }
+  },
   "channel_map": {
     "channels": [
       {
@@ -482,6 +513,130 @@
         "thermal_zone": 2
       }
     ],
+    "fan_output_vector_order": [
+      "front0",
+      "front1",
+      "front2",
+      "front3",
+      "rear0",
+      "rear1",
+      "rear2",
+      "rear3"
+    ],
+    "fan_outputs": [
+      {
+        "ball_active_level": "low",
+        "board_inverts": true,
+        "board_stage": "Q101",
+        "connector": "CON25",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "B1",
+        "group": "front",
+        "lane": 0,
+        "net": "FAN_PWM3",
+        "output_index": 24,
+        "pin": 7
+      },
+      {
+        "ball_active_level": "low",
+        "board_inverts": true,
+        "board_stage": "Q99",
+        "connector": "CON8",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "C4",
+        "group": "front",
+        "lane": 1,
+        "net": "FAN_PWM1",
+        "output_index": 25,
+        "pin": 7
+      },
+      {
+        "ball_active_level": "low",
+        "board_inverts": true,
+        "board_stage": "Q100",
+        "connector": "CON24",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "B5",
+        "group": "front",
+        "lane": 2,
+        "net": "FAN_PWM2",
+        "output_index": 26,
+        "pin": 7
+      },
+      {
+        "ball_active_level": "low",
+        "board_inverts": true,
+        "board_stage": "Q102",
+        "connector": "CON26",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "A14",
+        "group": "front",
+        "lane": 3,
+        "net": "FAN_PWM4",
+        "output_index": 27,
+        "pin": 7
+      },
+      {
+        "ball_active_level": "high",
+        "board_inverts": false,
+        "board_stage": "R704_0R_DIRECT",
+        "connector": "CON64",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "P15",
+        "group": "rear",
+        "lane": 0,
+        "net": "FAN_GPIO44",
+        "output_index": 28,
+        "pin": 4
+      },
+      {
+        "ball_active_level": "high",
+        "board_inverts": false,
+        "board_stage": "R706_0R_DIRECT",
+        "connector": "CON66",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "N15",
+        "group": "rear",
+        "lane": 1,
+        "net": "FAN_GPIO46",
+        "output_index": 29,
+        "pin": 4
+      },
+      {
+        "ball_active_level": "high",
+        "board_inverts": false,
+        "board_stage": "R702_0R_DIRECT",
+        "connector": "CON62",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "M14",
+        "group": "rear",
+        "lane": 2,
+        "net": "FAN_GPIO42",
+        "output_index": 30,
+        "pin": 4
+      },
+      {
+        "ball_active_level": "high",
+        "board_inverts": false,
+        "board_stage": "R700_0R_DIRECT",
+        "connector": "CON60",
+        "connector_active_level": "high",
+        "evidence": "confirmed_board_v1_1",
+        "fpga_ball": "P5",
+        "group": "rear",
+        "lane": 3,
+        "net": "FAN_GPIO40",
+        "output_index": 31,
+        "pin": 4
+      }
+    ],
     "lanes": [
       {
         "air_lane": 0,
@@ -527,7 +682,7 @@
     "product": "6400-front-rear-v1",
     "schema": "prod2u-6400-channel-map-v1"
   },
-  "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+  "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
   "controller_coefficients": {
     "classes": {
       "CENTER": {
@@ -564,23 +719,36 @@
     "truth_label": "SIMULATION_DEFAULT_NOT_HARDWARE_TUNED"
   },
   "fan_control": {
+    "actual_airflow_status": "NOT_RUN",
+    "actual_rpm_status": "NOT_RUN",
     "duty": {
       "hard": 100,
       "nominal": 30,
       "protection": 80,
       "reset": 10,
-      "stopped": 30,
+      "stopped": 10,
       "warm": 50
     },
     "front_rear_independent": true,
     "invalid_lane_threshold": 2,
-    "schema": "prod2u-6400-fan-control-v1",
+    "pwm": {
+      "carrier_backend": "shared_equal_frequency_v1",
+      "clock_hz": 25000000,
+      "evidence": "EXPERIMENTAL_CONFIGURATION_NOT_FAN_DATASHEET_VERIFIED",
+      "fan_hz": 500,
+      "fan_phase_clks": 500,
+      "phases": 100,
+      "ptc_hz": 500,
+      "ptc_phase_clks": 500
+    },
+    "pwm_high_level_status": "PWM_HIGH_LEVEL_UNVERIFIED",
+    "schema": "prod2u-6400-fan-control-v2",
     "temperature_centi_degC": {
       "hard": 7700,
       "protection": 7400,
       "warm_delta_from_target": -300
     },
-    "truth_label": "SIMULATION_DEFAULT_NOT_HARDWARE_TUNED"
+    "truth_label": "EXPERIMENTAL_UNVERIFIED"
   },
   "fixed_point": {
     "algorithm": "incremental_pi",
@@ -617,9 +785,10 @@
     }
   },
   "golden_vectors": {
-    "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+    "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
     "frames": {
       "get_snapshot": "A55A02006D7B",
+      "get_snapshot_ack": "A55A8200F560",
       "set_target_20": "A55A010114289A",
       "set_target_70": "A55A0101469FE0",
       "set_target_ack": "A55A8100A635",
@@ -629,10 +798,10 @@
     },
     "schema": "prod2u-6400-golden-vectors-v1"
   },
-  "schema": "prod2u-6400-host-contract-v1",
+  "schema": "prod2u-6400-host-contract-v2",
   "snapshot": {
     "byte_order": "little",
-    "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+    "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
     "fields": [
       {
         "name": "control_state",
@@ -785,6 +954,11 @@
     "schema": "prod2u-6400-snapshot-v1"
   },
   "wire": {
+    "ack_contract": {
+      "every_legal_command": true,
+      "independent_frame": true,
+      "payload_length": 0
+    },
     "bmc_uart": {
       "baud": 115200,
       "clks_per_bit": 217,
@@ -802,14 +976,51 @@
     "commands": {
       "GET_SNAPSHOT": {
         "payload_length": 0,
-        "response": "SNAPSHOT_DATA",
+        "response": [
+          "GET_SNAPSHOT_ACK",
+          "SNAPSHOT_DATA"
+        ],
         "type": 2
       },
       "SET_STIMULUS": {
+        "payload_fields": [
+          {
+            "count": 1,
+            "maximum": 255,
+            "minimum": 1,
+            "name": "duration_seconds",
+            "offset": 0,
+            "unit": "seconds"
+          },
+          {
+            "count": 24,
+            "maximum": 100,
+            "minimum": 0,
+            "name": "ptc_duty_percent",
+            "offset": 1,
+            "unit": "percent"
+          },
+          {
+            "count": 4,
+            "maximum": 100,
+            "minimum": 0,
+            "name": "front_fan_duty_percent",
+            "offset": 25,
+            "unit": "percent"
+          },
+          {
+            "count": 4,
+            "maximum": 100,
+            "minimum": 0,
+            "name": "rear_fan_duty_percent",
+            "offset": 29,
+            "unit": "percent"
+          }
+        ],
         "payload_length": 33,
         "profiles": [
-          "identification",
-          "sim-debug"
+          "6400-identification",
+          "6400-sim-debug"
         ],
         "response": "SET_STIMULUS_ACK",
         "type": 3
@@ -850,6 +1061,18 @@
       165,
       90
     ],
+    "host_response_order": {
+      "GET_SNAPSHOT": [
+        "GET_SNAPSHOT_ACK",
+        "SNAPSHOT_DATA"
+      ],
+      "SET_STIMULUS": [
+        "SET_STIMULUS_ACK"
+      ],
+      "SET_TARGET": [
+        "SET_TARGET_ACK"
+      ]
+    },
     "host_uart": {
       "baud": 921600,
       "fixed_candidate_clks_per_bit": 27,
@@ -871,11 +1094,15 @@
     "invalid_behavior": "silent_drop",
     "outstanding_transactions": 1,
     "responses": {
+      "GET_SNAPSHOT_ACK": {
+        "payload_length": 0,
+        "type": 130
+      },
       "SET_STIMULUS_ACK": {
         "payload_length": 0,
         "profiles": [
-          "identification",
-          "sim-debug"
+          "6400-identification",
+          "6400-sim-debug"
         ],
         "type": 131
       },
@@ -885,9 +1112,15 @@
       },
       "SNAPSHOT_DATA": {
         "payload_contract": "6400-snapshot.yaml",
-        "type": 130
+        "type": 66
       }
     },
-    "schema": "prod2u-6400-wire-v1"
+    "schema": "prod2u-6400-wire-v1",
+    "type_classes": {
+      "ack": "request_type_or_0x80",
+      "data": "request_type_or_0x40",
+      "request": "0x01-0x3F",
+      "reserved": "0xC0-0xFF"
+    }
   }
 }

+ 2 - 2
deploy/amd64-release/README.zh-CN.md

@@ -1,4 +1,4 @@
-# hth Linux amd64 v1.0.0-rc1
+# hth Linux amd64 v1.0.0-rc2
 
 ## 5 分钟快速开始
 
@@ -6,7 +6,7 @@
 Mock,不打开串口。
 
 ```bash
-(cd .. && sha256sum -c hth-linux-amd64-v1.0.0-rc1.tar.gz.sha256)
+(cd .. && sha256sum -c hth-linux-amd64-v1.0.0-rc2.tar.gz.sha256)
 sha256sum -c SHA256SUMS
 ./selftest.sh
 sudo ./install.sh

+ 1 - 1
deploy/amd64-release/config/hthd.6400-mock.yaml

@@ -12,7 +12,7 @@ sockets:
   observe_group: hth-observe
   control_group: hth-control
 thermal:
-  firmware_profile: production
+  firmware_profile: 6400-control
   transaction_timeout_ms: 1000
   retries: 2
   mock_scenario: normal

+ 1 - 1
deploy/amd64-release/config/hthd.6400-serial.yaml

@@ -14,7 +14,7 @@ sockets:
   observe_group: hth-observe
   control_group: hth-control
 thermal:
-  firmware_profile: production
+  firmware_profile: 6400-control
   transaction_timeout_ms: 1000
   retries: 2
 grpc:

+ 1 - 1
deploy/amd64-release/selftest.sh

@@ -36,4 +36,4 @@ raw_b64="$(sed -n 's/.*"raw_\{0,1\}payload"[[:space:]]*:[[:space:]]*"\([^"]*\)".
 payload_bytes="$(printf '%s' "$raw_b64" | base64 -d | wc -c)"
 [[ "$payload_bytes" -eq 193 ]]
 "${CTL[@]}" stop >/dev/null
-echo "HTH_AMD64_SELFTEST_PASS set_target_ack=PASS snapshot_payload_bytes=$payload_bytes profile=production"
+echo "HTH_AMD64_SELFTEST_PASS set_target_ack=PASS snapshot_payload_bytes=$payload_bytes profile=6400-control"

+ 1 - 1
deploy/amd64-release/verify-install.sh

@@ -39,7 +39,7 @@ SOURCE_COMMIT="$(json_string source_commit)"
 [[ -n "$VERSION" && -n "$SOURCE_COMMIT" ]] || fail "invalid release metadata"
 PROFILE="$(sed -n 's/^[[:space:]]*firmware_profile:[[:space:]]*//p' "$CONFIG" | head -n 1)"
 BACKEND="$(sed -n 's/^[[:space:]]*backend:[[:space:]]*//p' "$CONFIG" | head -n 1)"
-[[ "$PROFILE" == production || "$PROFILE" == 6400-control ]] || fail "installed profile is not Production: $PROFILE"
+[[ "$PROFILE" == 6400-control ]] || fail "installed profile is not canonical 6400-control: $PROFILE"
 
 PIDS=""
 for proc_dir in /proc/[0-9]*; do

+ 1 - 1
deploy/examples/hthd.6400-mock.yaml

@@ -10,7 +10,7 @@ sockets:
   observe_perm: "0660"
   control_perm: "0660"
 thermal:
-  firmware_profile: production
+  firmware_profile: 6400-control
   transaction_timeout_ms: 1000
   retries: 1
   mock_scenario: normal

+ 1 - 1
deploy/examples/hthd.6400-replay.yaml

@@ -12,7 +12,7 @@ sockets:
 replay:
   path: /var/lib/hth/6400-replay.jsonl
 thermal:
-  firmware_profile: production
+  firmware_profile: 6400-control
   transaction_timeout_ms: 1000
   retries: 0
 grpc:

+ 1 - 1
deploy/examples/hthd.6400-serial.yaml

@@ -14,7 +14,7 @@ sockets:
   observe_group: hth-observe
   control_group: hth-control
 thermal:
-  firmware_profile: production
+  firmware_profile: 6400-control
   transaction_timeout_ms: 1000
   retries: 1
 grpc:

Разница между файлами не показана из-за своего большого размера
+ 12 - 8
docs/6400/migration.md


+ 14 - 0
generated/6400/golden-vectors.json

@@ -0,0 +1,14 @@
+{
+  "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
+  "frames": {
+    "get_snapshot": "A55A02006D7B",
+    "get_snapshot_ack": "A55A8200F560",
+    "set_target_20": "A55A010114289A",
+    "set_target_70": "A55A0101469FE0",
+    "set_target_ack": "A55A8100A635",
+    "set_target_stop": "A55A0101009DC8",
+    "stimulus_ack": "A55A8300C453",
+    "stimulus_all_zero_one_second": "A55A03210100000000000000000000000000000000000000000000000000000000000000009782"
+  },
+  "schema": "prod2u-6400-golden-vectors-v1"
+}

Разница между файлами не показана из-за своего большого размера
+ 1126 - 0
generated/6400/host-contract.json


+ 8 - 0
generated/6400/import-source.json

@@ -0,0 +1,8 @@
+{
+  "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
+  "golden_vectors_file_sha256": "78f946cff044064d95d8098580cff871bf67cb614d105e4d400d52023b917145",
+  "schema": "hth-cpld-contract-import-v1",
+  "source_commit": "66f8ee052f4b1199224f0f3d58fe863fecd21c4d",
+  "source_contract_file_sha256": "971702eb7d7a113cd6d106d6f0486b8863194e06f15a3b97ed29067f3faf704f",
+  "source_repository": "cpld-temperature-control"
+}

+ 7 - 5
internal/config/config.go

@@ -11,6 +11,7 @@ import (
 
 	"gopkg.in/yaml.v3"
 	"hth/internal/profile"
+	"hth/internal/protocol6400"
 )
 
 type BackendKind string
@@ -350,11 +351,10 @@ func (c *Config) validate6400() error {
 	if c.DeviceID == "" {
 		return fmt.Errorf("config: device_id required")
 	}
-	switch c.Thermal.FirmwareProfile {
-	case "production", "6400-control", "identification", "6400-identification":
-	case "":
+	if c.Thermal.FirmwareProfile == "" {
 		return fmt.Errorf("config: thermal.firmware_profile required")
-	default:
+	}
+	if !protocol6400.IsCanonicalProfile(c.Thermal.FirmwareProfile) {
 		return fmt.Errorf("config: thermal.firmware_profile %q invalid", c.Thermal.FirmwareProfile)
 	}
 	if c.Sockets.Observe == "" || c.Sockets.Control == "" {
@@ -399,7 +399,9 @@ func (c *Config) validate6400() error {
 		return fmt.Errorf("config: thermal.retries must be 0..3")
 	}
 	switch c.Thermal.MockScenario {
-	case "", "normal", "invalid", "bmc-stale", "high-temperature", "ct-stale", "ack-loss", "crc-error", "epoch":
+	case "", "normal", "invalid", "bmc-stale", "high-temperature", "ct-stale",
+		"ack-loss", "get-ack-loss", "get-data-loss", "stimulus-ack-loss", "wrong-get-ack",
+		"crc-error", "epoch":
 	default:
 		return fmt.Errorf("config: thermal.mock_scenario %q invalid", c.Thermal.MockScenario)
 	}

+ 24 - 1
internal/config/thermal_6400_test.go

@@ -4,6 +4,8 @@ import (
 	"path/filepath"
 	"strings"
 	"testing"
+
+	"hth/internal/protocol6400"
 )
 
 func validThermal6400Config(t *testing.T) Config {
@@ -19,7 +21,28 @@ func validThermal6400Config(t *testing.T) Config {
 			Observe: filepath.Join(root, "observe.sock"),
 			Control: filepath.Join(root, "control.sock"),
 		},
-		Thermal: Thermal{FirmwareProfile: "production", Retries: 1, MockScenario: "normal"},
+		Thermal: Thermal{FirmwareProfile: protocol6400.ProfileControl, Retries: 1, MockScenario: "normal"},
+	}
+}
+
+func TestThermal6400ConfigAcceptsOnlyCanonicalProfiles(t *testing.T) {
+	for _, value := range []string{
+		protocol6400.ProfileControl,
+		protocol6400.ProfileIdentification,
+		protocol6400.ProfileSimDebug,
+	} {
+		cfg := validThermal6400Config(t)
+		cfg.Thermal.FirmwareProfile = value
+		if err := cfg.Validate(nil); err != nil {
+			t.Fatalf("canonical profile %q rejected: %v", value, err)
+		}
+	}
+	for _, value := range []string{"production", "identification"} {
+		cfg := validThermal6400Config(t)
+		cfg.Thermal.FirmwareProfile = value
+		if err := cfg.Validate(nil); err == nil {
+			t.Fatalf("legacy alias %q accepted", value)
+		}
 	}
 }
 

+ 16 - 3
internal/protocol6400/frame.go

@@ -55,11 +55,11 @@ func expectedLength(frameType byte) (int, error) {
 	switch frameType {
 	case CmdSetTarget:
 		return 1, nil
-	case CmdGetSnapshot, RspSetTargetAck, RspStimulusAck:
+	case CmdGetSnapshot, RspSetTargetAck, RspGetSnapshotAck, RspStimulusAck:
 		return 0, nil
 	case CmdSetStimulus:
 		return 33, nil
-	case RspSnapshot:
+	case RspSnapshotData:
 		return SnapshotPayloadLen, nil
 	default:
 		return 0, fmt.Errorf("%w: 0x%02X", ErrType, frameType)
@@ -125,8 +125,21 @@ func GetSnapshotRequest() []byte {
 	return value
 }
 
+func IsCanonicalProfile(profile string) bool {
+	switch profile {
+	case ProfileControl, ProfileIdentification, ProfileSimDebug:
+		return true
+	default:
+		return false
+	}
+}
+
+func StimulusSupported(profile string) bool {
+	return profile == ProfileIdentification || profile == ProfileSimDebug
+}
+
 func StimulusRequest(profile string, value Stimulus) ([]byte, error) {
-	if profile != "identification" && profile != "6400-identification" {
+	if !StimulusSupported(profile) {
 		return nil, ErrNotSupported
 	}
 	if value.DurationSeconds == 0 {

+ 31 - 2
internal/protocol6400/frame_test.go

@@ -29,6 +29,20 @@ func TestGeneratedGoldenFrames(t *testing.T) {
 	if got := GetSnapshotRequest(); hex.EncodeToString(got) != GoldenGetSnapshot {
 		t.Fatalf("GET got %x", got)
 	}
+	responses := map[byte]string{
+		RspSetTargetAck:   GoldenSetTargetAck,
+		RspGetSnapshotAck: GoldenGetSnapshotAck,
+		RspStimulusAck:    GoldenStimulusAck,
+	}
+	for frameType, want := range responses {
+		got, err := Encode(frameType, nil)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if hex.EncodeToString(got) != want {
+			t.Fatalf("response 0x%02x got %x want %s", frameType, got, want)
+		}
+	}
 }
 
 func TestTargetRangeAndCRC(t *testing.T) {
@@ -45,18 +59,33 @@ func TestTargetRangeAndCRC(t *testing.T) {
 }
 
 func TestProductionRejectsStimulus(t *testing.T) {
-	if _, err := StimulusRequest("production", Stimulus{DurationSeconds: 1}); !errors.Is(err, ErrNotSupported) {
+	if _, err := StimulusRequest(ProfileControl, Stimulus{DurationSeconds: 1}); !errors.Is(err, ErrNotSupported) {
 		t.Fatalf("production stimulus error %v", err)
 	}
+	if _, err := StimulusRequest("identification", Stimulus{DurationSeconds: 1}); !errors.Is(err, ErrNotSupported) {
+		t.Fatalf("legacy alias stimulus error %v", err)
+	}
 	if _, err := StimulusRequest("unknown", Stimulus{DurationSeconds: 1}); !errors.Is(err, ErrNotSupported) {
 		t.Fatalf("unknown profile stimulus error %v", err)
 	}
 	value := Stimulus{DurationSeconds: 1}
-	raw, err := StimulusRequest("identification", value)
+	raw, err := StimulusRequest(ProfileIdentification, value)
 	if err != nil {
 		t.Fatal(err)
 	}
 	if hex.EncodeToString(raw) != GoldenStimulusAllZeroOneSecond {
 		t.Fatalf("stimulus got %x", raw)
 	}
+	if _, err := StimulusRequest(ProfileSimDebug, value); err != nil {
+		t.Fatalf("sim-debug stimulus error %v", err)
+	}
+}
+
+func TestSnapshotACKAndDataTypesAreDistinct(t *testing.T) {
+	if RspGetSnapshotAck != 0x82 || RspSnapshotData != 0x42 {
+		t.Fatalf("GET response types ACK=0x%02x DATA=0x%02x", RspGetSnapshotAck, RspSnapshotData)
+	}
+	if _, err := Encode(RspGetSnapshotAck, make([]byte, SnapshotPayloadLen)); !errors.Is(err, ErrLength) {
+		t.Fatalf("0x82 with snapshot payload error %v", err)
+	}
 }

+ 11 - 2
internal/protocol6400/generated_contract.go

@@ -1,15 +1,21 @@
 // Code generated by tools/import_6400_contract.py; DO NOT EDIT.
 package protocol6400
 
-const ContractSHA256 = "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1"
+const ContractSHA256 = "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1"
+const SourceContractFileSHA256 = "971702eb7d7a113cd6d106d6f0486b8863194e06f15a3b97ed29067f3faf704f"
+const SourceCommit = "66f8ee052f4b1199224f0f3d58fe863fecd21c4d"
 const SnapshotPayloadLen = 193
 const CmdSetTarget byte = 0x01
 const CmdGetSnapshot byte = 0x02
 const CmdSetStimulus byte = 0x03
 const RspSetTargetAck byte = 0x81
-const RspSnapshot byte = 0x82
+const RspGetSnapshotAck byte = 0x82
+const RspSnapshotData byte = 0x42
 const RspStimulusAck byte = 0x83
 const HostBaud = 921600
+const ProfileControl = "6400-control"
+const ProfileIdentification = "6400-identification"
+const ProfileSimDebug = "6400-sim-debug"
 
 const SnapshotControlStateOffset = 0
 const SnapshotFaultFlagsOffset = 1
@@ -38,4 +44,7 @@ const GoldenSetTargetStop = "a55a0101009dc8"
 const GoldenSetTarget20 = "a55a010114289a"
 const GoldenSetTarget70 = "a55a0101469fe0"
 const GoldenGetSnapshot = "a55a02006d7b"
+const GoldenSetTargetAck = "a55a8100a635"
+const GoldenGetSnapshotAck = "a55a8200f560"
+const GoldenStimulusAck = "a55a8300c453"
 const GoldenStimulusAllZeroOneSecond = "a55a03210100000000000000000000000000000000000000000000000000000000000000009782"

+ 34 - 11
internal/thermalbackend/backend_test.go

@@ -24,27 +24,48 @@ func TestMockFaultScenariosAndRecovery(t *testing.T) {
 	}
 	for _, tc := range cases {
 		t.Run(tc.name, func(t *testing.T) {
-			value, payload, err := NewMock("production", tc.name).GetSnapshot(context.Background())
+			value, payload, err := NewMock(protocol6400.ProfileControl, tc.name).GetSnapshot(context.Background())
 			if err != nil || len(payload) != protocol6400.SnapshotPayloadLen || !tc.check(value) {
 				t.Fatalf("value=%+v len=%d err=%v", value, len(payload), err)
 			}
 		})
 	}
-	ack := NewMock("production", "ack-loss")
+	ack := NewMock(protocol6400.ProfileControl, "ack-loss")
 	if err := ack.SetTarget(context.Background(), 65); !errors.Is(err, context.DeadlineExceeded) {
 		t.Fatalf("ACK loss err=%v", err)
 	}
 	if err := ack.SetTarget(context.Background(), 65); err != nil {
 		t.Fatalf("idempotent retry err=%v", err)
 	}
-	crc := NewMock("production", "crc-error")
+	for _, scenario := range []string{"get-ack-loss", "get-data-loss"} {
+		mock := NewMock(protocol6400.ProfileControl, scenario)
+		if _, _, err := mock.GetSnapshot(context.Background()); !errors.Is(err, context.DeadlineExceeded) {
+			t.Fatalf("%s first GET err=%v", scenario, err)
+		}
+		if _, _, err := mock.GetSnapshot(context.Background()); err != nil {
+			t.Fatalf("%s recovery err=%v", scenario, err)
+		}
+	}
+	wrongACK := NewMock(protocol6400.ProfileControl, "wrong-get-ack")
+	if _, _, err := wrongACK.GetSnapshot(context.Background()); !errors.Is(err, protocol6400.ErrType) {
+		t.Fatalf("wrong GET ACK err=%v", err)
+	}
+	stimulusACK := NewMock(protocol6400.ProfileIdentification, "stimulus-ack-loss")
+	stimulus := protocol6400.Stimulus{DurationSeconds: 1}
+	if err := stimulusACK.RunStimulus(context.Background(), stimulus); !errors.Is(err, context.DeadlineExceeded) {
+		t.Fatalf("stimulus ACK loss err=%v", err)
+	}
+	if err := stimulusACK.RunStimulus(context.Background(), stimulus); err != nil {
+		t.Fatalf("stimulus retry err=%v", err)
+	}
+	crc := NewMock(protocol6400.ProfileControl, "crc-error")
 	if _, _, err := crc.GetSnapshot(context.Background()); !errors.Is(err, protocol6400.ErrCRC) {
 		t.Fatalf("CRC scenario err=%v", err)
 	}
 	if _, _, err := crc.GetSnapshot(context.Background()); err != nil {
 		t.Fatalf("CRC recovery err=%v", err)
 	}
-	epoch := NewMock("production", "epoch")
+	epoch := NewMock(protocol6400.ProfileControl, "epoch")
 	first, _, err := epoch.GetSnapshot(context.Background())
 	if err != nil {
 		t.Fatal(err)
@@ -63,11 +84,11 @@ func TestReplayStrictSnapshotsErrorsAndReadOnly(t *testing.T) {
 	value.CurrentTarget = 70
 	payload := protocol6400.EncodeSnapshot(value)
 	path := filepath.Join(t.TempDir(), "replay.jsonl")
-	text := `{"payload_hex":"` + hex.EncodeToString(payload) + `"}` + "\n" + `{"error":"crc"}` + "\n" + `{"error":"timeout"}` + "\n"
+	text := `{"ack":true,"payload_hex":"` + hex.EncodeToString(payload) + `"}` + "\n" + `{"ack":true,"error":"data-crc"}` + "\n" + `{"ack":false,"error":"ack-timeout"}` + "\n"
 	if err := os.WriteFile(path, []byte(text), 0o600); err != nil {
 		t.Fatal(err)
 	}
-	replay := NewReplay(path, "production")
+	replay := NewReplay(path, protocol6400.ProfileControl)
 	if err := replay.Open(context.Background()); err != nil {
 		t.Fatal(err)
 	}
@@ -94,18 +115,20 @@ func TestReplayStrictSnapshotsErrorsAndReadOnly(t *testing.T) {
 
 func TestReplayRejectsUnknownFieldsAndBadLength(t *testing.T) {
 	for name, content := range map[string]string{
-		"unknown":       `{"payload_hex":"00","extra":true}` + "\n",
-		"short":         `{"payload_hex":"00"}` + "\n",
-		"both":          `{"payload_hex":"00","error":"crc"}` + "\n",
+		"unknown":       `{"ack":true,"payload_hex":"00","extra":true}` + "\n",
+		"short":         `{"ack":true,"payload_hex":"00"}` + "\n",
+		"missing-ack":   `{"payload_hex":"00"}` + "\n",
+		"both":          `{"ack":true,"payload_hex":"00","error":"data-crc"}` + "\n",
 		"unknown-error": `{"error":"disconnect"}` + "\n",
-		"two-values":    `{"error":"crc"} {"error":"timeout"}` + "\n",
+		"bad-stage":     `{"ack":false,"error":"data-timeout"}` + "\n",
+		"two-values":    `{"ack":false,"error":"ack-crc"} {"ack":false,"error":"ack-timeout"}` + "\n",
 	} {
 		t.Run(name, func(t *testing.T) {
 			path := filepath.Join(t.TempDir(), "bad.jsonl")
 			if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
 				t.Fatal(err)
 			}
-			if err := NewReplay(path, "production").Open(context.Background()); err == nil {
+			if err := NewReplay(path, protocol6400.ProfileControl).Open(context.Background()); err == nil {
 				t.Fatal("invalid replay accepted")
 			}
 		})

+ 28 - 0
internal/thermalbackend/mock.go

@@ -13,7 +13,11 @@ type Mock struct {
 	scenario    string
 	snapshot    protocol6400.Snapshot
 	dropSetACK  bool
+	dropGetACK  bool
+	dropGetData bool
+	dropStimACK bool
 	crcError    bool
+	wrongGetACK bool
 	epochOnRead bool
 }
 
@@ -62,6 +66,14 @@ func NewMock(profile, scenario string) *Mock {
 		m.snapshot.CTAge = 0xffff
 	case "ack-loss":
 		m.dropSetACK = true
+	case "get-ack-loss":
+		m.dropGetACK = true
+	case "get-data-loss":
+		m.dropGetData = true
+	case "stimulus-ack-loss":
+		m.dropStimACK = true
+	case "wrong-get-ack":
+		m.wrongGetACK = true
 	case "crc-error":
 		m.crcError = true
 	case "epoch":
@@ -104,6 +116,14 @@ func (m *Mock) SetTarget(_ context.Context, target byte) error {
 func (m *Mock) GetSnapshot(context.Context) (protocol6400.Snapshot, []byte, error) {
 	m.mu.Lock()
 	defer m.mu.Unlock()
+	if m.dropGetACK {
+		m.dropGetACK = false
+		return protocol6400.Snapshot{}, nil, context.DeadlineExceeded
+	}
+	if m.wrongGetACK {
+		m.wrongGetACK = false
+		return protocol6400.Snapshot{}, nil, protocol6400.ErrType
+	}
 	if m.crcError {
 		m.crcError = false
 		return protocol6400.Snapshot{}, nil, protocol6400.ErrCRC
@@ -114,6 +134,10 @@ func (m *Mock) GetSnapshot(context.Context) (protocol6400.Snapshot, []byte, erro
 		m.snapshot.ControlEpoch++
 	}
 	value := m.snapshot
+	if m.dropGetData {
+		m.dropGetData = false
+		return protocol6400.Snapshot{}, nil, context.DeadlineExceeded
+	}
 	return value, protocol6400.EncodeSnapshot(value), nil
 }
 
@@ -130,5 +154,9 @@ func (m *Mock) RunStimulus(_ context.Context, value protocol6400.Stimulus) error
 	copy(m.snapshot.RearRequested[:], value.Rear[:])
 	copy(m.snapshot.RearApplied[:], value.Rear[:])
 	m.snapshot.ControlEpoch++
+	if m.dropStimACK {
+		m.dropStimACK = false
+		return context.DeadlineExceeded
+	}
 	return nil
 }

+ 21 - 4
internal/thermalbackend/replay.go

@@ -17,6 +17,7 @@ import (
 type ReplayRecord struct {
 	PayloadHex string `json:"payload_hex"`
 	Error      string `json:"error,omitempty"`
+	ACK        bool   `json:"ack"`
 }
 
 type Replay struct {
@@ -65,6 +66,9 @@ func (r *Replay) Open(context.Context) error {
 			return fmt.Errorf("thermal replay line %d: exactly one of payload_hex or error required", line)
 		}
 		if record.PayloadHex != "" {
+			if !record.ACK {
+				return fmt.Errorf("thermal replay line %d: snapshot data requires GET_SNAPSHOT_ACK", line)
+			}
 			payload, err := hex.DecodeString(record.PayloadHex)
 			if err != nil {
 				return fmt.Errorf("thermal replay line %d: %w", line, err)
@@ -72,8 +76,19 @@ func (r *Replay) Open(context.Context) error {
 			if _, err := protocol6400.DecodeSnapshot(payload); err != nil {
 				return fmt.Errorf("thermal replay line %d: %w", line, err)
 			}
-		} else if record.Error != "crc" && record.Error != "timeout" {
-			return fmt.Errorf("thermal replay line %d: unsupported error %q", line, record.Error)
+		} else {
+			switch record.Error {
+			case "ack-timeout", "ack-crc", "ack-type":
+				if record.ACK {
+					return fmt.Errorf("thermal replay line %d: %s cannot claim ACK", line, record.Error)
+				}
+			case "data-timeout", "data-crc":
+				if !record.ACK {
+					return fmt.Errorf("thermal replay line %d: %s requires ACK", line, record.Error)
+				}
+			default:
+				return fmt.Errorf("thermal replay line %d: unsupported error %q", line, record.Error)
+			}
 		}
 		r.records = append(r.records, record)
 	}
@@ -100,9 +115,11 @@ func (r *Replay) GetSnapshot(context.Context) (protocol6400.Snapshot, []byte, er
 	r.index++
 	switch record.Error {
 	case "":
-	case "crc":
+	case "ack-crc", "data-crc":
 		return protocol6400.Snapshot{}, nil, protocol6400.ErrCRC
-	case "timeout":
+	case "ack-type":
+		return protocol6400.Snapshot{}, nil, protocol6400.ErrType
+	case "ack-timeout", "data-timeout":
 		return protocol6400.Snapshot{}, nil, context.DeadlineExceeded
 	default:
 		return protocol6400.Snapshot{}, nil, fmt.Errorf("thermal replay error %q", record.Error)

+ 3 - 3
internal/thermalbackend/replay_fuzz_test.go

@@ -15,8 +15,8 @@ import (
 
 func FuzzThermalReplayOpen(f *testing.F) {
 	payload := protocol6400.EncodeSnapshot(protocol6400.Snapshot{CurrentTarget: 65})
-	f.Add([]byte(`{"payload_hex":"` + hex.EncodeToString(payload) + `"}` + "\n"))
-	f.Add([]byte("{\"error\":\"crc\"}\n{\"error\":\"timeout\"}\n"))
+	f.Add([]byte(`{"ack":true,"payload_hex":"` + hex.EncodeToString(payload) + `"}` + "\n"))
+	f.Add([]byte("{\"ack\":false,\"error\":\"ack-crc\"}\n{\"ack\":true,\"error\":\"data-timeout\"}\n"))
 	f.Add([]byte("not-json\n"))
 	f.Fuzz(func(t *testing.T, data []byte) {
 		if len(data) > 1<<16 {
@@ -26,7 +26,7 @@ func FuzzThermalReplayOpen(f *testing.F) {
 		if err := os.WriteFile(path, data, 0o600); err != nil {
 			t.Fatal(err)
 		}
-		replay := NewReplay(path, "production")
+		replay := NewReplay(path, protocol6400.ProfileControl)
 		if err := replay.Open(context.Background()); err != nil {
 			return
 		}

+ 5 - 3
internal/thermalbackend/serial_linux_test.go

@@ -14,7 +14,7 @@ import (
 )
 
 func TestSerialRejectsInvalidCommandsBeforeOpeningDevice(t *testing.T) {
-	serial := NewSerial("/path/that/must/not/exist", "production", 10*time.Millisecond, 0)
+	serial := NewSerial("/path/that/must/not/exist", protocol6400.ProfileControl, 10*time.Millisecond, 0)
 	if err := serial.SetTarget(context.Background(), 19); !errors.Is(err, protocol6400.ErrTargetRange) {
 		t.Fatalf("invalid target err=%v", err)
 	}
@@ -61,7 +61,9 @@ func TestSerialPTYTargetSnapshotAndStimulus(t *testing.T) {
 						return
 					}
 					value := protocol6400.Snapshot{CurrentTarget: 65, HostTargetSeen: true}
-					response, _ = protocol6400.Encode(protocol6400.RspSnapshot, protocol6400.EncodeSnapshot(value))
+					ack, _ := protocol6400.Encode(protocol6400.RspGetSnapshotAck, nil)
+					data, _ := protocol6400.Encode(protocol6400.RspSnapshotData, protocol6400.EncodeSnapshot(value))
+					response = append(ack, data...)
 				case 2:
 					if item.Frame.Type != protocol6400.CmdSetStimulus {
 						done <- errors.New("third request was not SET_STIMULUS")
@@ -79,7 +81,7 @@ func TestSerialPTYTargetSnapshotAndStimulus(t *testing.T) {
 		done <- nil
 	}()
 
-	serial := NewSerial(slave, "identification", 100*time.Millisecond, 0)
+	serial := NewSerial(slave, protocol6400.ProfileIdentification, 100*time.Millisecond, 0)
 	if err := serial.Open(context.Background()); err != nil {
 		t.Fatal(err)
 	}

+ 1 - 1
internal/thermalservice/service.go

@@ -152,7 +152,7 @@ func (s *Service) RunStimulus(ctx context.Context, req *hthv1.RunThermalStimulus
 	if err := s.validateDevice(req.GetDeviceId()); err != nil {
 		return nil, err
 	}
-	if s.profile != "identification" && s.profile != "6400-identification" {
+	if !protocol6400.StimulusSupported(s.profile) {
 		return nil, status.Error(codes.Unimplemented, "stimulus is not supported by production firmware")
 	}
 	if req.GetDurationSeconds() > 255 {

+ 12 - 7
internal/thermalservice/service_test.go

@@ -15,13 +15,15 @@ import (
 )
 
 func TestProductionTargetSnapshotStopAndStimulusBoundary(t *testing.T) {
-	svc := New("thermal-0", "production", thermalbackend.NewMock("production", "normal"), 50*time.Millisecond, 1)
+	svc := New("thermal-0", protocol6400.ProfileControl, thermalbackend.NewMock(protocol6400.ProfileControl, "normal"), 50*time.Millisecond, 1)
 	ctx := context.Background()
 	set, err := svc.SetTarget(ctx, &hthv1.SetThermalTargetRequest{DeviceId: "thermal-0", TemperatureC: 65})
 	if err != nil {
 		t.Fatal(err)
 	}
-	if !set.Committed || set.TargetTemperatureC != 65 || set.ContractSha256 != protocol6400.ContractSHA256 {
+	if !set.Committed || set.TargetTemperatureC != 65 ||
+		set.FirmwareProfile != protocol6400.ProfileControl ||
+		set.ContractSha256 != protocol6400.ContractSHA256 {
 		t.Fatalf("set result %+v", set)
 	}
 	snapshot, err := svc.GetSnapshot(ctx, &hthv1.GetThermalSnapshotRequest{DeviceId: "thermal-0"})
@@ -29,7 +31,10 @@ func TestProductionTargetSnapshotStopAndStimulusBoundary(t *testing.T) {
 		t.Fatal(err)
 	}
 	value := snapshot.GetSnapshot()
-	if value.GetCurrentTarget() != 65 || len(value.GetRawPayload()) != protocol6400.SnapshotPayloadLen || len(value.GetBmcRaw()) != 24 || len(value.GetCtRaw()) != 27 {
+	if value.GetFirmwareProfile() != protocol6400.ProfileControl ||
+		value.GetContractSha256() != protocol6400.ContractSHA256 ||
+		value.GetCurrentTarget() != 65 || len(value.GetRawPayload()) != protocol6400.SnapshotPayloadLen ||
+		len(value.GetBmcRaw()) != 24 || len(value.GetCtRaw()) != 27 {
 		t.Fatalf("snapshot target=%d payload=%d bmc=%d ct=%d", value.GetCurrentTarget(), len(value.GetRawPayload()), len(value.GetBmcRaw()), len(value.GetCtRaw()))
 	}
 	if _, err := svc.Stop(ctx, &hthv1.StopThermalRequest{DeviceId: "thermal-0"}); err != nil {
@@ -49,7 +54,7 @@ func TestProductionTargetSnapshotStopAndStimulusBoundary(t *testing.T) {
 }
 
 func TestIdentificationStimulusAndValidation(t *testing.T) {
-	svc := New("thermal-0", "identification", thermalbackend.NewMock("identification", "normal"), 50*time.Millisecond, 0)
+	svc := New("thermal-0", protocol6400.ProfileIdentification, thermalbackend.NewMock(protocol6400.ProfileIdentification, "normal"), 50*time.Millisecond, 0)
 	if _, err := svc.RunStimulus(context.Background(), validStimulusRequest("thermal-0")); err != nil {
 		t.Fatal(err)
 	}
@@ -94,7 +99,7 @@ type serializedBackend struct {
 }
 
 func (b *serializedBackend) Kind() string               { return "test" }
-func (b *serializedBackend) Profile() string            { return "production" }
+func (b *serializedBackend) Profile() string            { return protocol6400.ProfileControl }
 func (b *serializedBackend) Open(context.Context) error { return nil }
 func (b *serializedBackend) Close() error               { return nil }
 func (b *serializedBackend) enter() {
@@ -138,7 +143,7 @@ func TestProductionStimulusDoesNotTouchBackend(t *testing.T) {
 
 func TestInvalidCommandsDoNotTouchBackend(t *testing.T) {
 	backend := &serializedBackend{}
-	svc := New("thermal-0", "6400-identification", backend, time.Second, 0)
+	svc := New("thermal-0", protocol6400.ProfileIdentification, backend, time.Second, 0)
 	if _, err := svc.SetTarget(context.Background(), &hthv1.SetThermalTargetRequest{TemperatureC: 19}); status.Code(err) != codes.InvalidArgument {
 		t.Fatalf("invalid target code=%s err=%v", status.Code(err), err)
 	}
@@ -154,7 +159,7 @@ func TestInvalidCommandsDoNotTouchBackend(t *testing.T) {
 
 func TestServiceAllowsOnlyOneOutstandingTransaction(t *testing.T) {
 	backend := &serializedBackend{}
-	svc := New("thermal-0", "identification", backend, time.Second, 0)
+	svc := New("thermal-0", protocol6400.ProfileIdentification, backend, time.Second, 0)
 	start := make(chan struct{})
 	var wg sync.WaitGroup
 	wg.Add(2)

+ 40 - 16
internal/thermaltransport/client_linux.go

@@ -66,9 +66,12 @@ func (c *Client) Close() error {
 	return err
 }
 
-func (c *Client) transactLocked(ctx context.Context, request []byte, responseType byte) (protocol6400.Frame, error) {
+func (c *Client) transactSequenceLocked(ctx context.Context, request []byte, responseTypes []byte) ([]protocol6400.Frame, error) {
 	if c.file == nil {
-		return protocol6400.Frame{}, os.ErrClosed
+		return nil, os.ErrClosed
+	}
+	if len(responseTypes) == 0 {
+		return nil, errors.New("thermal transport: empty response sequence")
 	}
 	deadline := time.Now().Add(c.timeout)
 	if value, ok := ctx.Deadline(); ok && value.Before(deadline) {
@@ -78,56 +81,71 @@ func (c *Client) transactLocked(ctx context.Context, request []byte, responseTyp
 	c.parser.Reset()
 	written, err := c.file.Write(request)
 	if err != nil {
-		return protocol6400.Frame{}, err
+		return nil, err
 	}
 	if written != len(request) {
-		return protocol6400.Frame{}, io.ErrShortWrite
+		return nil, io.ErrShortWrite
 	}
 	buffer := make([]byte, 256)
+	frames := make([]protocol6400.Frame, 0, len(responseTypes))
 	for {
 		if err := ctx.Err(); err != nil {
-			return protocol6400.Frame{}, err
+			return nil, err
 		}
 		n, err := c.file.Read(buffer)
 		now := time.Now()
 		if n > 0 {
 			for _, item := range c.parser.Push(buffer[:n], now) {
 				if item.Err != nil {
-					return protocol6400.Frame{}, item.Err
+					return nil, item.Err
 				}
-				if item.Frame.Type != responseType {
-					return protocol6400.Frame{}, fmt.Errorf("unexpected response 0x%02x", item.Frame.Type)
+				if len(frames) >= len(responseTypes) || item.Frame.Type != responseTypes[len(frames)] {
+					return nil, fmt.Errorf(
+						"unexpected response 0x%02x at stage %d", item.Frame.Type, len(frames),
+					)
 				}
-				return item.Frame, nil
+				frames = append(frames, item.Frame)
+			}
+			if len(frames) == len(responseTypes) {
+				return frames, nil
 			}
 		}
 		if err != nil {
 			if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
-				return protocol6400.Frame{}, context.DeadlineExceeded
+				return nil, context.DeadlineExceeded
 			}
 			if errors.Is(err, io.EOF) && strings.HasPrefix(c.path, "/dev/pts/") {
 				continue
 			}
-			return protocol6400.Frame{}, err
+			return nil, err
 		}
 	}
 }
 
-func (c *Client) transact(ctx context.Context, request []byte, responseType byte) (protocol6400.Frame, error) {
+func (c *Client) transactSequence(ctx context.Context, request []byte, responseTypes ...byte) ([]protocol6400.Frame, error) {
 	c.mu.Lock()
 	defer c.mu.Unlock()
 	var last error
 	for attempt := 0; attempt <= c.retries; attempt++ {
-		frame, err := c.transactLocked(ctx, request, responseType)
+		frames, err := c.transactSequenceLocked(ctx, request, responseTypes)
 		if err == nil {
-			return frame, nil
+			return frames, nil
 		}
 		last = err
 		if ctx.Err() != nil {
 			break
 		}
 	}
-	return protocol6400.Frame{}, last
+	return nil, last
+
+}
+
+func (c *Client) transact(ctx context.Context, request []byte, responseType byte) (protocol6400.Frame, error) {
+	frames, err := c.transactSequence(ctx, request, responseType)
+	if err != nil {
+		return protocol6400.Frame{}, err
+	}
+	return frames[0], nil
 }
 
 func (c *Client) SetTarget(ctx context.Context, target byte) error {
@@ -142,10 +160,16 @@ func (c *Client) SetTarget(ctx context.Context, target byte) error {
 func (c *Client) Stop(ctx context.Context) error { return c.SetTarget(ctx, 0) }
 
 func (c *Client) GetSnapshot(ctx context.Context) (protocol6400.Snapshot, []byte, error) {
-	frame, err := c.transact(ctx, protocol6400.GetSnapshotRequest(), protocol6400.RspSnapshot)
+	frames, err := c.transactSequence(
+		ctx,
+		protocol6400.GetSnapshotRequest(),
+		protocol6400.RspGetSnapshotAck,
+		protocol6400.RspSnapshotData,
+	)
 	if err != nil {
 		return protocol6400.Snapshot{}, nil, err
 	}
+	frame := frames[1]
 	value, err := protocol6400.DecodeSnapshot(frame.Payload)
 	return value, frame.Payload, err
 }

+ 133 - 5
internal/thermaltransport/client_linux_test.go

@@ -4,6 +4,7 @@ package thermaltransport
 
 import (
 	"context"
+	"encoding/binary"
 	"errors"
 	"os"
 	"sync/atomic"
@@ -43,7 +44,9 @@ func serveThermalPTY(t *testing.T, master *os.File, dropFirstACK bool, done chan
 				payload := make([]byte, protocol6400.SnapshotPayloadLen)
 				payload[0] = 4
 				payload[3] = 70
-				response, _ = protocol6400.Encode(protocol6400.RspSnapshot, payload)
+				ack, _ := protocol6400.Encode(protocol6400.RspGetSnapshotAck, nil)
+				data, _ := protocol6400.Encode(protocol6400.RspSnapshotData, payload)
+				response = append(ack, data...)
 			default:
 				t.Errorf("unexpected request type %02x", item.Frame.Type)
 				return
@@ -69,7 +72,7 @@ func TestPTYTargetRetrySnapshotAndProductionStimulus(t *testing.T) {
 	defer unix.Close(slaveHold)
 	done := make(chan struct{})
 	go serveThermalPTY(t, master, true, done)
-	client, err := Open(slave, "production", 80*time.Millisecond, 1)
+	client, err := Open(slave, protocol6400.ProfileControl, 80*time.Millisecond, 1)
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -123,7 +126,7 @@ func TestPTYTargetExhaustsRetriesWithoutACK(t *testing.T) {
 		requests <- count
 	}()
 
-	client, err := Open(slave, "production", 20*time.Millisecond, 1)
+	client, err := Open(slave, protocol6400.ProfileControl, 20*time.Millisecond, 1)
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -169,7 +172,9 @@ func TestPTYSnapshotAndStimulusUseBoundedRetries(t *testing.T) {
 					getCount++
 					if getCount == 2 {
 						payload := make([]byte, protocol6400.SnapshotPayloadLen)
-						response, _ := protocol6400.Encode(protocol6400.RspSnapshot, payload)
+						ack, _ := protocol6400.Encode(protocol6400.RspGetSnapshotAck, nil)
+						data, _ := protocol6400.Encode(protocol6400.RspSnapshotData, payload)
+						response := append(ack, data...)
 						_, _ = master.Write(response)
 					}
 				case protocol6400.CmdSetStimulus:
@@ -183,7 +188,7 @@ func TestPTYSnapshotAndStimulusUseBoundedRetries(t *testing.T) {
 		}
 		done <- [2]int{getCount, stimulusCount}
 	}()
-	client, err := Open(slave, "identification", 20*time.Millisecond, 1)
+	client, err := Open(slave, protocol6400.ProfileIdentification, 20*time.Millisecond, 1)
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -205,3 +210,126 @@ func TestPTYSnapshotAndStimulusUseBoundedRetries(t *testing.T) {
 		t.Fatal("PTY server did not finish")
 	}
 }
+
+func TestPTYSnapshotRetriesBadACKFrames(t *testing.T) {
+	makeWrongLength := func() []byte {
+		raw, _ := protocol6400.Encode(
+			protocol6400.RspSnapshotData,
+			make([]byte, protocol6400.SnapshotPayloadLen),
+		)
+		raw[2] = protocol6400.RspGetSnapshotAck
+		binary.LittleEndian.PutUint16(raw[len(raw)-2:], protocol6400.CRC16(raw[2:len(raw)-2]))
+		return raw
+	}
+	makeBadCRC := func() []byte {
+		raw, _ := protocol6400.Encode(protocol6400.RspGetSnapshotAck, nil)
+		raw[len(raw)-1] ^= 1
+		return raw
+	}
+	wrongType, _ := protocol6400.Encode(protocol6400.RspSetTargetAck, nil)
+	for name, firstResponse := range map[string][]byte{
+		"wrong-type":   wrongType,
+		"wrong-length": makeWrongLength(),
+		"bad-crc":      makeBadCRC(),
+	} {
+		t.Run(name, func(t *testing.T) {
+			master, slaveHold, slave, err := serialtransport.OpenPTY()
+			if err != nil {
+				t.Fatal(err)
+			}
+			defer master.Close()
+			defer unix.Close(slaveHold)
+			requests := make(chan int, 1)
+			go func() {
+				parser := protocol6400.NewStreamParser(20 * time.Millisecond)
+				buffer := make([]byte, 128)
+				count := 0
+				for count < 2 {
+					n, readErr := master.Read(buffer)
+					if readErr != nil {
+						break
+					}
+					for _, item := range parser.Push(buffer[:n], time.Now()) {
+						if item.Err != nil || item.Frame.Type != protocol6400.CmdGetSnapshot {
+							continue
+						}
+						count++
+						if count == 1 {
+							_, _ = master.Write(firstResponse)
+							continue
+						}
+						ack, _ := protocol6400.Encode(protocol6400.RspGetSnapshotAck, nil)
+						data, _ := protocol6400.Encode(
+							protocol6400.RspSnapshotData,
+							make([]byte, protocol6400.SnapshotPayloadLen),
+						)
+						_, _ = master.Write(append(ack, data...))
+					}
+				}
+				requests <- count
+			}()
+			client, err := Open(slave, protocol6400.ProfileControl, 50*time.Millisecond, 1)
+			if err != nil {
+				t.Fatal(err)
+			}
+			defer client.Close()
+			ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+			defer cancel()
+			if _, _, err := client.GetSnapshot(ctx); err != nil {
+				t.Fatal(err)
+			}
+			select {
+			case count := <-requests:
+				if count != 2 {
+					t.Fatalf("GET attempts=%d want=2", count)
+				}
+			case <-time.After(time.Second):
+				t.Fatal("PTY server did not observe retry")
+			}
+		})
+	}
+}
+
+func TestPTYRepeatedTargetRequiresFreshACK(t *testing.T) {
+	master, slaveHold, slave, err := serialtransport.OpenPTY()
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer master.Close()
+	defer unix.Close(slaveHold)
+	requests := make(chan int, 1)
+	go func() {
+		parser := protocol6400.NewStreamParser(20 * time.Millisecond)
+		buffer := make([]byte, 128)
+		count := 0
+		for count < 2 {
+			n, readErr := master.Read(buffer)
+			if readErr != nil {
+				break
+			}
+			for _, item := range parser.Push(buffer[:n], time.Now()) {
+				if item.Err == nil && item.Frame.Type == protocol6400.CmdSetTarget {
+					count++
+					ack, _ := protocol6400.Encode(protocol6400.RspSetTargetAck, nil)
+					_, _ = master.Write(ack)
+				}
+			}
+		}
+		requests <- count
+	}()
+	client, err := Open(slave, protocol6400.ProfileControl, 50*time.Millisecond, 0)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer client.Close()
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	for range 2 {
+		if err := client.SetTarget(ctx, 65); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if count := <-requests; count != 2 {
+		t.Fatalf("identical SET requests=%d want=2", count)
+	}
+}

+ 11 - 2
profiles/6400-control/profile.json

@@ -1,6 +1,12 @@
 {
-  "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+  "allowed_commands": [
+    "SET_TARGET",
+    "GET_SNAPSHOT"
+  ],
+  "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
+  "golden_vectors_file_sha256": "78f946cff044064d95d8098580cff871bf67cb614d105e4d400d52023b917145",
   "one_outstanding_transaction": true,
+  "production": true,
   "profile_id": "6400-control",
   "schema": "hth-6400-profile-v1",
   "serial": {
@@ -9,7 +15,10 @@
     "parity": "N",
     "stop_bits": 1
   },
+  "simulation_only": false,
   "single_serial_owner": true,
   "snapshot_payload_length": 193,
-  "stimulus_supported": false
+  "source_commit": "66f8ee052f4b1199224f0f3d58fe863fecd21c4d",
+  "source_contract_file_sha256": "971702eb7d7a113cd6d106d6f0486b8863194e06f15a3b97ed29067f3faf704f",
+  "stimulus": false
 }

+ 12 - 2
profiles/6400-identification/profile.json

@@ -1,6 +1,13 @@
 {
-  "contract_sha256": "06c18dee5c27c4830398c8bc348d7fe868cde72aebe4c3be68b562f00e9b0fc1",
+  "allowed_commands": [
+    "SET_TARGET",
+    "GET_SNAPSHOT",
+    "SET_STIMULUS"
+  ],
+  "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
+  "golden_vectors_file_sha256": "78f946cff044064d95d8098580cff871bf67cb614d105e4d400d52023b917145",
   "one_outstanding_transaction": true,
+  "production": false,
   "profile_id": "6400-identification",
   "schema": "hth-6400-profile-v1",
   "serial": {
@@ -9,7 +16,10 @@
     "parity": "N",
     "stop_bits": 1
   },
+  "simulation_only": false,
   "single_serial_owner": true,
   "snapshot_payload_length": 193,
-  "stimulus_supported": true
+  "source_commit": "66f8ee052f4b1199224f0f3d58fe863fecd21c4d",
+  "source_contract_file_sha256": "971702eb7d7a113cd6d106d6f0486b8863194e06f15a3b97ed29067f3faf704f",
+  "stimulus": true
 }

+ 25 - 0
profiles/6400-sim-debug/profile.json

@@ -0,0 +1,25 @@
+{
+  "allowed_commands": [
+    "SET_TARGET",
+    "GET_SNAPSHOT",
+    "SET_STIMULUS"
+  ],
+  "contract_sha256": "9f1be59b6fe6f65fafe1f09a2c5d97076ac3e94996faa5834110066cc5714bd1",
+  "golden_vectors_file_sha256": "78f946cff044064d95d8098580cff871bf67cb614d105e4d400d52023b917145",
+  "one_outstanding_transaction": true,
+  "production": false,
+  "profile_id": "6400-sim-debug",
+  "schema": "hth-6400-profile-v1",
+  "serial": {
+    "baud": 921600,
+    "data_bits": 8,
+    "parity": "N",
+    "stop_bits": 1
+  },
+  "simulation_only": true,
+  "single_serial_owner": true,
+  "snapshot_payload_length": 193,
+  "source_commit": "66f8ee052f4b1199224f0f3d58fe863fecd21c4d",
+  "source_contract_file_sha256": "971702eb7d7a113cd6d106d6f0486b8863194e06f15a3b97ed29067f3faf704f",
+  "stimulus": true
+}

+ 9 - 0
sdk/python/README.md

@@ -22,3 +22,12 @@ open, not STOP), `GET_MOTOR_STATUS` exists, **no ACK**, FPGA watchdog 30 s fed
 only by valid `SET_ALL` after startup, `GET_TEMPERATURE` dropped during
 startup. Fan RPM / encoder / firmware version = `NOT_SUPPORTED`. Temperature
 channel mapping = `UNKNOWN`. Hardware validation: **NOT RUN**.
+
+## 6400 thermal facade
+
+`hth_sdk.thermal.connect_thermal()` accepts only `6400-control`,
+`6400-identification`, or `6400-sim-debug`; the old `production` and
+`identification` aliases are rejected. The facade validates the canonical
+profile ID and generated CPLD contract SHA-256 on every command and snapshot
+response. GET_SNAPSHOT wire sequencing (`0x82` ACK followed by `0x42` data) is
+owned by `hthd`; the SDK never opens or parses a serial stream.

Разница между файлами не показана из-за своего большого размера
+ 6 - 2
sdk/python/hth_sdk/generated/thermal/contract.py


+ 61 - 10
sdk/python/hth_sdk/thermal.py

@@ -8,7 +8,13 @@ import time
 from typing import Protocol, Sequence
 
 from hth_sdk.constants import DEFAULT_CONTROL_SOCKET, DEFAULT_OBSERVE_SOCKET
-from hth_sdk.generated.thermal.contract import SNAPSHOT_FIELDS, SNAPSHOT_PAYLOAD_LENGTH
+from hth_sdk.generated.thermal.contract import (
+    CANONICAL_PROFILES,
+    CONTRACT_SHA256,
+    PROFILE_CAPABILITIES,
+    SNAPSHOT_FIELDS,
+    SNAPSHOT_PAYLOAD_LENGTH,
+)
 
 
 class ThermalBackend(Protocol):
@@ -25,6 +31,25 @@ def _unix_target(path: str) -> str:
     return f"unix://{path}"
 
 
+def _canonical_profile(profile: str) -> str:
+    if profile not in CANONICAL_PROFILES:
+        allowed = ", ".join(CANONICAL_PROFILES)
+        raise ValueError(f"firmware_profile must be canonical ({allowed}), got {profile!r}")
+    return profile
+
+
+def _validate_binding(expected_profile: str, actual_profile: str, actual_contract: str) -> None:
+    expected_profile = _canonical_profile(expected_profile)
+    if actual_profile != expected_profile:
+        raise RuntimeError(
+            f"firmware profile mismatch: expected {expected_profile}, got {actual_profile or '<empty>'}"
+        )
+    if actual_contract != CONTRACT_SHA256:
+        raise RuntimeError(
+            f"contract hash mismatch: expected {CONTRACT_SHA256}, got {actual_contract or '<empty>'}"
+        )
+
+
 class GrpcThermalBackend:
     """Synchronous gRPC/UDS backend. It never opens a serial device."""
 
@@ -34,6 +59,7 @@ class GrpcThermalBackend:
         device_id: str,
         observe_socket: str,
         control_socket: str,
+        firmware_profile: str,
         timeout: float,
     ) -> None:
         try:
@@ -44,6 +70,7 @@ class GrpcThermalBackend:
         self._grpc = grpc
         self._pb2 = hth_pb2
         self._device_id = device_id
+        self._firmware_profile = _canonical_profile(firmware_profile)
         self._timeout = timeout
         self._observe_channel = grpc.insecure_channel(_unix_target(observe_socket))
         self._control_channel = grpc.insecure_channel(_unix_target(control_socket))
@@ -55,26 +82,41 @@ class GrpcThermalBackend:
         self._control_channel.close()
 
     def set_target(self, temperature_c: int) -> None:
-        self._control.SetTarget(
+        response = self._control.SetTarget(
             self._pb2.SetThermalTargetRequest(
                 device_id=self._device_id, temperature_c=temperature_c
             ),
             timeout=self._timeout,
         )
+        _validate_binding(
+            self._firmware_profile,
+            response.firmware_profile,
+            response.contract_sha256,
+        )
+        if not response.committed:
+            raise RuntimeError("SET_TARGET response did not confirm an ACK-backed commit")
 
     def get_snapshot_payload(self) -> bytes:
         response = self._observe.GetSnapshot(
             self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
             timeout=self._timeout,
         )
-        return bytes(response.snapshot.raw_payload)
+        return self._validated_snapshot_payload(response.snapshot)
 
     def capture_snapshot_payload(self) -> bytes:
         response = self._observe.CaptureSnapshot(
             self._pb2.GetThermalSnapshotRequest(device_id=self._device_id),
             timeout=self._timeout,
         )
-        return bytes(response.snapshot.raw_payload)
+        return self._validated_snapshot_payload(response.snapshot)
+
+    def _validated_snapshot_payload(self, snapshot) -> bytes:
+        _validate_binding(
+            self._firmware_profile,
+            snapshot.firmware_profile,
+            snapshot.contract_sha256,
+        )
+        return bytes(snapshot.raw_payload)
 
     def run_stimulus(
         self,
@@ -83,7 +125,7 @@ class GrpcThermalBackend:
         front: Sequence[int],
         rear: Sequence[int],
     ) -> None:
-        self._control.RunStimulus(
+        response = self._control.RunStimulus(
             self._pb2.RunThermalStimulusRequest(
                 device_id=self._device_id,
                 duration_seconds=duration_seconds,
@@ -93,6 +135,13 @@ class GrpcThermalBackend:
             ),
             timeout=self._timeout,
         )
+        _validate_binding(
+            self._firmware_profile,
+            response.firmware_profile,
+            response.contract_sha256,
+        )
+        if not response.committed:
+            raise RuntimeError("SET_STIMULUS response did not confirm an ACK-backed commit")
 
 
 def _field(payload: bytes, name: str):
@@ -138,9 +187,9 @@ class Snapshot:
 
 
 class ThermalHTH:
-    def __init__(self, backend: ThermalBackend, *, identification: bool = False):
+    def __init__(self, backend: ThermalBackend, *, firmware_profile: str = "6400-control"):
         self._backend = backend
-        self._identification = identification
+        self._firmware_profile = _canonical_profile(firmware_profile)
 
     def set_target(self, temperature_c: int) -> None:
         if temperature_c != 0 and not 20 <= temperature_c <= 70:
@@ -175,7 +224,7 @@ class ThermalHTH:
         return Snapshot(payload, decode_snapshot(payload), start, end)
 
     def run_stimulus(self, duration_seconds: int, ptc: Sequence[int], front: Sequence[int], rear: Sequence[int]) -> None:
-        if not self._identification:
+        if not PROFILE_CAPABILITIES[self._firmware_profile]["stimulus"]:
             raise NotImplementedError("stimulus is not supported by production firmware")
         if not 1 <= duration_seconds <= 255:
             raise ValueError("duration must be 1..255 seconds")
@@ -191,16 +240,18 @@ def connect_thermal(
     device_id: str = "prod2u-6400-0",
     observe_socket: str = DEFAULT_OBSERVE_SOCKET,
     control_socket: str = DEFAULT_CONTROL_SOCKET,
-    firmware_profile: str = "production",
+    firmware_profile: str = "6400-control",
     timeout: float = 3.0,
 ) -> ThermalHTH:
+    firmware_profile = _canonical_profile(firmware_profile)
     backend = GrpcThermalBackend(
         device_id=device_id,
         observe_socket=observe_socket,
         control_socket=control_socket,
+        firmware_profile=firmware_profile,
         timeout=timeout,
     )
     return ThermalHTH(
         backend,
-        identification=firmware_profile in {"identification", "6400-identification"},
+        firmware_profile=firmware_profile,
     )

+ 17 - 2
sdk/python/tests/test_thermal.py

@@ -2,7 +2,8 @@ from __future__ import annotations
 
 import pytest
 
-from hth_sdk.thermal import ThermalHTH, decode_snapshot
+from hth_sdk.generated.thermal.contract import CONTRACT_SHA256
+from hth_sdk.thermal import ThermalHTH, _validate_binding, decode_snapshot
 
 
 class Backend:
@@ -36,7 +37,7 @@ def test_production_rejects_stimulus() -> None:
 
 def test_identification_validates_and_runs_stimulus() -> None:
     backend = Backend()
-    hth = ThermalHTH(backend, identification=True)
+    hth = ThermalHTH(backend, firmware_profile="6400-identification")
     hth.run_stimulus(2, [1] * 24, [20] * 4, [30] * 4)
     assert backend.stimuli[0][0] == 2
 
@@ -44,3 +45,17 @@ def test_identification_validates_and_runs_stimulus() -> None:
 def test_snapshot_length_is_exact() -> None:
     with pytest.raises(ValueError):
         decode_snapshot(bytes(192))
+
+
+@pytest.mark.parametrize("profile", ["production", "identification", "unknown"])
+def test_profile_aliases_and_unknown_are_rejected(profile: str) -> None:
+    with pytest.raises(ValueError):
+        ThermalHTH(Backend(), firmware_profile=profile)
+
+
+def test_profile_and_contract_binding_is_strict() -> None:
+    _validate_binding("6400-control", "6400-control", CONTRACT_SHA256)
+    with pytest.raises(RuntimeError, match="profile mismatch"):
+        _validate_binding("6400-control", "6400-identification", CONTRACT_SHA256)
+    with pytest.raises(RuntimeError, match="contract hash mismatch"):
+        _validate_binding("6400-control", "6400-control", "0" * 64)

+ 10 - 6
tests/thermal_6400_uds_test.go

@@ -63,7 +63,7 @@ func startThermalMock(t *testing.T, profile string) (string, string) {
 }
 
 func TestThermal6400UDSProductionAPI(t *testing.T) {
-	observe, control := startThermalMock(t, "production")
+	observe, control := startThermalMock(t, protocol6400.ProfileControl)
 	obsConn, err := grpcserver.DialUnix(observe, time.Second)
 	if err != nil {
 		t.Fatal(err)
@@ -82,14 +82,18 @@ func TestThermal6400UDSProductionAPI(t *testing.T) {
 	if err != nil {
 		t.Fatal(err)
 	}
-	if !set.GetCommitted() || set.GetContractSha256() != protocol6400.ContractSHA256 {
+	if !set.GetCommitted() || set.GetFirmwareProfile() != protocol6400.ProfileControl ||
+		set.GetContractSha256() != protocol6400.ContractSHA256 {
 		t.Fatalf("set result %+v", set)
 	}
 	snapshot, err := obs.CaptureSnapshot(ctx, &hthv1.GetThermalSnapshotRequest{DeviceId: "prod2u-6400-0"})
 	if err != nil {
 		t.Fatal(err)
 	}
-	if snapshot.GetSnapshot().GetCurrentTarget() != 65 || len(snapshot.GetSnapshot().GetRawPayload()) != protocol6400.SnapshotPayloadLen {
+	if snapshot.GetSnapshot().GetFirmwareProfile() != protocol6400.ProfileControl ||
+		snapshot.GetSnapshot().GetContractSha256() != protocol6400.ContractSHA256 ||
+		snapshot.GetSnapshot().GetCurrentTarget() != 65 ||
+		len(snapshot.GetSnapshot().GetRawPayload()) != protocol6400.SnapshotPayloadLen {
 		t.Fatalf("snapshot %+v", snapshot.GetSnapshot())
 	}
 	_, err = ctl.RunStimulus(ctx, &hthv1.RunThermalStimulusRequest{
@@ -105,7 +109,7 @@ func TestThermal6400UDSProductionAPI(t *testing.T) {
 }
 
 func TestThermal6400CLIAndCapture(t *testing.T) {
-	observe, control := startThermalMock(t, "production")
+	observe, control := startThermalMock(t, protocol6400.ProfileControl)
 	hthctl := buildHostCmd(t, "hthctl", "./cmd/hthctl")
 	for _, args := range [][]string{
 		{"--observe-sock", observe, "--control-sock", control, "--device", "prod2u-6400-0", "--timeout", "2s", "--target", "65", "set-target"},
@@ -156,10 +160,10 @@ func TestThermal6400CLIAndCapture(t *testing.T) {
 }
 
 func TestThermal6400PythonSDKLiveUDS(t *testing.T) {
-	observe, control := startThermalMock(t, "identification")
+	observe, control := startThermalMock(t, protocol6400.ProfileIdentification)
 	code := strings.Join([]string{
 		"from hth_sdk.thermal import connect_thermal",
-		fmt.Sprintf("with connect_thermal(device_id='prod2u-6400-0', observe_socket=%q, control_socket=%q, firmware_profile='identification', timeout=2.0) as h:", observe, control),
+		fmt.Sprintf("with connect_thermal(device_id='prod2u-6400-0', observe_socket=%q, control_socket=%q, firmware_profile='6400-identification', timeout=2.0) as h:", observe, control),
 		"    h.set_target(60)",
 		"    s = h.get_snapshot()",
 		"    assert s.decoded['current_target'] == 60",

+ 62 - 8
tools/import_6400_contract.py

@@ -7,6 +7,7 @@ import argparse
 import hashlib
 import json
 from pathlib import Path
+import subprocess
 import sys
 from typing import Any
 
@@ -23,26 +24,56 @@ def camel(name: str) -> str:
     return "".join(item.upper() if item in {"bmc", "ct", "ptc"} else item.title() for item in name.split("_"))
 
 
-def outputs(source: Path) -> dict[Path, bytes]:
+def resolve_source_commit(source: Path, explicit: str | None) -> str:
+    source_root = source.resolve().parents[2]
+    detected = subprocess.run(
+        ["git", "-C", str(source_root), "rev-parse", "HEAD"],
+        check=True,
+        capture_output=True,
+        text=True,
+    ).stdout.strip().lower()
+    if explicit:
+        value = explicit.strip().lower()
+    else:
+        value = detected
+    if len(value) not in {40, 64} or any(ch not in "0123456789abcdef" for ch in value):
+        raise ValueError("source commit must be a full hexadecimal Git object id")
+    if value != detected:
+        raise ValueError(f"source commit {value} does not match source worktree HEAD {detected}")
+    return value
+
+
+def outputs(source: Path, source_commit: str | None = None) -> dict[Path, bytes]:
     raw = source.read_bytes()
     contract = json.loads(raw)
     contract_sha = contract["contract_sha256"]
     wire = contract["wire"]
     snapshot = contract["snapshot"]
-    golden = contract["golden_vectors"]["frames"]
+    golden_contract = contract["golden_vectors"]
+    golden = golden_contract["frames"]
+    source_file_sha = hashlib.sha256(raw).hexdigest()
+    golden_raw = json_bytes(golden_contract)
+    golden_file_sha = hashlib.sha256(golden_raw).hexdigest()
+    resolved_source_commit = resolve_source_commit(source, source_commit)
     go_lines = [
         "// Code generated by tools/import_6400_contract.py; DO NOT EDIT.",
         "package protocol6400",
         "",
         f'const ContractSHA256 = "{contract_sha}"',
+        f'const SourceContractFileSHA256 = "{source_file_sha}"',
+        f'const SourceCommit = "{resolved_source_commit}"',
         f"const SnapshotPayloadLen = {snapshot['payload_length']}",
         f"const CmdSetTarget byte = 0x{wire['commands']['SET_TARGET']['type']:02X}",
         f"const CmdGetSnapshot byte = 0x{wire['commands']['GET_SNAPSHOT']['type']:02X}",
         f"const CmdSetStimulus byte = 0x{wire['commands']['SET_STIMULUS']['type']:02X}",
         f"const RspSetTargetAck byte = 0x{wire['responses']['SET_TARGET_ACK']['type']:02X}",
-        f"const RspSnapshot byte = 0x{wire['responses']['SNAPSHOT_DATA']['type']:02X}",
+        f"const RspGetSnapshotAck byte = 0x{wire['responses']['GET_SNAPSHOT_ACK']['type']:02X}",
+        f"const RspSnapshotData byte = 0x{wire['responses']['SNAPSHOT_DATA']['type']:02X}",
         f"const RspStimulusAck byte = 0x{wire['responses']['SET_STIMULUS_ACK']['type']:02X}",
         f"const HostBaud = {wire['host_uart']['baud']}",
+        f'const ProfileControl = "6400-control"',
+        f'const ProfileIdentification = "6400-identification"',
+        f'const ProfileSimDebug = "6400-sim-debug"',
         "",
     ]
     for field in snapshot["fields"]:
@@ -53,16 +84,23 @@ def outputs(source: Path) -> dict[Path, bytes]:
         f'const GoldenSetTarget20 = "{golden["set_target_20"].lower()}"',
         f'const GoldenSetTarget70 = "{golden["set_target_70"].lower()}"',
         f'const GoldenGetSnapshot = "{golden["get_snapshot"].lower()}"',
+        f'const GoldenSetTargetAck = "{golden["set_target_ack"].lower()}"',
+        f'const GoldenGetSnapshotAck = "{golden["get_snapshot_ack"].lower()}"',
+        f'const GoldenStimulusAck = "{golden["stimulus_ack"].lower()}"',
         f'const GoldenStimulusAllZeroOneSecond = "{golden["stimulus_all_zero_one_second"].lower()}"',
         "",
     ])
     py_lines = [
         '"""Generated 6400 wire and snapshot constants."""',
         f'CONTRACT_SHA256 = "{contract_sha}"',
+        f'SOURCE_CONTRACT_FILE_SHA256 = "{source_file_sha}"',
+        f'SOURCE_COMMIT = "{resolved_source_commit}"',
         f"SNAPSHOT_PAYLOAD_LENGTH = {snapshot['payload_length']}",
         f"HOST_BAUD = {wire['host_uart']['baud']}",
         "COMMANDS = " + repr({name: value["type"] for name, value in wire["commands"].items()}),
         "RESPONSES = " + repr({name: value["type"] for name, value in wire["responses"].items()}),
+        "CANONICAL_PROFILES = " + repr(tuple(contract["canonical_profiles"])),
+        "PROFILE_CAPABILITIES = " + repr(contract["canonical_profiles"]),
         "SNAPSHOT_FIELDS = " + repr({field["name"]: field for field in snapshot["fields"]}),
         "CHANNEL_MAP = " + repr(contract["channel_map"]["channels"]),
         "",
@@ -70,31 +108,47 @@ def outputs(source: Path) -> dict[Path, bytes]:
     profile_common = {
         "schema": "hth-6400-profile-v1",
         "contract_sha256": contract_sha,
+        "source_commit": resolved_source_commit,
+        "source_contract_file_sha256": source_file_sha,
+        "golden_vectors_file_sha256": golden_file_sha,
         "serial": {"baud": wire["host_uart"]["baud"], "data_bits": 8, "parity": "N", "stop_bits": 1},
         "snapshot_payload_length": snapshot["payload_length"],
         "single_serial_owner": True,
         "one_outstanding_transaction": True,
     }
-    production = {**profile_common, "profile_id": "6400-control", "stimulus_supported": False}
-    identification = {**profile_common, "profile_id": "6400-identification", "stimulus_supported": True}
-    imported_sha = hashlib.sha256(raw).hexdigest()
+    production = {**profile_common, "profile_id": "6400-control", **contract["canonical_profiles"]["6400-control"]}
+    identification = {**profile_common, "profile_id": "6400-identification", **contract["canonical_profiles"]["6400-identification"]}
+    sim_debug = {**profile_common, "profile_id": "6400-sim-debug", **contract["canonical_profiles"]["6400-sim-debug"]}
+    import_meta = {
+        "schema": "hth-cpld-contract-import-v1",
+        "source_repository": "cpld-temperature-control",
+        "source_commit": resolved_source_commit,
+        "source_contract_file_sha256": source_file_sha,
+        "contract_sha256": contract_sha,
+        "golden_vectors_file_sha256": golden_file_sha,
+    }
     return {
         ROOT / "contracts/6400/host-contract.json": raw,
-        ROOT / "contracts/6400/SHA256SUMS": f"{imported_sha}  host-contract.json\n".encode(),
+        ROOT / "contracts/6400/SHA256SUMS": f"{source_file_sha}  host-contract.json\n".encode(),
+        ROOT / "generated/6400/host-contract.json": raw,
+        ROOT / "generated/6400/golden-vectors.json": golden_raw,
+        ROOT / "generated/6400/import-source.json": json_bytes(import_meta),
         ROOT / "internal/protocol6400/generated_contract.go": ("\n".join(go_lines)).encode(),
         ROOT / "sdk/python/hth_sdk/generated/thermal/contract.py": ("\n".join(py_lines)).encode(),
         ROOT / "sdk/python/hth_sdk/generated/thermal/__init__.py": b"from .contract import *  # noqa: F401,F403\n",
         ROOT / "profiles/6400-control/profile.json": json_bytes(production),
         ROOT / "profiles/6400-identification/profile.json": json_bytes(identification),
+        ROOT / "profiles/6400-sim-debug/profile.json": json_bytes(sim_debug),
     }
 
 
 def main() -> int:
     parser = argparse.ArgumentParser()
     parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)
+    parser.add_argument("--source-commit")
     parser.add_argument("--check", action="store_true")
     args = parser.parse_args()
-    expected = outputs(args.source)
+    expected = outputs(args.source, args.source_commit)
     drift = []
     for path, content in expected.items():
         if args.check:

+ 348 - 0
tools/rtl_uart_cosim/run_hthd_6400_pty_rtl.py

@@ -0,0 +1,348 @@
+#!/usr/bin/env python3
+"""Run real hthd through a PTY into the exact bound 6400 Production RTL."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import pty
+import select
+import shutil
+import socket
+import subprocess
+import sys
+import tempfile
+import termios
+import threading
+import time
+from pathlib import Path
+
+
+HERE = Path(__file__).resolve().parent
+HOST = HERE.parents[1]
+CPLD = Path(os.environ.get("HTH_CPLD_ROOT", HOST.parent / "cpld-temperature-control"))
+IMPORT_META = HOST / "generated/6400/import-source.json"
+CLOSURE = CPLD / "products/6400-control/source-closure.json"
+WRAPPER = CPLD / "tests/cocotb/prod2u_6400_v1_cocotb_top.v"
+
+
+def _bound_sources() -> list[Path]:
+    imported = json.loads(IMPORT_META.read_text(encoding="utf-8"))
+    expected_commit = imported["source_commit"]
+    actual_commit = subprocess.run(
+        ["git", "-C", str(CPLD), "rev-parse", "HEAD"],
+        check=True,
+        capture_output=True,
+        text=True,
+    ).stdout.strip()
+    if actual_commit != expected_commit:
+        raise RuntimeError(
+            f"CPLD worktree HEAD {actual_commit} != imported Production source {expected_commit}"
+        )
+    contract = CPLD / "generated/6400/host-contract.json"
+    actual_sha = hashlib.sha256(contract.read_bytes()).hexdigest()
+    if actual_sha != imported["source_contract_file_sha256"]:
+        raise RuntimeError(
+            f"CPLD contract file SHA {actual_sha} != imported {imported['source_contract_file_sha256']}"
+        )
+    closure = json.loads(CLOSURE.read_text(encoding="utf-8"))
+    sources = [CPLD / item for item in closure["sources"] if item.endswith(".v")]
+    missing = [str(path) for path in [*sources, WRAPPER] if not path.is_file()]
+    if missing:
+        raise RuntimeError("missing 6400 Production RTL: " + ", ".join(missing))
+    return sources
+
+
+def _set_raw(fd: int) -> None:
+    attrs = termios.tcgetattr(fd)
+    attrs[0] &= ~(
+        termios.IGNBRK
+        | termios.BRKINT
+        | termios.PARMRK
+        | termios.ISTRIP
+        | termios.INLCR
+        | termios.IGNCR
+        | termios.ICRNL
+        | termios.IXON
+    )
+    attrs[1] &= ~termios.OPOST
+    attrs[2] |= termios.CS8 | termios.CLOCAL | termios.CREAD
+    attrs[2] &= ~(termios.PARENB | termios.CSTOPB | termios.HUPCL)
+    attrs[3] &= ~(
+        termios.ECHO
+        | termios.ECHONL
+        | termios.ICANON
+        | termios.ISIG
+        | termios.IEXTEN
+    )
+    attrs[6][termios.VMIN] = 0
+    attrs[6][termios.VTIME] = 0
+    termios.tcsetattr(fd, termios.TCSANOW, attrs)
+
+
+def _shuttle(master_fd: int, conn: socket.socket, stop: threading.Event, log: Path) -> None:
+    up = down = 0
+    rtl_frame = bytearray()
+    with log.open("a", encoding="utf-8") as output:
+        while not stop.is_set():
+            try:
+                ready, _, _ = select.select([master_fd, conn], [], [], 0.05)
+            except (OSError, ValueError):
+                break
+            if master_fd in ready:
+                try:
+                    data = os.read(master_fd, 512)
+                except OSError:
+                    continue
+                if data:
+                    up += len(data)
+                    output.write(f"pty->rtl {data.hex()}\n")
+                    output.flush()
+                    conn.sendall(data)
+            if conn in ready:
+                try:
+                    data = conn.recv(512)
+                except OSError:
+                    continue
+                if data:
+                    down += len(data)
+                    output.write(f"rtl->pty {data.hex()}\n")
+                    output.flush()
+                    rtl_frame.extend(data)
+                    while True:
+                        while rtl_frame and rtl_frame[0] != 0xA5:
+                            del rtl_frame[0]
+                        if len(rtl_frame) < 4:
+                            break
+                        if rtl_frame[1] != 0x5A:
+                            del rtl_frame[0]
+                            continue
+                        frame_len = 6 + rtl_frame[3]
+                        if len(rtl_frame) < frame_len:
+                            break
+                        frame = bytes(rtl_frame[:frame_len])
+                        del rtl_frame[:frame_len]
+                        # Icarus advances one UART byte much slower than wall
+                        # time. Deliver each fully observed RTL frame in one
+                        # PTY write so the production 10 ms inter-byte guard is
+                        # not confused by simulator speed.
+                        os.write(master_fd, frame)
+        output.write(f"totals pty_to_rtl={up} rtl_to_pty={down}\n")
+
+
+def _write_config(path: Path, serial: str, runtime: Path) -> tuple[Path, Path]:
+    observe = runtime / "observe.sock"
+    control = runtime / "control.sock"
+    path.write_text(
+        f"""api_version: hth.api.v1
+product: 6400-front-rear-v1
+device_id: prod2u-6400-0
+display_name: 6400 RTL cosim
+backend: serial
+runtime_root: {runtime}
+serial:
+  path: {serial}
+sockets:
+  observe: {observe}
+  control: {control}
+  observe_perm: "0660"
+  control_perm: "0660"
+thermal:
+  firmware_profile: 6400-control
+  transaction_timeout_ms: 15000
+  retries: 1
+grpc:
+  reflection: false
+""",
+        encoding="utf-8",
+    )
+    return observe, control
+
+
+def _run_sim() -> int:
+    try:
+        from cocotb_tools.runner import get_runner
+    except ModuleNotFoundError:
+        from cocotb.runner import get_runner
+
+    runner = get_runner("icarus")
+    runner.build(
+        sources=[*_bound_sources(), WRAPPER],
+        hdl_toplevel="prod2u_6400_v1_cocotb_top",
+        build_dir=os.environ["HTH_SIM_DIR"],
+        build_args=["-g2012", "-I", str(CPLD)],
+        parameters={"ENABLE_STIMULUS": 0},
+        always=True,
+    )
+    runner.test(
+        hdl_toplevel="prod2u_6400_v1_cocotb_top",
+        test_module="test_hthd_6400_pty_bridge",
+        test_dir=HERE,
+        build_dir=os.environ["HTH_SIM_DIR"],
+        results_xml=os.environ["HTH_RESULTS_XML"],
+        extra_env={
+            "HTH_UART_BRIDGE": os.environ["HTH_UART_BRIDGE"],
+            "HTH_RTL_RESULT": os.environ["HTH_RTL_RESULT"],
+            "HTH_BRIDGE_READY": os.environ["HTH_BRIDGE_READY"],
+            "HTH_SIM_DONE": os.environ["HTH_SIM_DONE"],
+            "PYTHONPATH": str(HERE),
+        },
+    )
+    return 0
+
+
+def _wait_path(path: Path, timeout: float) -> None:
+    deadline = time.monotonic() + timeout
+    while time.monotonic() < deadline:
+        if path.exists():
+            return
+        time.sleep(0.05)
+    raise TimeoutError(f"timed out waiting for {path}")
+
+
+def main() -> int:
+    if "--sim" in sys.argv:
+        return _run_sim()
+
+    if not shutil.which("iverilog") or not shutil.which("vvp"):
+        print("6400 hthd PTY RTL cosim: NOT RUN (Icarus missing)")
+        return 2
+    try:
+        import cocotb  # noqa: F401
+        import grpc  # noqa: F401
+    except ImportError as exc:
+        print(f"6400 hthd PTY RTL cosim: NOT RUN ({exc})")
+        return 2
+    try:
+        _bound_sources()
+    except Exception as exc:
+        print(f"6400 hthd PTY RTL cosim: NOT RUN ({exc})")
+        return 2
+
+    hthd_bin = Path(os.environ.get("HTH_HTHD_BIN", ""))
+    if not hthd_bin.is_file():
+        print("6400 hthd PTY RTL cosim: NOT RUN (set HTH_HTHD_BIN)")
+        return 2
+
+    requested = os.environ.get("HTH_COSIM_RUN_DIR")
+    if requested:
+        build = Path(requested)
+        build.mkdir(parents=True, exist_ok=False)
+    else:
+        build = Path(tempfile.mkdtemp(prefix="hth-6400-rtl-"))
+    runtime = build / "runtime"
+    runtime.mkdir()
+    sim_dir = build / "sim"
+    result = build / "result.txt"
+    ready = build / "bridge.ready"
+    done = build / "sim.done"
+    results_xml = build / "results.xml"
+    bridge = build / "uart.bridge"
+    config = build / "hthd.yaml"
+    uart_log = build / "uart.log"
+
+    master, slave = pty.openpty()
+    _set_raw(master)
+    _set_raw(slave)
+    observe, control = _write_config(config, os.ttyname(slave), runtime)
+
+    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+    server.bind(str(bridge))
+    server.listen(1)
+    server.settimeout(90)
+    env = os.environ.copy()
+    env.update(
+        {
+            "HTH_UART_BRIDGE": str(bridge),
+            "HTH_RTL_RESULT": str(result),
+            "HTH_BRIDGE_READY": str(ready),
+            "HTH_SIM_DONE": str(done),
+            "HTH_SIM_DIR": str(sim_dir),
+            "HTH_RESULTS_XML": str(results_xml),
+            "PYTHONPATH": os.pathsep.join((str(HERE), str(CPLD), env.get("PYTHONPATH", ""))),
+        }
+    )
+
+    simulator = subprocess.Popen(
+        [sys.executable, "-B", str(Path(__file__).resolve()), "--sim"],
+        cwd=HERE,
+        env=env,
+    )
+    hthd: subprocess.Popen | None = None
+    conn: socket.socket | None = None
+    stop = threading.Event()
+    try:
+        conn, _ = server.accept()
+        threading.Thread(
+            target=_shuttle, args=(master, conn, stop, uart_log), daemon=True
+        ).start()
+        _wait_path(ready, 30)
+        hthd = subprocess.Popen(
+            [str(hthd_bin), "--config", str(config)],
+            cwd=HOST,
+            stdout=(build / "hthd.stdout").open("w", encoding="utf-8"),
+            stderr=(build / "hthd.stderr").open("w", encoding="utf-8"),
+        )
+        _wait_path(observe, 10)
+        _wait_path(control, 10)
+
+        sys.path.insert(0, str(HOST / "sdk/python"))
+        from hth_sdk.thermal import connect_thermal
+
+        with connect_thermal(
+            device_id="prod2u-6400-0",
+            observe_socket=str(observe),
+            control_socket=str(control),
+            firmware_profile="6400-control",
+            timeout=40.0,
+        ) as thermal:
+            thermal.set_target(60)
+            snapshot = thermal.get_snapshot()
+            if len(snapshot.payload) != 193:
+                raise AssertionError(f"snapshot length {len(snapshot.payload)} != 193")
+            if snapshot.decoded["current_target"] != 60:
+                raise AssertionError(f"target did not commit: {snapshot.decoded['current_target']}")
+            try:
+                thermal.run_stimulus(1, [0] * 24, [0] * 4, [0] * 4)
+            except NotImplementedError:
+                pass
+            else:
+                raise AssertionError("Production profile exposed stimulus")
+            thermal.stop()
+
+        result.write_text(
+            "PASS profile=6400-control set_ack=PASS get_ack=PASS "
+            "snapshot_data=193 stimulus=REJECTED\n",
+            encoding="utf-8",
+        )
+        done.write_text("done\n", encoding="utf-8")
+        if simulator.wait(timeout=60) != 0:
+            raise RuntimeError("cocotb simulator failed")
+        print("RTL_HTHD_6400_PTY_UART_PASS")
+        print(result.read_text(encoding="utf-8").strip())
+        print(f"artifacts={build}")
+        return 0
+    finally:
+        stop.set()
+        if hthd is not None:
+            hthd.terminate()
+            try:
+                hthd.wait(timeout=5)
+            except subprocess.TimeoutExpired:
+                hthd.kill()
+        if simulator.poll() is None:
+            simulator.terminate()
+            try:
+                simulator.wait(timeout=5)
+            except subprocess.TimeoutExpired:
+                simulator.kill()
+        if conn is not None:
+            conn.close()
+        server.close()
+        os.close(master)
+        os.close(slave)
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 125 - 0
tools/rtl_uart_cosim/test_hthd_6400_pty_bridge.py

@@ -0,0 +1,125 @@
+"""Cocotb UART-bit bridge between real hthd PTY traffic and the 6400 RTL."""
+
+from __future__ import annotations
+
+import os
+import queue
+import socket
+import threading
+from pathlib import Path
+
+import cocotb
+from cocotb.triggers import FallingEdge, ReadWrite, RisingEdge, Timer, with_timeout
+
+
+CLKS_PER_BIT = 27  # 25 MHz / 921600 baud, as frozen by the 6400 contract.
+
+
+async def clocks(dut, count: int) -> None:
+    if count < 32:
+        for _ in range(count):
+            await RisingEdge(dut.sys_clk)
+        return
+    await Timer((count - 1) * 40, units="ns")
+    await RisingEdge(dut.sys_clk)
+
+
+async def send_uart_byte(dut, value: int) -> None:
+    await ReadWrite()
+    dut.host_rs232_rx.value = 0
+    await clocks(dut, CLKS_PER_BIT)
+    for bit in range(8):
+        await ReadWrite()
+        dut.host_rs232_rx.value = (value >> bit) & 1
+        await clocks(dut, CLKS_PER_BIT)
+    await ReadWrite()
+    dut.host_rs232_rx.value = 1
+    await clocks(dut, CLKS_PER_BIT)
+
+
+async def receive_uart_byte(dut) -> int:
+    while int(dut.host_rs232_tx.value) != 1:
+        await clocks(dut, 1)
+    await FallingEdge(dut.host_rs232_tx)
+    await clocks(dut, CLKS_PER_BIT + CLKS_PER_BIT // 2)
+    value = 0
+    for bit in range(8):
+        value |= int(dut.host_rs232_tx.value) << bit
+        await clocks(dut, CLKS_PER_BIT)
+    return value
+
+
+def socket_queues(sock: socket.socket) -> tuple[queue.Queue[int], queue.Queue[int]]:
+    host_to_rtl: queue.Queue[int] = queue.Queue(maxsize=512)
+    rtl_to_host: queue.Queue[int] = queue.Queue()
+
+    def reader() -> None:
+        try:
+            while data := sock.recv(512):
+                for value in data:
+                    host_to_rtl.put(value)
+        except OSError:
+            return
+
+    def writer() -> None:
+        try:
+            while True:
+                sock.sendall(bytes((rtl_to_host.get(),)))
+        except OSError:
+            return
+
+    threading.Thread(target=reader, daemon=True).start()
+    threading.Thread(target=writer, daemon=True).start()
+    return host_to_rtl, rtl_to_host
+
+
+@cocotb.test()
+async def test_hthd_6400_set_get_ack_data(dut):
+    result = Path(os.environ["HTH_RTL_RESULT"])
+    done = Path(os.environ["HTH_SIM_DONE"])
+    result.write_text("RUNNING\n", encoding="utf-8")
+    dut.host_rs232_rx.value = 1
+    dut.host_ttl_rx.value = 1
+    dut.bmc_rs232_rx.value = 1
+    dut.tick_1s_test.value = 0
+    dut.reset_test.value = 0
+    await with_timeout(RisingEdge(dut.rst_n_mon), 2, "ms")
+
+    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+    sock.connect(os.environ["HTH_UART_BRIDGE"])
+    host_to_rtl, rtl_to_host = socket_queues(sock)
+    Path(os.environ["HTH_BRIDGE_READY"]).write_text("ready\n", encoding="utf-8")
+
+    async def drive_host_rx() -> None:
+        while True:
+            try:
+                value = host_to_rtl.get_nowait()
+            except queue.Empty:
+                await Timer(1, units="us")
+                continue
+            await send_uart_byte(dut, value)
+
+    async def sample_host_tx() -> None:
+        while True:
+            try:
+                value = await with_timeout(receive_uart_byte(dut), 5, "sec")
+                rtl_to_host.put(value)
+            except Exception:
+                await Timer(1, units="us")
+
+    cocotb.start_soon(drive_host_rx())
+    cocotb.start_soon(sample_host_tx())
+
+    for _ in range(300_000):
+        if done.is_file():
+            break
+        await Timer(10, units="us")
+    else:
+        raise AssertionError("host did not complete the 6400 UART transaction sequence")
+
+    text = result.read_text(encoding="utf-8")
+    assert text.startswith("PASS"), text
+    assert int(dut.target_commit_count_mon.value) >= 2  # target 60, then safe stop 0
+    assert int(dut.host_response_count_mon.value) >= 4  # ACK, ACK+DATA, ACK
+    assert int(dut.current_target_mon.value) == 0
+    sock.close()