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

Release 0.8.1.30: dual-disconnect/watchdog protection, 5-tier HIL sim & Phase 0 P0/P1 fixes

XJKJ STL 1 неделя назад
Родитель
Сommit
45887e3570
46 измененных файлов с 7771 добавлено и 176 удалено
  1. 2 0
      .gitignore
  2. 1 1
      Dockerfile
  3. 1 1
      VERSION
  4. 1 1
      deploy/pxe-dhcp/entrypoint.sh
  5. 2 0
      deploy/stl-backend.service
  6. 2 2
      docker-compose.yml
  7. 16 0
      docs/QT_CLIENT_API_ZH.md
  8. 38 0
      docs/WEBSOCKET_API_ZH.md
  9. 19 4
      native/stl_accel/c_bridge.c
  10. 277 54
      native/stl_accel/src/actors.rs
  11. 64 10
      native/stl_accel/src/api.rs
  12. 37 0
      native/stl_accel/src/commands.rs
  13. 19 5
      native/stl_accel/src/devices.rs
  14. 41 13
      native/stl_accel/src/json.rs
  15. 513 2
      native/stl_accel/src/main.rs
  16. 33 10
      native/stl_accel/src/pxe.rs
  17. 427 1
      native/stl_accel/src/results.rs
  18. 79 3
      native/stl_accel/src/storage.rs
  19. 84 5
      native/stl_accel/src/thermal_mcu.rs
  20. 440 24
      native/stl_accel/src/workflow.rs
  21. 36 0
      sim/README.md
  22. 1378 0
      sim/hil_cluster/bmc_ssh_hil_sim.c
  23. 451 0
      sim/hil_cluster/cluster_harness.py
  24. 1023 0
      sim/hil_cluster/dut_and_hood_sim.py
  25. 134 0
      sim/hil_cluster/smoke_test_bmc_ssh.c
  26. 553 0
      sim/hil_cluster/test_tier2_hil_e2e.py
  27. 657 0
      sim/kvm_uefi_tier/test_tier3_kvm_uefi_e2e.py
  28. 90 0
      sim/qt_e2e/qt_hil_e2e_test.pro
  29. 230 0
      sim/qt_e2e/test_tier5_qt_xvfb_e2e.py
  30. 173 0
      sim/qt_e2e/tst_qt_hil_e2e.cpp
  31. 230 0
      sim/run_all_tiers.py
  32. 394 0
      sim/web_e2e/test_tier4_chrome_web_e2e.py
  33. 1 1
      src/backendlink.cpp
  34. 27 4
      src/detailview.cpp
  35. 22 4
      src/mainwindow.cpp
  36. 1 0
      src/mainwindow.h
  37. 39 3
      src/overviewview.cpp
  38. 36 0
      src/stationdata.cpp
  39. 6 0
      src/stationdata.h
  40. 27 4
      web/app.js
  41. 76 6
      web/boot-plan-controls.js
  42. 5 3
      web/dimm-overview.js
  43. 1 1
      web/firmware-controls.js
  44. 11 10
      web/index.html
  45. 55 2
      web/stage-progress.js
  46. 19 2
      web/transport.js

+ 2 - 0
.gitignore

@@ -14,3 +14,5 @@ local.env
 config/station0-live.json
 *.zip
 *.bundle
+__pycache__/
+*.pyc

+ 1 - 1
Dockerfile

@@ -14,7 +14,7 @@ COPY config/ ./config/
 COPY build/native/stl_native_server /usr/local/bin/stl_native_server
 
 ARG STL_BUILD_COMMIT=vd012-native
-ARG STL_VERSION=0.8.1.29
+ARG STL_VERSION=0.8.1.30
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
     STL_VERSION=${STL_VERSION}
 

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.8.1.29
+0.8.1.30

+ 1 - 1
deploy/pxe-dhcp/entrypoint.sh

@@ -18,7 +18,7 @@ fi
 
 ip link set "$PXE_IFACE" up || true
 if ! ip -4 addr show dev "$PXE_IFACE" | grep -q "${PXE_SERVER_IP}/24"; then
-  ip addr add "${PXE_SERVER_IP}/24" brd 192.168.0.255 dev "$PXE_IFACE" || true
+  ip addr add "${PXE_SERVER_IP}/24" brd + dev "$PXE_IFACE" || true
 fi
 
 cat > /etc/dnsmasq.pxe.conf << EOF

+ 2 - 0
deploy/stl-backend.service

@@ -7,6 +7,8 @@ After=network-online.target
 Type=simple
 User=stl
 Group=stl
+AmbientCapabilities=CAP_NET_BIND_SERVICE
+CapabilityBoundingSet=CAP_NET_BIND_SERVICE
 WorkingDirectory=/opt/xjkj-stl
 EnvironmentFile=/etc/xjkj-stl/stl-backend.env
 ExecStart=/usr/local/bin/stl_native_server --config /etc/xjkj-stl/station0-live.json --web-listen 0.0.0.0:8080 --tftp-listen 0.0.0.0:69 --data-dir /var/lib/xjkj-stl --web-dir /opt/xjkj-stl/web --contracts /opt/xjkj-stl/contracts/firmware-vd012.json

+ 2 - 2
docker-compose.yml

@@ -3,9 +3,9 @@ services:
     build:
       context: .
       args:
-        STL_VERSION: ${STL_VERSION:-0.8.1.29}
+        STL_VERSION: ${STL_VERSION:-0.8.1.30}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
-    image: xjkj-stl:0.8.1.29
+    image: xjkj-stl:0.8.1.30
     container_name: xjkj-stl-backend
     restart: unless-stopped
     stop_grace_period: 30s

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


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


+ 19 - 4
native/stl_accel/c_bridge.c

@@ -1546,13 +1546,15 @@ int c_ipmi_open(
         }
     }
     if (rc != 0) {
+        int final_err = ipmi_ctx_errnum(ctx);
         ipmi_ctx_destroy(ctx);
-        return -1;
+        return (final_err == IPMI_ERR_CONNECTION_TIMEOUT) ? -2 : -1;
     }
 
     pthread_mutex_lock(&g_slots_lock);
     int idx = -1;
     for (int i = 0; i < MAX_IPMI_SLOTS; i++) {
+        pthread_mutex_lock(&g_ipmi_slots[i].mu);
         if (!g_ipmi_slots[i].in_use) {
             idx = i;
             g_ipmi_slots[i].in_use = 1;
@@ -1571,11 +1573,13 @@ int c_ipmi_open(
                 }
                 safe_host[hi] = '\0';
                 snprintf(g_ipmi_slots[i].sdr_cache_path, sizeof(g_ipmi_slots[i].sdr_cache_path),
-                         "/tmp/stl_sdr_%d_%s.cache", i, safe_host);
+                         "/tmp/stl_sdr_%ld_%d_%s.cache", (long)getpid(), i, safe_host);
                 unlink(g_ipmi_slots[i].sdr_cache_path);
             }
+            pthread_mutex_unlock(&g_ipmi_slots[i].mu);
             break;
         }
+        pthread_mutex_unlock(&g_ipmi_slots[i].mu);
     }
     pthread_mutex_unlock(&g_slots_lock);
 
@@ -1590,24 +1594,35 @@ int c_ipmi_open(
 void c_ipmi_close(int handle) {
     StlIpmiSlot *slot = get_ipmi_slot(handle);
     if (!slot) return;
+    pthread_mutex_lock(&g_slots_lock);
     pthread_mutex_lock(&slot->mu);
     if (slot->in_use) {
         if (slot->ctx) {
-            (void)ipmi_ctx_close(slot->ctx);
+            if (slot->alive) {
+                (void)ipmi_ctx_close(slot->ctx);
+            }
             ipmi_ctx_destroy(slot->ctx);
             slot->ctx = NULL;
         }
+        if (slot->sdr_cache_path[0]) {
+            unlink(slot->sdr_cache_path);
+            slot->sdr_cache_path[0] = '\0';
+        }
         slot->alive  = 0;
         slot->in_use = 0;
         slot->host[0] = '\0';
     }
     pthread_mutex_unlock(&slot->mu);
+    pthread_mutex_unlock(&g_slots_lock);
 }
 
 int c_ipmi_is_alive(int handle) {
     StlIpmiSlot *slot = get_ipmi_slot(handle);
     if (!slot) return 0;
-    return (slot->in_use && slot->alive && slot->ctx != NULL) ? 1 : 0;
+    pthread_mutex_lock(&slot->mu);
+    int alive = (slot->in_use && slot->alive && slot->ctx != NULL) ? 1 : 0;
+    pthread_mutex_unlock(&slot->mu);
+    return alive;
 }
 
 int c_ipmi_chassis_status(int handle, int *out_power_on, char *out_buf, size_t out_cap) {

+ 277 - 54
native/stl_accel/src/actors.rs

@@ -7,7 +7,7 @@ use crate::commands::{
 };
 use crate::devices::{
     close_station_pty, flush_tx_pacer, open_station_pty, poll_station_listener, poll_station_pty,
-    probe_tcp_port, run_ipmi_with_session, update_dimms_from_bmc_sdr,
+    probe_tcp_port, run_ipmi_with_session, update_dimms_from_bmc_sdr, write_station_paced,
     PersistentIpmiSession,
 };
 use crate::firmware::FirmwareContract;
@@ -16,12 +16,12 @@ use crate::lib;
 use crate::results::{now_ms, patch_timing_fields, StationState};
 use crate::storage::{strip_private_keys_recursive};
 use crate::workflow::{
-    apply_profile_to_station, control_boot_plan_impl, step_boot_plan, step_task_batch,
-    submit_task_batch,
+    apply_profile_to_station, control_boot_plan_impl, evaluate_stage_watchdog, step_boot_plan,
+    step_task_batch, submit_task_batch,
 };
 use std::path::PathBuf;
 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
-use std::sync::{mpsc, Arc, Condvar, Mutex, RwLock};
+use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, RwLock};
 use std::thread;
 use std::time::{Duration, Instant};
 
@@ -242,6 +242,7 @@ pub struct PushBroadcaster {
     pub qt_clean_senders: Mutex<Vec<mpsc::Sender<Arc<[u8]>>>>,
     pub full_ws_senders: Mutex<Vec<mpsc::Sender<Arc<[u8]>>>>,
     pub cached_qt_state_frame: RwLock<Arc<[u8]>>,
+    pub thermal_hub: OnceLock<Arc<crate::thermal_mcu::ThermalMcuHub>>,
 }
 
 impl PushBroadcaster {
@@ -250,9 +251,14 @@ impl PushBroadcaster {
             qt_clean_senders: Mutex::new(Vec::new()),
             full_ws_senders: Mutex::new(Vec::new()),
             cached_qt_state_frame: RwLock::new(Arc::from(initial_qt_frame.into_boxed_slice())),
+            thermal_hub: OnceLock::new(),
         }
     }
 
+    pub fn set_thermal_hub(&self, hub: Arc<crate::thermal_mcu::ThermalMcuHub>) {
+        let _ = self.thermal_hub.set(hub);
+    }
+
     pub fn subscribe(&self, is_qt_clean: bool) -> mpsc::Receiver<Arc<[u8]>> {
         let (tx, rx) = mpsc::channel();
         if is_qt_clean {
@@ -278,6 +284,16 @@ impl PushBroadcaster {
     }
 
     pub fn broadcast_task_complete(&self, sig: &JsonVal) {
+        if sig.get_str_or("verdict", "") == "fail" && sig.get_bool("batch_complete").unwrap_or(true)
+        {
+            if let Some(th) = self.thermal_hub.get() {
+                let sid = sig.get_str_or("station_id", "");
+                if !sid.is_empty() {
+                    let fault = sig.get_str_or("fault_code", "test_fail");
+                    th.notify_station_fault_purge(&sid, &fault);
+                }
+            }
+        }
         let mut ev = JsonVal::obj();
         ev.set("v", JsonVal::Num(1.0));
         ev.set("event", JsonVal::Str("task_complete".to_string()));
@@ -346,8 +362,9 @@ pub fn build_published_view(st: &StationState) -> StationPublishedView {
 }
 
 fn build_station_list_entry(st: &StationState) -> JsonVal {
-    let has_any_err =
-        st.awaiting_dimm_replacement || st.stage_errors.values().any(|v| !v.is_empty());
+    let has_any_err = st.awaiting_dimm_replacement
+        || !st.last_fault_code.is_empty()
+        || st.stage_errors.values().any(|v| !v.is_empty());
     let verdict = if has_any_err {
         "fail"
     } else if st.task_status == "completed" {
@@ -383,6 +400,14 @@ fn build_station_list_entry(st: &StationState) -> JsonVal {
         JsonVal::Str(st.boot_plan.get_str_or("preset", "manual")),
     );
     s.set("verdict", JsonVal::Str(verdict.to_string()));
+    s.set("observed_detail", JsonVal::Str(st.observed_detail.clone()));
+    s.set("fault_code", JsonVal::Str(st.last_fault_code.clone()));
+    s.set("fault_message", JsonVal::Str(st.last_fault_message.clone()));
+    s.set(
+        "hang_scene_preserved",
+        JsonVal::Bool(st.hang_scene_preserved),
+    );
+    s.set("serial_gap_detected", JsonVal::Bool(st.serial_gap_detected));
     let now = now_ms();
     patch_timing_fields(&mut s, st.run_started_unix_ms, st.run_ended_unix_ms, now);
     s.set("updated_unix_ms", JsonVal::Num(now as f64));
@@ -669,6 +694,11 @@ fn build_station_control_base(st: &StationState) -> JsonVal {
             JsonVal::Arr(st.stage_errors.get(k).cloned().unwrap_or_default()),
         );
     }
+    if let Some(sys_errs) = st.stage_errors.get("system") {
+        if !sys_errs.is_empty() {
+            stg_errs.set("system", JsonVal::Arr(sys_errs.clone()));
+        }
+    }
 
     let mut fw_obs = JsonVal::obj();
     fw_obs.set("live", JsonVal::Bool(st.diag_state == "online"));
@@ -733,6 +763,23 @@ fn build_station_control_base(st: &StationState) -> JsonVal {
             o
         })
         .collect();
+    let now_ctrl = now_ms();
+    let wd_json = st.build_watchdog_status_json(now_ctrl);
+    fw_obs.set("serial_gap_detected", JsonVal::Bool(st.serial_gap_detected));
+    fw_obs.set("serial_gap_count", JsonVal::Num(st.serial_gap_count as f64));
+    fw_obs.set(
+        "serial_gap_total_ms",
+        JsonVal::Num(st.serial_gap_total_ms as f64),
+    );
+    fw_obs.set("fault_code", JsonVal::Str(st.last_fault_code.clone()));
+    fw_obs.set(
+        "fault_message",
+        JsonVal::Str(st.last_fault_message.clone()),
+    );
+    fw_obs.set(
+        "hang_scene_preserved",
+        JsonVal::Bool(st.hang_scene_preserved),
+    );
     fw_obs.set("stage_errors", stg_errs.clone());
     fw_obs.set(
         "unsupported_commands",
@@ -782,6 +829,7 @@ fn build_station_control_base(st: &StationState) -> JsonVal {
     out.set("task_batch", st.task_batch.clone());
     out.set("task_history", JsonVal::Arr(st.task_history.clone()));
     out.set("saved_profiles", JsonVal::Arr(st.saved_profiles.clone()));
+    out.set("watchdog", wd_json);
     out.set("firmware", fw_obs);
     out.set("dimms", JsonVal::Arr(dimm_arr));
     out.set("phase_actions", phase_actions);
@@ -854,8 +902,9 @@ pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     patch_timing_fields(&mut s, st.run_started_unix_ms, st.run_ended_unix_ms, now_ms());
     s.set("boot_id", JsonVal::Str(st.boot_id.clone()));
 
-    let has_any_err =
-        st.awaiting_dimm_replacement || st.stage_errors.values().any(|v| !v.is_empty());
+    let has_any_err = st.awaiting_dimm_replacement
+        || !st.last_fault_code.is_empty()
+        || st.stage_errors.values().any(|v| !v.is_empty());
     let verdict_str = if has_any_err {
         "fail"
     } else if st.task_status == "completed" {
@@ -965,6 +1014,11 @@ pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
             JsonVal::Arr(st.stage_errors.get(k).cloned().unwrap_or_default()),
         );
     }
+    if let Some(sys_errs) = st.stage_errors.get("system") {
+        if !sys_errs.is_empty() {
+            stg_errs.set("system", JsonVal::Arr(sys_errs.clone()));
+        }
+    }
     s.set("stage_errors", stg_errs);
     s.set("stage_completions", st.stage_completions_json());
     s.set("command", strip_private_keys_recursive(&st.command));
@@ -1037,6 +1091,15 @@ pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
         .collect();
     s.set("task_history", JsonVal::Arr(compact_history));
     s.set("task_status", JsonVal::Str(st.task_status.clone()));
+    s.set("observed_detail", JsonVal::Str(st.observed_detail.clone()));
+    s.set("fault_code", JsonVal::Str(st.last_fault_code.clone()));
+    s.set("fault_message", JsonVal::Str(st.last_fault_message.clone()));
+    s.set(
+        "hang_scene_preserved",
+        JsonVal::Bool(st.hang_scene_preserved),
+    );
+    s.set("serial_gap_detected", JsonVal::Bool(st.serial_gap_detected));
+    s.set("serial_gap_count", JsonVal::Num(st.serial_gap_count as f64));
     s.set(
         "awaiting_dimm_replacement",
         JsonVal::Bool(st.awaiting_dimm_replacement),
@@ -1095,6 +1158,8 @@ pub fn apply_runtime_disconnect_policy(
 ) -> bool {
     if st.power_seq_in_progress {
         *offline_since_ms = None;
+        st.link_offline_since_unix_ms = 0;
+        st.serial_offline_since_unix_ms = 0;
         return false;
     }
     let bmc_disconnected = !st.bmc_enabled
@@ -1102,29 +1167,108 @@ pub fn apply_runtime_disconnect_policy(
         || st.bmc_state == "offline"
         || st.bmc_state == "disabled";
     let serial_disconnected = !st.console_online && st.pty_master_fd < 0;
+    let mut dirty = false;
+
+    // Track serial-only or dual-link serial gaps during an active run for `serial_gap_detected` + prompt re-probe
+    if st.is_run_active() && !st.in_internal_warm_reset {
+        if serial_disconnected {
+            if st.serial_offline_since_unix_ms == 0 {
+                st.serial_offline_since_unix_ms = now;
+            }
+        } else if st.serial_offline_since_unix_ms > 0 {
+            let prev_serial_down = st.serial_offline_since_unix_ms;
+            st.serial_offline_since_unix_ms = 0;
+            // Anchor post-reconnect silence timer to recovery timestamp so time spent offline
+            // never triggers a false `stage_hang_timeout` immediately upon cable reconnect!
+            st.observed_unix_ms = now;
+            st.hot.observed_unix_ms = now;
+            let was_gap_before = st.serial_gap_detected;
+            let prev_gap_cnt = st.serial_gap_count;
+            st.record_serial_gap(prev_serial_down, now);
+            if st.serial_gap_detected != was_gap_before || st.serial_gap_count != prev_gap_cnt {
+                dirty = true;
+            }
+            if st.boot_execution.get_str_or("state", "idle") == "running"
+                && !st.prompt_ready
+                && st.observed_phase != "mt"
+            {
+                st.pending_reconnect_prompt_probe_ms =
+                    now + st.watchdog.reconnect_prompt_probe_delay_ms.max(100);
+                st.reconnect_prompt_probed_for_session = false;
+            }
+        }
+    } else {
+        st.serial_offline_since_unix_ms = 0;
+    }
+
     if !(bmc_disconnected && serial_disconnected) {
-        let mut dirty = false;
         if *active_disconnect_logged {
             st.log_debug(
                 "CONN",
                 &format!(
-                    "RECONNECTED_ACTIVE_RUN boot_id={} bmc_state={} console_online={} started={}",
-                    st.boot_id, st.bmc_state, st.console_online, st.run_started_unix_ms
+                    "RECONNECTED_ACTIVE_RUN boot_id={} bmc_state={} server_power={} console_online={} started={}",
+                    st.boot_id, st.bmc_state, st.server_power, st.console_online, st.run_started_unix_ms
                 ),
             );
             *active_disconnect_logged = false;
+            st.link_offline_since_unix_ms = 0;
+            if st.is_run_active() && st.bmc_state == "online" && st.server_power == "off" {
+                let msg = "BMC 与 2200 串口恢复重连后核验发现主板已断电关机 (server_power=off),判定测试异常掉电中断 (reconnect_power_off)";
+                st.latch_watchdog_or_link_fault(
+                    "reconnect_power_off",
+                    &st.observed_phase.clone(),
+                    msg,
+                    true,
+                    0,
+                    now,
+                );
+                st.freeze_run_timing(now);
+                *offline_since_ms = None;
+                return true;
+            }
+            st.reconnect_power_verify_until_ms = now + 15_000;
             if st.observed_detail == "link_offline_waiting" {
                 st.observed_detail = "link_recovered".to_string();
                 dirty = true;
             }
+        } else if st.link_offline_since_unix_ms > 0 {
+            st.link_offline_since_unix_ms = 0;
+            dirty = true;
         }
         *offline_since_ms = None;
         return dirty;
     }
+
     if st.is_run_active() {
         let since = *offline_since_ms.get_or_insert(now);
-        if now.saturating_sub(since) >= 5_000 {
-            let mut dirty = false;
+        let offline_ms = now.saturating_sub(since);
+        if st.link_offline_since_unix_ms != since {
+            st.link_offline_since_unix_ms = since;
+        }
+        if st.watchdog.enabled
+            && st.watchdog.link_lost_timeout_ms > 0
+            && offline_ms >= st.watchdog.link_lost_timeout_ms
+        {
+            let msg = format!(
+                "BMC 与 2200 串口持续同时断联 {:.1}s 达到超时上限 ({:.0}s),判定整机失联/断电异常终止 (link_lost_timeout)",
+                offline_ms as f64 / 1000.0,
+                st.watchdog.link_lost_timeout_ms as f64 / 1000.0
+            );
+            st.latch_watchdog_or_link_fault(
+                "link_lost_timeout",
+                &st.observed_phase.clone(),
+                &msg,
+                true,
+                offline_ms,
+                now,
+            );
+            st.freeze_run_timing(now);
+            st.link_offline_since_unix_ms = 0;
+            *offline_since_ms = None;
+            *active_disconnect_logged = false;
+            return true;
+        }
+        if offline_ms >= 5_000 {
             if st.observed_detail != "link_offline_waiting" {
                 st.observed_detail = "link_offline_waiting".to_string();
                 dirty = true;
@@ -1144,6 +1288,7 @@ pub fn apply_runtime_disconnect_policy(
         return false;
     }
     *active_disconnect_logged = false;
+    st.link_offline_since_unix_ms = 0;
     if st.has_stale_station_state() {
         let since = *offline_since_ms.get_or_insert(now);
         if now.saturating_sub(since) >= 5_000 {
@@ -1734,6 +1879,7 @@ pub fn spawn_station_actor(
             }
 
             let mut registered_pty_fd: i32 = -1;
+            let mut registered_pty_gen: u64 = 0;
             let mut cached_pxe_state = crate::storage::load_pxe_state(&data_dir);
             let mut next_ipmi_poll_ms = now_ms() + 3000;
             let mut last_sdr_refresh_ms = now_ms();
@@ -1745,13 +1891,13 @@ pub fn spawn_station_actor(
             let mut ev_masks = [0u32; 8];
 
             loop {
-                // Keep epoll registration synced with pty_master_fd or tcp_listener_fd
+                // Keep epoll registration synced with pty_master_fd or tcp_listener_fd (track generation for OS fd reuse)
                 let desired_ep_fd = if st.pty_master_fd >= 0 {
                     st.pty_master_fd
                 } else {
                     st.tcp_listener_fd
                 };
-                if desired_ep_fd != registered_pty_fd {
+                if desired_ep_fd != registered_pty_fd || st.pty_open_gen != registered_pty_gen {
                     if registered_pty_fd >= 0 && ep_fd >= 0 {
                         unsafe {
                             lib::stl_epoll_ctl_fd(
@@ -1764,6 +1910,7 @@ pub fn spawn_station_actor(
                         }
                     }
                     registered_pty_fd = desired_ep_fd;
+                    registered_pty_gen = st.pty_open_gen;
                     if registered_pty_fd >= 0 && ep_fd >= 0 {
                         unsafe {
                             lib::stl_epoll_ctl_fd(
@@ -2039,6 +2186,32 @@ pub fn spawn_station_actor(
                                     st.server_power = pwr.clone();
                                     state_dirty = true;
                                 }
+                                if st.reconnect_power_verify_until_ms > 0 {
+                                    let now_v = now_ms();
+                                    if now_v > st.reconnect_power_verify_until_ms {
+                                        st.reconnect_power_verify_until_ms = 0;
+                                    } else if st.bmc_state == "online" {
+                                        if pwr == "off"
+                                            && !st.power_seq_in_progress
+                                            && st.is_run_active()
+                                        {
+                                            st.reconnect_power_verify_until_ms = 0;
+                                            let msg = "BMC 链路重连后 IPMI 电源核验确认主板已断电关机 (server_power=off),判定测试异常掉电中断 (reconnect_power_off)";
+                                            st.latch_watchdog_or_link_fault(
+                                                "reconnect_power_off",
+                                                &st.observed_phase.clone(),
+                                                msg,
+                                                true,
+                                                0,
+                                                now_v,
+                                            );
+                                            st.freeze_run_timing(now_v);
+                                            state_dirty = true;
+                                        } else if pwr == "on" {
+                                            st.reconnect_power_verify_until_ms = 0;
+                                        }
+                                    }
+                                }
                                 if pwr == "off"
                                     && !st.power_seq_in_progress
                                     && !st.is_run_active()
@@ -2129,6 +2302,7 @@ pub fn spawn_station_actor(
                                 }
                                 st.bmc_state = "online".to_string();
                                 st.server_power = "on".to_string();
+                                st.power_seq_completed_unix_ms = now_ms();
                                 st.cleaner.clear_halfline();
                                 st.prompt_ready = false;
                                 st.hot.prompt_ready = false;
@@ -2236,6 +2410,7 @@ pub fn spawn_station_actor(
                                 }
                             }
                             cached_pxe_state = pxe_snapshot;
+                            let _ = evaluate_stage_watchdog(&mut st, now_ms());
                             step_boot_plan(&mut st, &contract);
                             step_task_batch(
                                 &mut st,
@@ -2381,31 +2556,7 @@ pub fn spawn_station_actor(
                     }
                 }
 
-                // 4. Advance non-blocking boot plan & universal/batch task queue
-                let prev_bp_state = st.boot_execution.get_str_or("state", "idle");
-                let prev_tb_state = st.task_batch.get_str_or("state", "idle");
-                let prev_task_status = st.task_status.clone();
-                let prev_run_started = st.run_started_unix_ms;
-                let prev_run_ended = st.run_ended_unix_ms;
-                step_boot_plan(&mut st, &contract);
-                step_task_batch(
-                    &mut st,
-                    &contract,
-                    &mut cached_pxe_state,
-                    &data_dir,
-                    &pxe_tftp_dir,
-                );
-                dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor, enable_hw_bg_probes);
-                if st.boot_execution.get_str_or("state", "idle") != prev_bp_state
-                    || st.task_batch.get_str_or("state", "idle") != prev_tb_state
-                    || st.task_status != prev_task_status
-                    || st.run_started_unix_ms != prev_run_started
-                    || st.run_ended_unix_ms != prev_run_ended
-                {
-                    state_dirty = true;
-                }
-
-                // 5. Non-blocking console auto-reconnect when wired NIC carrier recovers
+                // 4a. Non-blocking console auto-reconnect when wired NIC carrier recovers
                 if enable_hw_bg_probes
                     && st.console_enabled
                     && !st.console_online
@@ -2427,10 +2578,84 @@ pub fn spawn_station_actor(
                 {
                     st.next_reconnect_probe_ms = now + 3000;
                     if open_station_pty(&mut st, &data_dir).is_ok() {
+                        st.reconnect_prompt_probed_for_session = false;
+                        state_dirty = true;
+                    }
+                }
+
+                // 4b. Real-time dual-link disconnect protection (5s grace -> link_offline_waiting -> link_lost_timeout),
+                //     post-reconnect server_power=="off" verification, and serial_gap_detected tracking
+                if enable_hw_bg_probes
+                    && apply_runtime_disconnect_policy(
+                        &mut st,
+                        &mut offline_since_ms,
+                        &mut active_disconnect_logged,
+                        now,
+                    )
+                {
+                    if st.reconnect_power_verify_until_ms > now {
+                        next_ipmi_poll_ms = now;
+                    }
+                    state_dirty = true;
+                }
+
+                // 4c. Silent prompt re-probe after `:2200` reconnect when auto-plan may have missed a prompt
+                if st.pending_reconnect_prompt_probe_ms > 0
+                    && now >= st.pending_reconnect_prompt_probe_ms
+                {
+                    st.pending_reconnect_prompt_probe_ms = 0;
+                    if st.console_online
+                        && st.pty_master_fd >= 0
+                        && !st.reconnect_prompt_probed_for_session
+                        && st.is_run_active()
+                        && st.boot_execution.get_str_or("state", "idle") == "running"
+                        && !st.prompt_ready
+                        && st.pty_rx_bytes_this_session == 0
+                        && st.tx_pacer.is_empty()
+                        && st.observed_phase != "mt"
+                    {
+                        st.reconnect_prompt_probed_for_session = true;
+                        st.log_debug(
+                            "CONN",
+                            &format!(
+                                "RECONNECT_PROMPT_PROBE sending CR phase={} boot_id={}",
+                                st.observed_phase, st.boot_id
+                            ),
+                        );
+                        let _ = write_station_paced(&mut st, b"\r");
                         state_dirty = true;
                     }
                 }
 
+                // 4d. Stage-graded silence & duration watchdog (Level 1 preserve hang scene vs Level 2 reboot_on_hang)
+                if evaluate_stage_watchdog(&mut st, now) {
+                    state_dirty = true;
+                }
+
+                // 4e. Advance non-blocking boot plan & universal/batch task queue
+                let prev_bp_state = st.boot_execution.get_str_or("state", "idle");
+                let prev_tb_state = st.task_batch.get_str_or("state", "idle");
+                let prev_task_status = st.task_status.clone();
+                let prev_run_started = st.run_started_unix_ms;
+                let prev_run_ended = st.run_ended_unix_ms;
+                step_boot_plan(&mut st, &contract);
+                step_task_batch(
+                    &mut st,
+                    &contract,
+                    &mut cached_pxe_state,
+                    &data_dir,
+                    &pxe_tftp_dir,
+                );
+                dispatch_pending_bmc_power(&mut st, &ipmi_tx_for_actor, enable_hw_bg_probes);
+                if st.boot_execution.get_str_or("state", "idle") != prev_bp_state
+                    || st.task_batch.get_str_or("state", "idle") != prev_tb_state
+                    || st.task_status != prev_task_status
+                    || st.run_started_unix_ms != prev_run_started
+                    || st.run_ended_unix_ms != prev_run_ended
+                {
+                    state_dirty = true;
+                }
+
                 if !st.boot_id.is_empty() && st.boot_id != last_seen_boot_id {
                     last_seen_boot_id = st.boot_id.clone();
                     pending_sdr_refresh = true;
@@ -2466,20 +2691,6 @@ pub fn spawn_station_actor(
                     }
                 }
 
-                // 6b. Real-time disconnect/idle reset: once BOTH console and BMC are offline
-                // (or station is unconfigured idle), clear stale channel PASS/FAIL, presence,
-                // temperatures, and run state ONLY when no active test run is in progress.
-                if enable_hw_bg_probes
-                    && apply_runtime_disconnect_policy(
-                        &mut st,
-                        &mut offline_since_ms,
-                        &mut active_disconnect_logged,
-                        now,
-                    )
-                {
-                    state_dirty = true;
-                }
-
                 // 7. Publish updated ring offsets & station snapshot + emit active `task_complete` push
                 if rx_bytes_arrived || state_dirty {
                     uart_clone.publish(&st, rx_bytes_arrived);
@@ -2563,6 +2774,18 @@ fn handle_actor_start_test(
         st.run_ended_unix_ms = 0;
     }
     st.next_reconnect_probe_ms = 0;
+    if let Some(wd) = params.get("watchdog") {
+        st.ensure_persistent_baseline();
+        st.watchdog.apply_patch(wd);
+    }
+    if let Some(roh) = params.get_bool("reboot_on_hang") {
+        st.ensure_persistent_baseline();
+        st.watchdog.reboot_on_hang = roh;
+    }
+    if let Some(mch) = params.get_i64("max_consecutive_hangs") {
+        st.ensure_persistent_baseline();
+        st.watchdog.max_consecutive_hangs = mch.clamp(1, 20) as u32;
+    }
 
     let has_task_params = params.get("memory_params").is_some()
         || params.get("uip_overrides").is_some()

+ 64 - 10
native/stl_accel/src/api.rs

@@ -209,6 +209,7 @@ impl AppHub {
 
         let thermal_hub =
             crate::thermal_mcu::ThermalMcuHub::spawn(args.data_dir.clone(), stations.clone());
+        push_hub.set_thermal_hub(Arc::clone(&thermal_hub));
 
         let hub = Arc::new(Self {
             version: args.version.clone(),
@@ -528,7 +529,7 @@ impl AppHub {
         arguments: Option<JsonVal>,
         preempt_station: bool,
     ) -> (bool, JsonVal) {
-        let mut book = self.queue_book.write().unwrap();
+        let mut book = self.queue_book.write().unwrap_or_else(|e| e.into_inner());
         if let Some(existing) = book
             .items
             .iter()
@@ -576,7 +577,7 @@ impl AppHub {
     }
 
     fn finalize_command(&self, cmd_id: &str, updater: impl FnOnce(&mut JsonVal)) -> JsonVal {
-        let mut book = self.queue_book.write().unwrap();
+        let mut book = self.queue_book.write().unwrap_or_else(|e| e.into_inner());
         if let Some(item) = book
             .items
             .iter_mut()
@@ -1473,6 +1474,34 @@ impl AppHub {
                     "awaiting_dimm_replacement",
                     JsonVal::Bool(view.awaiting_dimm_replacement),
                 );
+                out.set(
+                    "observed_detail",
+                    JsonVal::Str(view.qt_clean_station.get_str_or("observed_detail", "")),
+                );
+                out.set(
+                    "fault_code",
+                    JsonVal::Str(view.qt_clean_station.get_str_or("fault_code", "")),
+                );
+                out.set(
+                    "fault_message",
+                    JsonVal::Str(view.qt_clean_station.get_str_or("fault_message", "")),
+                );
+                out.set(
+                    "hang_scene_preserved",
+                    JsonVal::Bool(
+                        view.qt_clean_station
+                            .get_bool("hang_scene_preserved")
+                            .unwrap_or(false),
+                    ),
+                );
+                out.set(
+                    "serial_gap_detected",
+                    JsonVal::Bool(
+                        view.qt_clean_station
+                            .get_bool("serial_gap_detected")
+                            .unwrap_or(false),
+                    ),
+                );
                 out.set("stage_completions", view.stage_completions);
                 if let Some(errs) = view.qt_clean_station.get("stage_errors") {
                     out.set("stage_errors", errs.clone());
@@ -1569,7 +1598,11 @@ impl AppHub {
             "GetQueueItem" | "GetCommand" => {
                 let cid = params.get_str_or("command_id", "");
                 if let Some(found) = self.find_queued_command(&cid) {
-                    Ok(found)
+                    if is_qt_clean {
+                        Ok(strip_private_keys_recursive(&found))
+                    } else {
+                        Ok(found)
+                    }
                 } else {
                     Err((
                         "NOT_FOUND".to_string(),
@@ -1603,27 +1636,39 @@ impl AppHub {
                 Ok(out)
             }
             "ReadEventQueue" => {
-                let after = params.get_i64("after_sequence").unwrap_or(0) as u64;
+                let after = params.get_i64("after_sequence").unwrap_or(0).max(0) as u64;
                 let sid_filter = params.get_str_or("station_id", "");
                 let limit = params.get_i64("limit").unwrap_or(100).clamp(1, 500) as usize;
                 let Ok(book) = self.audit_book.lock() else {
                     return Err(("INTERNAL".to_string(), "事件队列锁异常".to_string()));
                 };
-                let evs: Vec<JsonVal> = book
+                let mut matched: Vec<JsonVal> = book
                     .event_items
                     .iter()
-                    .filter(|x| x.get_i64("sequence").unwrap_or(0) as u64 > after)
+                    .filter(|x| x.get_i64("sequence").unwrap_or(0).max(0) as u64 > after)
                     .filter(|x| {
                         sid_filter.is_empty() || x.get_str_or("station_id", "") == sid_filter
                     })
-                    .take(limit)
+                    .take(limit + 1)
                     .cloned()
                     .collect();
+                let has_more = matched.len() > limit;
+                if has_more {
+                    matched.truncate(limit);
+                }
+                let next_after = if has_more {
+                    matched
+                        .last()
+                        .and_then(|x| x.get_i64("sequence"))
+                        .unwrap_or(after as i64) as u64
+                } else {
+                    book.event_seq
+                };
                 let mut out = JsonVal::obj();
-                out.set("events", JsonVal::Arr(evs));
-                out.set("next_after_sequence", JsonVal::Num(book.event_seq as f64));
+                out.set("events", JsonVal::Arr(matched));
+                out.set("next_after_sequence", JsonVal::Num(next_after as f64));
                 out.set("latest_sequence", JsonVal::Num(book.event_seq as f64));
-                out.set("has_more", JsonVal::Bool(false));
+                out.set("has_more", JsonVal::Bool(has_more));
                 Ok(out)
             }
             "GetN540Config" => {
@@ -2600,6 +2645,15 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
     }
 
     let file_path = hub.web_dir.join(rel_clean);
+    let canonical_ok = match (fs::canonicalize(&hub.web_dir), fs::canonicalize(&file_path)) {
+        (Ok(root_canon), Ok(file_canon)) => file_canon.starts_with(&root_canon),
+        _ => false,
+    };
+    if !canonical_ok {
+        let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nNot Found";
+        let _ = stream.write_all(resp.as_bytes());
+        return;
+    }
     let Ok(body) = fs::read(&file_path) else {
         let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\nConnection: close\r\n\r\nNot Found";
         let _ = stream.write_all(resp.as_bytes());

+ 37 - 0
native/stl_accel/src/commands.rs

@@ -229,6 +229,8 @@ pub fn handle_station_command_nonblocking(
                     };
                     if let Some(en) = want_rmt {
                         st.boot_plan.set("run_rmt", JsonVal::Bool(en));
+                        // Last-write-wins: clear stale standalone "rmt" intent so it cannot overwrite this newer uip/uip1 intent
+                        st.stage_intents.remove("rmt");
                     }
                     if args.get("memory_params").is_some()
                         || want_rmt.is_some()
@@ -1203,6 +1205,9 @@ pub fn handle_station_command_nonblocking(
             };
             let norm = normalize_boot_plan(raw_plan);
             st.boot_plan = norm.clone();
+            if let Some(wd) = args.get("watchdog").or_else(|| raw_plan.get("watchdog")) {
+                st.watchdog.apply_patch(wd);
+            }
             st.clear_persistent_baseline();
             save_station_settings(data_dir, st);
             let audit = AuditRecordDraft {
@@ -1217,9 +1222,39 @@ pub fn handle_station_command_nonblocking(
             };
             let mut res = JsonVal::obj();
             res.set("boot_plan", norm);
+            res.set("watchdog", st.watchdog.to_json());
             res.set("hardware_written", JsonVal::Bool(false));
             StationCmdExec::Immediate(Ok(res), Some(audit))
         }
+        "ConfigureWatchdog" => {
+            let patch = args.get("watchdog").unwrap_or(args);
+            st.watchdog.apply_patch(patch);
+            if args.get_bool("reset_consecutive_hangs") == Some(true) {
+                st.consecutive_hang_count = 0;
+            }
+            st.clear_persistent_baseline();
+            save_station_settings(data_dir, st);
+            let wd_json = st.watchdog.to_json();
+            let audit = AuditRecordDraft {
+                category: "watchdog".to_string(),
+                action: "configure_watchdog".to_string(),
+                summary: format!(
+                    "更新防卡死与断联保护参数:enabled={} · link_lost={}s · dense={}s · amt={}s · mt={}s · reboot_on_hang={} (max={})",
+                    st.watchdog.enabled,
+                    st.watchdog.link_lost_timeout_ms / 1000,
+                    st.watchdog.dense_stage_silence_timeout_ms / 1000,
+                    st.watchdog.amt_silence_timeout_ms / 1000,
+                    st.watchdog.mt_silence_timeout_ms / 1000,
+                    st.watchdog.reboot_on_hang,
+                    st.watchdog.max_consecutive_hangs,
+                ),
+                details: wd_json.clone(),
+            };
+            let mut res = JsonVal::obj();
+            res.set("station_id", JsonVal::Str(sid));
+            res.set("watchdog", wd_json);
+            StationCmdExec::Immediate(Ok(res), Some(audit))
+        }
         "ControlBootPlan" => {
             let action = args.get_str_or("action", "");
             match control_boot_plan(st, &action, data_dir) {
@@ -1767,8 +1802,10 @@ pub fn handle_station_command_nonblocking(
                 st.single_run_active = false;
                 st.plan_paused = false;
                 st.async_script.clear();
+                st.stage_intents.clear();
                 st.task_status = "interrupted".to_string();
                 st.freeze_run_timing(now);
+                st.restore_persistent_baseline("station_power_host_off");
                 st.boot_execution.set("state", JsonVal::Str("stopped".to_string()));
                 st.boot_execution.set(
                     "waiting_reason",

+ 19 - 5
native/stl_accel/src/devices.rs

@@ -64,6 +64,7 @@ pub fn close_station_listener(st: &mut StationState) {
         unsafe { lib::c_pty_close(st.tcp_listener_fd, 0) };
         st.tcp_listener_fd = -1;
         st.tcp_listener_port = 0;
+        st.pty_open_gen = st.pty_open_gen.wrapping_add(1);
     }
 }
 
@@ -130,6 +131,7 @@ pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), St
             }
             st.tcp_listener_fd = lfd;
             st.tcp_listener_port = port;
+            st.pty_open_gen = st.pty_open_gen.wrapping_add(1);
         }
         let accepted = unsafe { lib::c_pty_accept_tcp_nonblock(st.tcp_listener_fd) };
         if accepted >= 0 {
@@ -255,6 +257,7 @@ pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), St
     let now = now_ms();
     st.pty_master_fd = mfd;
     st.pty_child_pid = cpid;
+    st.pty_open_gen = st.pty_open_gen.wrapping_add(1);
     st.pty_opened_ms = now;
     st.pty_rx_bytes_this_session = 0;
     st.diag_state = "online".to_string();
@@ -287,6 +290,7 @@ pub fn close_station_pty(st: &mut StationState) {
         unsafe { lib::c_pty_close(st.pty_master_fd, st.pty_child_pid) };
         st.pty_master_fd = -1;
         st.pty_child_pid = -1;
+        st.pty_open_gen = st.pty_open_gen.wrapping_add(1);
     }
     st.diag_state = if st.tcp_listener_fd >= 0 {
         "listening".to_string()
@@ -311,6 +315,7 @@ pub fn poll_station_listener(st: &mut StationState) -> bool {
     let now = now_ms();
     st.pty_master_fd = accepted;
     st.pty_child_pid = 0;
+    st.pty_open_gen = st.pty_open_gen.wrapping_add(1);
     st.pty_opened_ms = now;
     st.pty_rx_bytes_this_session = 0;
     st.diag_state = "online".to_string();
@@ -496,14 +501,14 @@ impl PersistentIpmiSession {
         }
     }
 
-    pub fn ensure_connected(&mut self, host: &str, user: &str, pass: &str) -> bool {
+    pub fn ensure_connected_rc(&mut self, host: &str, user: &str, pass: &str) -> i32 {
         if self.handle > 0
             && self.host == host
             && self.user == user
             && self.pass == pass
             && unsafe { lib::c_ipmi_is_alive(self.handle) } != 0
         {
-            return true;
+            return self.handle;
         }
         self.close();
         let host_c = format!("{}\0", host.trim());
@@ -523,11 +528,15 @@ impl PersistentIpmiSession {
             self.user = user.to_string();
             self.pass = pass.to_string();
             self.handle = h;
-            true
+            h
         } else {
-            false
+            h
         }
     }
+
+    pub fn ensure_connected(&mut self, host: &str, user: &str, pass: &str) -> bool {
+        self.ensure_connected_rc(host, user, pass) > 0
+    }
 }
 
 impl Drop for PersistentIpmiSession {
@@ -730,7 +739,12 @@ pub fn run_ipmi_with_session(
 
     let mut last_err = String::new();
     for cand_pass in [primary_pass, alt_pass] {
-        if !s.ensure_connected(&resolved_host, user, cand_pass) {
+        let open_rc = s.ensure_connected_rc(&resolved_host, user, cand_pass);
+        if open_rc <= 0 {
+            if open_rc == -2 {
+                last_err = format!("libfreeipmi RMCP+ 会话超时 ({})", resolved_host);
+                break;
+            }
             last_err = format!("libfreeipmi 无法建立 RMCP+ 会话 ({})", resolved_host);
             continue;
         }

+ 41 - 13
native/stl_accel/src/json.rs

@@ -176,10 +176,12 @@ pub fn escape_json_into(s: &str, out: &mut String) {
     out.push('"');
 }
 
+const MAX_JSON_DEPTH: usize = 128;
+
 pub fn parse_json(input: &str) -> Result<JsonVal, String> {
     let bytes = input.as_bytes();
     let mut pos = 0;
-    let val = parse_value(bytes, &mut pos)?;
+    let val = parse_value(bytes, &mut pos, 0)?;
     skip_ws(bytes, &mut pos);
     Ok(val)
 }
@@ -190,15 +192,18 @@ fn skip_ws(b: &[u8], pos: &mut usize) {
     }
 }
 
-fn parse_value(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
+fn parse_value(b: &[u8], pos: &mut usize, depth: usize) -> Result<JsonVal, String> {
+    if depth > MAX_JSON_DEPTH {
+        return Err("JSON nesting depth exceeded".to_string());
+    }
     skip_ws(b, pos);
     if *pos >= b.len() {
         return Err("Unexpected EOF".to_string());
     }
     match b[*pos] {
         b'"' => parse_string(b, pos).map(JsonVal::Str),
-        b'{' => parse_object(b, pos),
-        b'[' => parse_array(b, pos),
+        b'{' => parse_object(b, pos, depth + 1),
+        b'[' => parse_array(b, pos, depth + 1),
         b't' => {
             if b.get(*pos..*pos + 4) == Some(b"true") {
                 *pos += 4;
@@ -235,6 +240,17 @@ fn parse_string(b: &[u8], pos: &mut usize) -> Result<String, String> {
     *pos += 1;
     let mut out = String::new();
     while *pos < b.len() {
+        let seg_start = *pos;
+        while *pos < b.len() && b[*pos] != b'"' && b[*pos] != b'\\' {
+            *pos += 1;
+        }
+        if *pos > seg_start {
+            let s = std::str::from_utf8(&b[seg_start..*pos]).map_err(|_| "Invalid UTF-8")?;
+            out.push_str(s);
+        }
+        if *pos >= b.len() {
+            break;
+        }
         let c = b[*pos];
         if c == b'"' {
             *pos += 1;
@@ -262,6 +278,23 @@ fn parse_string(b: &[u8], pos: &mut usize) -> Result<String, String> {
                     let hex_s = std::str::from_utf8(&b[*pos..*pos + 4]).map_err(|_| "Bad hex")?;
                     let code = u32::from_str_radix(hex_s, 16).map_err(|_| "Bad hex")?;
                     *pos += 4;
+                    if (0xD800..=0xDBFF).contains(&code)
+                        && b.get(*pos..*pos + 2) == Some(b"\\u")
+                        && *pos + 6 <= b.len()
+                    {
+                        if let Ok(low_hex) = std::str::from_utf8(&b[*pos + 2..*pos + 6]) {
+                            if let Ok(low) = u32::from_str_radix(low_hex, 16) {
+                                if (0xDC00..=0xDFFF).contains(&low) {
+                                    *pos += 6;
+                                    let combined = 0x10000 + (((code - 0xD800) << 10) | (low - 0xDC00));
+                                    if let Some(ch) = char::from_u32(combined) {
+                                        out.push(ch);
+                                    }
+                                    continue;
+                                }
+                            }
+                        }
+                    }
                     if let Some(ch) = char::from_u32(code) {
                         out.push(ch);
                     }
@@ -271,11 +304,6 @@ fn parse_string(b: &[u8], pos: &mut usize) -> Result<String, String> {
                     *pos += 1;
                 }
             }
-        } else {
-            let s = std::str::from_utf8(&b[*pos..]).map_err(|_| "Invalid UTF-8")?;
-            let ch = s.chars().next().ok_or("EOF")?;
-            out.push(ch);
-            *pos += ch.len_utf8();
         }
     }
     Err("Unterminated string".to_string())
@@ -294,7 +322,7 @@ fn parse_number(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
     Ok(JsonVal::Num(val))
 }
 
-fn parse_array(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
+fn parse_array(b: &[u8], pos: &mut usize, depth: usize) -> Result<JsonVal, String> {
     *pos += 1; // skip '['
     skip_ws(b, pos);
     let mut arr = Vec::new();
@@ -303,7 +331,7 @@ fn parse_array(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
         return Ok(JsonVal::Arr(arr));
     }
     loop {
-        let v = parse_value(b, pos)?;
+        let v = parse_value(b, pos, depth)?;
         arr.push(v);
         skip_ws(b, pos);
         match b.get(*pos) {
@@ -314,7 +342,7 @@ fn parse_array(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
     }
 }
 
-fn parse_object(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
+fn parse_object(b: &[u8], pos: &mut usize, depth: usize) -> Result<JsonVal, String> {
     *pos += 1; // skip '{'
     skip_ws(b, pos);
     let mut map = BTreeMap::new();
@@ -330,7 +358,7 @@ fn parse_object(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
             return Err("Expected ':' in object".to_string());
         }
         *pos += 1;
-        let val = parse_value(b, pos)?;
+        let val = parse_value(b, pos, depth)?;
         map.insert(key, val);
         skip_ws(b, pos);
         match b.get(*pos) {

+ 513 - 2
native/stl_accel/src/main.rs

@@ -757,15 +757,21 @@ mod tests {
         assert_eq!(u16::from_be_bytes([buf[0], buf[1]]), 4); // ACK 1
         assert_eq!(u16::from_be_bytes([buf[2], buf[3]]), 1);
 
-        for _ in 0..50 {
+        for _ in 0..80 {
             let has_rpt = hub
                 .build_station_control("S1")
                 .ok()
                 .and_then(|c| c.get("pxe_control").and_then(|p| p.get_arr("recent_reports")).map(|a| !a.is_empty()))
                 .unwrap_or(false);
-            if has_rpt {
+            let s1_latched = hub
+                .read_station_view("S1")
+                .ok()
+                .map(|v| v.awaiting_dimm_replacement)
+                .unwrap_or(false);
+            if has_rpt && s1_latched {
                 break;
             }
+            hub.force_tick("S1");
             std::thread::sleep(Duration::from_millis(20));
         }
         hub.force_tick("S1");
@@ -4529,4 +4535,509 @@ FS0:\\EFI\\> \r\n",
 
         let _ = std::fs::remove_dir_all(&tmp_dir);
     }
+
+    #[test]
+    fn test_v30_dual_disconnect_timeout_reconnect_verify_and_decoupled_watchdog() {
+        use crate::actors::apply_runtime_disconnect_policy;
+        use crate::firmware::FirmwareContract;
+        use crate::results::{now_ms, StationState};
+        use crate::workflow::{
+            control_boot_plan, evaluate_stage_watchdog, step_boot_plan, step_task_batch,
+            submit_task_batch,
+        };
+
+        lib::init_hardware();
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl-v30-watchdog-{}-{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+        std::fs::create_dir_all(tmp_dir.join("station-controls")).unwrap();
+        std::fs::create_dir_all(tmp_dir.join("pxe-tftp")).unwrap();
+        std::fs::create_dir_all(tmp_dir.join("debug")).unwrap();
+        let contract = FirmwareContract::load(Path::new("contracts/firmware-vd012.json"));
+
+        // 1. Dual-disconnect ceiling (`link_lost_timeout`) + timer freeze + serial_gap_detected + reconnect_power_off
+        let mut st = StationState::new("S1", "Station 1", "192.168.2.166", "");
+        st.debug_log_path = Some(tmp_dir.join("debug").join("S1.log"));
+        st.watchdog.link_lost_timeout_ms = 20_000;
+        let _ = control_boot_plan(&mut st, "restart", &tmp_dir).unwrap();
+        st.power_seq_in_progress = false;
+        st.bmc_state = "online".to_string();
+        st.server_power = "on".to_string();
+        st.console_online = true;
+        let t0 = now_ms();
+        st.run_started_unix_ms = t0;
+        st.hot.last_rx_unix_ms = t0;
+
+        // 1a. Serial-only drop (BMC stays online) >= 2s sets `serial_gap_detected` + schedules prompt re-probe without `link_offline_waiting`
+        let mut offline_since = None;
+        let mut active_logged = false;
+        st.console_online = false;
+        st.pty_master_fd = -1;
+        assert!(!apply_runtime_disconnect_policy(
+            &mut st,
+            &mut offline_since,
+            &mut active_logged,
+            t0 + 1_000,
+        ));
+        assert!(!apply_runtime_disconnect_policy(
+            &mut st,
+            &mut offline_since,
+            &mut active_logged,
+            t0 + 8_000,
+        ));
+        assert_ne!(st.observed_detail, "link_offline_waiting");
+        assert_eq!(st.task_status, "running");
+        st.console_online = true;
+        assert!(apply_runtime_disconnect_policy(
+            &mut st,
+            &mut offline_since,
+            &mut active_logged,
+            t0 + 8_500,
+        ));
+        assert!(st.serial_gap_detected);
+        assert_eq!(st.serial_gap_count, 1);
+        assert!(st.serial_gap_total_ms >= 7_000);
+        assert!(st.pending_reconnect_prompt_probe_ms > t0 + 8_500);
+
+        // 1b. Dual-disconnect 6s -> `link_offline_waiting` (watchdog paused while link offline!) -> recover with `server_power=="off"` -> `reconnect_power_off`
+        st.bmc_state = "offline".to_string();
+        st.console_online = false;
+        st.pty_master_fd = -1;
+        assert!(!apply_runtime_disconnect_policy(
+            &mut st,
+            &mut offline_since,
+            &mut active_logged,
+            t0 + 10_000,
+        ));
+        assert!(apply_runtime_disconnect_policy(
+            &mut st,
+            &mut offline_since,
+            &mut active_logged,
+            t0 + 16_000,
+        ));
+        assert_eq!(st.observed_detail, "link_offline_waiting");
+        // Verify stage-silence watchdog does NOT misfire while `link_offline_waiting`
+        st.watchdog.dense_stage_silence_timeout_ms = 5_000;
+        assert!(!evaluate_stage_watchdog(&mut st, t0 + 50_000));
+
+        // Now BMC recovers at t0 + 18_000, but motherboard lost AC power (`server_power == "off"`)!
+        st.bmc_state = "online".to_string();
+        st.server_power = "off".to_string();
+        assert!(apply_runtime_disconnect_policy(
+            &mut st,
+            &mut offline_since,
+            &mut active_logged,
+            t0 + 18_000,
+        ));
+        assert_eq!(st.task_status, "failed");
+        assert_eq!(st.last_fault_code, "reconnect_power_off");
+        assert!(st.run_ended_unix_ms > 0);
+
+        // 1c. Dual-disconnect exceeding `link_lost_timeout_ms` -> `link_lost_timeout` + archival + complete signal
+        let mut st_lt = StationState::new("S2", "Station 2", "192.168.2.165", "");
+        st_lt.watchdog.link_lost_timeout_ms = 12_000;
+        let _ = control_boot_plan(&mut st_lt, "restart", &tmp_dir).unwrap();
+        st_lt.power_seq_in_progress = false;
+        st_lt.bmc_state = "offline".to_string();
+        st_lt.console_online = false;
+        st_lt.pty_master_fd = -1;
+        let mut off2 = None;
+        let mut log2 = false;
+        assert!(!apply_runtime_disconnect_policy(&mut st_lt, &mut off2, &mut log2, t0));
+        assert!(apply_runtime_disconnect_policy(&mut st_lt, &mut off2, &mut log2, t0 + 6_000));
+        assert_eq!(st_lt.observed_detail, "link_offline_waiting");
+        assert!(apply_runtime_disconnect_policy(&mut st_lt, &mut off2, &mut log2, t0 + 13_000));
+        assert_eq!(st_lt.last_fault_code, "link_lost_timeout");
+        assert_eq!(st_lt.task_status, "failed");
+        let mut pxe_dummy = JsonVal::obj();
+        step_task_batch(&mut st_lt, &contract, &mut pxe_dummy, &tmp_dir, &tmp_dir);
+        let sig_lt = st_lt.pending_complete_signal.take().expect("link_lost_timeout must emit task_complete");
+        assert_eq!(sig_lt.get_str_or("verdict", ""), "fail");
+        assert_eq!(sig_lt.get_str_or("fault_code", ""), "link_lost_timeout");
+
+        // 2. Stage-graded silence watchdog: manual prompt exempt, AMT wider threshold than RMT, MT duration cap
+        let mut st_wd = StationState::new("S3", "Station 3", "192.168.2.167", "");
+        st_wd.watchdog.dense_stage_silence_timeout_ms = 15_000;
+        st_wd.watchdog.amt_silence_timeout_ms = 60_000;
+        st_wd.watchdog.mt_silence_timeout_ms = 60_000;
+        st_wd.watchdog.mt_max_duration_ms = 120_000;
+        let _ = control_boot_plan(&mut st_wd, "restart", &tmp_dir).unwrap();
+        st_wd.power_seq_in_progress = false;
+        st_wd.bmc_state = "online".to_string();
+        st_wd.server_power = "on".to_string();
+        st_wd.console_online = true;
+        st_wd.observe_serial_chunk(
+            b"[HS_BIOS]Version:GNRSRF_AP(SDP)_RDIMM_108_VD012_20260612\r\n[0][Hovsee]Current stage is 1\r\n[0][Hovsee]Please input your command:",
+        );
+        let anchor_uip = st_wd.last_activity_anchor_ms();
+        // Default manual mode at ICT prompt -> exempt even after 500s!
+        assert!(st_wd.prompt_ready);
+        assert!(!evaluate_stage_watchdog(&mut st_wd, anchor_uip + 500_000));
+
+        // Switch to auto mode in AMT -> survives 30s (> dense 15s), triggers at 61s (>= amt 60s)
+        st_wd.boot_plan.set("preset", JsonVal::Str("auto".to_string()));
+        st_wd.prompt_ready = false;
+        st_wd.observed_phase = "amt".to_string();
+        st_wd.observed_unix_ms = anchor_uip + 1_000;
+        st_wd.hot.last_rx_unix_ms = anchor_uip + 1_000;
+        assert!(!evaluate_stage_watchdog(&mut st_wd, anchor_uip + 31_000));
+        assert!(evaluate_stage_watchdog(&mut st_wd, anchor_uip + 62_000));
+        assert_eq!(st_wd.last_fault_code, "stage_hang_timeout");
+        assert!(st_wd.hang_scene_preserved);
+
+        // MT max duration cap catches ANSI spinner loop even when `last_rx_unix_ms` keeps updating
+        let _ = control_boot_plan(&mut st_wd, "restart", &tmp_dir).unwrap();
+        st_wd.power_seq_in_progress = false;
+        st_wd.observed_phase = "mt".to_string();
+        st_wd.mt_started_unix_ms = t0;
+        st_wd.hot.last_rx_unix_ms = t0 + 121_000; // fresh RX 0ms ago, but total MT duration > 120s!
+        assert!(evaluate_stage_watchdog(&mut st_wd, t0 + 121_500));
+        assert_eq!(st_wd.last_fault_code, "mt_duration_timeout");
+
+        // 3. Level-1 vs Level-2 Decoupling in `SubmitTaskBatch` + `ThermalMcuHub` auto-purge (`0x08 00`)
+        let args = ServerArgs {
+            config_path: Path::new("config/backend.example.json").to_path_buf(),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: Path::new("web").to_path_buf(),
+            contracts_path: Path::new("contracts/firmware-vd012.json").to_path_buf(),
+            web_password: None,
+            version: "0.8.1.30".to_string(),
+            commit: "unit-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+        let rx_clean = hub.push_hub.subscribe(true);
+
+        // Connect S1 thermal hood in mock mode and start 70C heating
+        hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"station_id":"S1","action":"connect","mode":"mock"}"#).unwrap(),
+            false,
+        )
+        .unwrap();
+        hub.dispatch_rpc(
+            "ThermalAction",
+            &parse_json(r#"{"station_id":"S1","action":"set_temp","target_c":70}"#).unwrap(),
+            false,
+        )
+        .unwrap();
+
+        // 3a. Level-1 default (`stop_on_fail: false`, `reboot_on_hang: false`): hang in RMT MUST halt batch, preserve scene, and auto-purge hood!
+        hub.dispatch_rpc(
+            "SubmitTaskBatch",
+            &parse_json(r#"{
+                "station_id":"S1",
+                "stop_on_fail":false,
+                "reboot_on_hang":false,
+                "watchdog":{"dense_stage_silence_timeout_ms":1200},
+                "profiles":[{"name":"RMT-Hang-Preserve","repeat":3,"run_rmt":true,"run_amt":false,"run_mt":false}]
+            }"#).unwrap(),
+            true,
+        ).unwrap();
+        hub.test_inject_serial(
+            "S1",
+            b"[HS_BIOS]Version:GNRSRF_AP(SDP)_RDIMM_108_VD012_20260612\r\n[0][Hovsee]Current stage is 1\r\n[0][Hovsee]Exit ICT ddr test and go on training\r\n[HS_BIOS][RMT] Start Rank Margin Tool...\r\n",
+            Some("running"),
+            false,
+        );
+        std::thread::sleep(std::time::Duration::from_millis(1350));
+        hub.force_tick("S1");
+        std::thread::sleep(std::time::Duration::from_millis(120));
+
+        let v_s1 = hub.read_station_view("S1").unwrap();
+        assert_eq!(v_s1.task_status, "failed");
+        assert_eq!(v_s1.task_batch.get_str_or("state", ""), "failed");
+        assert_eq!(v_s1.task_batch.get_str_or("halt_reason", ""), "hang_scene_preserved");
+        assert_eq!(v_s1.qt_clean_station.get_str_or("fault_code", ""), "stage_hang_timeout");
+        assert_eq!(v_s1.qt_clean_station.get_bool("hang_scene_preserved"), Some(true));
+        // Only 1 run was executed; it did NOT auto-reboot into R2!
+        assert_eq!(v_s1.task_batch.get_arr("runs").unwrap().len(), 1);
+
+        // Verify `task_complete` event was broadcast to Qt-Clean AND ThermalMcuHub automatically sent `0x08 00` purge!
+        let mut saw_hang_complete = false;
+        while let Ok(frame) = rx_clean.try_recv() {
+            if let Ok(js) = parse_json(&String::from_utf8_lossy(&frame)) {
+                if js.get_str_or("event", "") == "task_complete" {
+                    let res = js.get("result").unwrap();
+                    if res.get_str_or("station_id", "") == "S1"
+                        && res.get_str_or("fault_code", "") == "stage_hang_timeout"
+                    {
+                        saw_hang_complete = true;
+                        assert_eq!(res.get_bool("batch_complete"), Some(true));
+                        assert_eq!(res.get_bool("hang_scene_preserved"), Some(true));
+                    }
+                }
+            }
+        }
+        assert!(saw_hang_complete, "Watchdog hang must push task_complete to Qt/Web");
+
+        let th_snap = hub
+            .dispatch_rpc(
+                "GetThermalConsole",
+                &parse_json(r#"{"station_id":"S1","include_frames":true}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        let th_events = th_snap.get_arr("events").unwrap();
+        assert!(
+            th_events
+                .iter()
+                .any(|e| e.get_str_or("kind", "") == "station_fault_auto_purge"),
+            "ThermalMcuHub must auto-purge (0x08 00) when station hangs!"
+        );
+
+        // 3b. Level-2 opt-in (`stop_on_fail: false`, `reboot_on_hang: true`, `max_consecutive_hangs: 2`):
+        //     Hang #1 auto-restarts into R2; Hang #2 trips `consecutive_hang_limit_exceeded` circuit breaker and stops!
+        let mut st_l2 = StationState::new("S4", "Station 4", "192.168.2.168", "");
+        let mut pxe_l2 = JsonVal::obj();
+        let batch_args = parse_json(
+            r#"{
+                "stop_on_fail": false,
+                "reboot_on_hang": true,
+                "max_consecutive_hangs": 2,
+                "watchdog": {"dense_stage_silence_timeout_ms": 5000},
+                "profiles": [{"name": "Unattended-Soak", "repeat": 4, "run_rmt": true, "run_amt": false, "run_mt": false}]
+            }"#,
+        )
+        .unwrap();
+        submit_task_batch(&mut st_l2, &batch_args, &contract, &mut pxe_l2, &tmp_dir, &tmp_dir).unwrap();
+        let _ = st_l2.pending_bmc_power_action.take();
+        st_l2.power_seq_in_progress = false;
+        let t_r1 = now_ms();
+        st_l2.observed_phase = "training".to_string();
+        st_l2.observed_unix_ms = t_r1;
+        st_l2.hot.last_rx_unix_ms = t_r1;
+
+        // Hang #1 at t_r1 + 6s -> should auto-advance to R2 and queue `smart_restart`!
+        assert!(evaluate_stage_watchdog(&mut st_l2, t_r1 + 6_000));
+        assert_eq!(st_l2.consecutive_hang_count, 1);
+        assert!(!st_l2.hang_scene_preserved);
+        step_boot_plan(&mut st_l2, &contract);
+        step_task_batch(&mut st_l2, &contract, &mut pxe_l2, &tmp_dir, &tmp_dir);
+        assert_eq!(st_l2.task_batch.get_str_or("state", ""), "running");
+        assert_eq!(st_l2.task_batch.get_i64("current_repeat"), Some(2));
+        assert_eq!(
+            st_l2.pending_bmc_power_action.take().as_deref(),
+            Some("smart_restart"),
+            "1st hang under reboot_on_hang=true must queue BMC smart_restart"
+        );
+
+        // Hang #2 in R2 -> reaches `max_consecutive_hangs=2` -> circuit breaker halts batch & preserves scene without reboot!
+        st_l2.power_seq_in_progress = false;
+        let t_r2 = now_ms() + 10_000;
+        st_l2.observed_phase = "training".to_string();
+        st_l2.observed_unix_ms = t_r2;
+        st_l2.hot.last_rx_unix_ms = t_r2;
+        assert!(evaluate_stage_watchdog(&mut st_l2, t_r2 + 6_000));
+        assert_eq!(st_l2.consecutive_hang_count, 2);
+        assert!(st_l2.hang_scene_preserved);
+        step_boot_plan(&mut st_l2, &contract);
+        step_task_batch(&mut st_l2, &contract, &mut pxe_l2, &tmp_dir, &tmp_dir);
+        assert_eq!(st_l2.task_batch.get_str_or("state", ""), "failed");
+        assert_eq!(
+            st_l2.task_batch.get_str_or("halt_reason", ""),
+            "consecutive_hang_limit_exceeded"
+        );
+        assert!(
+            st_l2.pending_bmc_power_action.is_none(),
+            "Circuit breaker must prevent further BMC power cycling on dead board"
+        );
+
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
+
+    #[test]
+    fn test_phase0_security_stability_and_thermal_purge_fixes() {
+        use crate::api::AppHub;
+        use crate::commands::handle_station_command_nonblocking;
+        use crate::config::ServerArgs;
+        use crate::firmware::FirmwareContract;
+        use crate::json::parse_json;
+        use crate::results::{now_ms, StationState};
+
+        // 1. JSON recursion depth guard + O(N) large UTF-8 string + surrogate pair decode
+        let deep = format!("{}{}", "[".repeat(200), "]".repeat(200));
+        assert!(parse_json(&deep).is_err(), "Deeply nested JSON must fail cleanly");
+        let big_utf8 = format!("{{\"msg\":\"{}\"}}", "高温测试日志".repeat(4000));
+        let parsed_big = parse_json(&big_utf8).expect("Large UTF-8 JSON should parse fast");
+        assert_eq!(parsed_big.get_str_or("msg", "").chars().count(), 24000);
+        let surr = parse_json(r#"{"e":"\uD83D\uDE00"}"#).unwrap();
+        assert_eq!(surr.get_str_or("e", ""), "😀");
+
+        // 2. AppHub: GetCommand strips password on qt-clean, ReadEventQueue paginates accurately,
+        //    and AutoPurgeOnStationFault ignores untouched idle hood yet purges PID (0x04) hood
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl-phase0-{}-{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+        std::fs::create_dir_all(tmp_dir.join("station-controls")).unwrap();
+        std::fs::create_dir_all(tmp_dir.join("pxe-tftp")).unwrap();
+        std::fs::create_dir_all(tmp_dir.join("debug")).unwrap();
+        let args = ServerArgs {
+            config_path: tmp_dir.join("missing.json"),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: std::path::PathBuf::from("web"),
+            contracts_path: std::path::PathBuf::from("contracts/firmware-vd012.json"),
+            web_password: None,
+            version: "0.8.1.30".to_string(),
+            commit: "phase0-test".to_string(),
+        };
+        let hub = AppHub::init_with_options(&args, false);
+
+        // 2a. ConfigureConnections stores password in queue_book; qt-clean GetCommand must strip it!
+        let _ = hub.dispatch_rpc(
+            "EnqueueCommand",
+            &parse_json(
+                r#"{"command_id":"cfg-secret-1","station_id":"S1","method":"ConfigureConnections","arguments":{"bmc":{"enabled":false,"host":"127.0.0.1","username":"ADMIN","password":"SuperSecretPassword123!"}}}"#,
+            )
+            .unwrap(),
+            false,
+        );
+        let qt_cmd = hub
+            .dispatch_rpc(
+                "GetCommand",
+                &parse_json(r#"{"command_id":"cfg-secret-1"}"#).unwrap(),
+                true,
+            )
+            .expect("GetCommand should succeed");
+        let qt_cmd_json = qt_cmd.to_json();
+        assert!(
+            !qt_cmd_json.contains("SuperSecretPassword123!"),
+            "qt-clean GetCommand must never leak plaintext password: {}",
+            qt_cmd_json
+        );
+
+        // 2b. ReadEventQueue pagination must set has_more and advance next_after_sequence accurately
+        let _ = hub.dispatch_rpc(
+            "EnqueueCommand",
+            &parse_json(r#"{"command_id":"cfg-ev-2","station_id":"S1","method":"SaveBootPlan","arguments":{"plan":{"preset":"auto"}}}"#).unwrap(),
+            false,
+        );
+        let _ = hub.dispatch_rpc(
+            "EnqueueCommand",
+            &parse_json(r#"{"command_id":"cfg-ev-3","station_id":"S1","method":"SaveBootPlan","arguments":{"plan":{"preset":"manual"}}}"#).unwrap(),
+            false,
+        );
+        let page1 = hub
+            .dispatch_rpc(
+                "ReadEventQueue",
+                &parse_json(r#"{"after_sequence":0,"limit":1}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        assert_eq!(page1.get_arr("events").unwrap().len(), 1);
+        assert_eq!(page1.get_bool("has_more"), Some(true));
+        let next1 = page1.get_i64("next_after_sequence").unwrap();
+        let page2 = hub
+            .dispatch_rpc(
+                "ReadEventQueue",
+                &parse_json(&format!(r#"{{"after_sequence":{},"limit":1}}"#, next1)).unwrap(),
+                false,
+            )
+            .unwrap();
+        assert_eq!(page2.get_arr("events").unwrap().len(), 1);
+        assert!(page2.get_arr("events").unwrap()[0].get_i64("sequence").unwrap() > next1);
+
+        // 2c. Thermal AutoPurgeOnStationFault: idle mock hood must NOT purge; active PID (0x04) MUST purge
+        let _ = hub
+            .dispatch_rpc(
+                "ThermalAction",
+                &parse_json(r#"{"station_id":"S1","action":"connect","mode":"mock"}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        std::thread::sleep(Duration::from_millis(80));
+        hub.thermal_hub
+            .notify_station_fault_purge("S1", "idle_test_fault");
+        std::thread::sleep(Duration::from_millis(120));
+        let snap_idle = hub
+            .dispatch_rpc(
+                "GetThermalConsole",
+                &parse_json(r#"{"station_id":"S1"}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        let s1_idle = snap_idle
+            .get_arr("stations")
+            .unwrap()
+            .iter()
+            .find(|x| x.get_str_or("station_id", "") == "S1")
+            .unwrap();
+        assert_eq!(
+            s1_idle.get_str_or("mcu_mode", ""),
+            "idle",
+            "Idle untouched hood must NOT spuriously enter cooling_purge on station fault"
+        );
+
+        // Now enter PID (0x07 -> flags 0x04) and trigger fault purge -> must enter cooling_purge!
+        let _ = hub
+            .dispatch_rpc(
+                "ThermalAction",
+                &parse_json(r#"{"station_id":"S1","action":"start_pid"}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        std::thread::sleep(Duration::from_millis(120));
+        hub.thermal_hub
+            .notify_station_fault_purge("S1", "pid_test_fault");
+        std::thread::sleep(Duration::from_millis(120));
+        let snap_pid = hub
+            .dispatch_rpc(
+                "GetThermalConsole",
+                &parse_json(r#"{"station_id":"S1"}"#).unwrap(),
+                false,
+            )
+            .unwrap();
+        let s1_pid = snap_pid
+            .get_arr("stations")
+            .unwrap()
+            .iter()
+            .find(|x| x.get_str_or("station_id", "") == "S1")
+            .unwrap();
+        assert_eq!(
+            s1_pid.get_str_or("mcu_mode", ""),
+            "cooling_purge",
+            "Active PID (flags 0x04) hood MUST enter cooling_purge on station fault"
+        );
+
+        // 3. Last-write-wins: SetStageIntent("uip", run_rmt=true) clears stale "rmt" intent
+        let contract = FirmwareContract::load(Path::new("contracts/firmware-vd012.json"));
+        let mut st = StationState::new("S1", "Station 1", "192.168.2.166", "");
+        let mut pxe_st = JsonVal::obj();
+        let _ = handle_station_command_nonblocking(
+            &mut st,
+            &contract,
+            &mut pxe_st,
+            &tmp_dir,
+            &tmp_dir,
+            "SetStageIntent",
+            &parse_json(r#"{"stage":"rmt","enabled":false}"#).unwrap(),
+            "web",
+        );
+        assert!(st.stage_intents.contains_key("rmt"));
+        let _ = handle_station_command_nonblocking(
+            &mut st,
+            &contract,
+            &mut pxe_st,
+            &tmp_dir,
+            &tmp_dir,
+            "SetStageIntent",
+            &parse_json(r#"{"stage":"uip1","run_rmt":true}"#).unwrap(),
+            "web",
+        );
+        assert!(
+            !st.stage_intents.contains_key("rmt"),
+            "Newer uip1 intent with run_rmt must clear stale rmt intent"
+        );
+
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
 }

+ 33 - 10
native/stl_accel/src/pxe.rs

@@ -574,7 +574,16 @@ pub fn apply_pxe_configuration(
             JsonVal::Str("已更新本地内置 TFTP 目录(未开启外部主机同步)".to_string()),
         );
     }
-    let _ = fs::write(data_dir.join("pxe_control_state.json"), pxe_state.to_json());
+    if let Err(e) = crate::storage::atomic_write_bytes(
+        &data_dir.join("pxe_control_state.json"),
+        pxe_state.to_json().as_bytes(),
+    ) {
+        append_system_debug_log(
+            data_dir,
+            "PXE",
+            &format!("PXE_STATE_SAVE_ERR err={}", e),
+        );
+    }
     append_system_debug_log(
         data_dir,
         "PXE",
@@ -1871,6 +1880,7 @@ fn handle_tftp_wrq(
 
     let mut payload: Vec<u8> = Vec::with_capacity(65536);
     let mut expected_block: u16 = 1;
+    let mut received_any_block = false;
     let mut rx = vec![0u8; 4 + blksize + 64];
     let mut timeouts = 0u32;
     let max_upload_bytes = 64 * 1024 * 1024usize;
@@ -1884,10 +1894,6 @@ fn handle_tftp_wrq(
                 if n >= 4 && u16::from_be_bytes([rx[0], rx[1]]) == 3 {
                     let bno = u16::from_be_bytes([rx[2], rx[3]]);
                     let chunk = &rx[4..n];
-                    let mut ack = [0u8; 4];
-                    ack[0..2].copy_from_slice(&4u16.to_be_bytes());
-                    ack[2..4].copy_from_slice(&bno.to_be_bytes());
-                    let _ = sock.send_to(&ack, peer);
                     timeouts = 0;
 
                     if bno == expected_block {
@@ -1896,10 +1902,21 @@ fn handle_tftp_wrq(
                             return;
                         }
                         payload.extend_from_slice(chunk);
+                        received_any_block = true;
+                        let mut ack = [0u8; 4];
+                        ack[0..2].copy_from_slice(&4u16.to_be_bytes());
+                        ack[2..4].copy_from_slice(&bno.to_be_bytes());
+                        let _ = sock.send_to(&ack, peer);
                         if chunk.len() < blksize {
                             break;
                         }
                         expected_block = expected_block.wrapping_add(1);
+                    } else if received_any_block && bno == expected_block.wrapping_sub(1) {
+                        // Duplicate of previous block (client missed our ACK): re-ACK it without appending
+                        let mut ack = [0u8; 4];
+                        ack[0..2].copy_from_slice(&4u16.to_be_bytes());
+                        ack[2..4].copy_from_slice(&bno.to_be_bytes());
+                        let _ = sock.send_to(&ack, peer);
                     }
                 } else if n >= 4 && u16::from_be_bytes([rx[0], rx[1]]) == 5 {
                     return;
@@ -1910,7 +1927,7 @@ fn handle_tftp_wrq(
                 if timeouts >= 5 {
                     return;
                 }
-                if expected_block == 1 {
+                if !received_any_block {
                     let _ = sock.send_to(&first_reply, peer);
                 } else {
                     let mut ack = [0u8; 4];
@@ -1965,10 +1982,16 @@ fn handle_tftp_wrq(
         }
         pxe_st.set("recent_reports", JsonVal::Arr(rpts));
         pxe_st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
-        let _ = fs::write(
-            hub.data_dir.join("pxe_control_state.json"),
-            pxe_st.to_json(),
-        );
+        if let Err(e) = crate::storage::atomic_write_bytes(
+            &hub.data_dir.join("pxe_control_state.json"),
+            pxe_st.to_json().as_bytes(),
+        ) {
+            append_system_debug_log(
+                &hub.data_dir,
+                "PXE",
+                &format!("PXE_STATE_SAVE_ERR err={}", e),
+            );
+        }
     }
 
     // Deliver HTML/XML report strictly to the originating station without cross-contaminating concurrent stations

+ 427 - 1
native/stl_accel/src/results.rs

@@ -387,6 +387,147 @@ impl AsyncCommandScript {
     }
 }
 
+#[derive(Clone, Debug)]
+pub struct WatchdogConfig {
+    pub enabled: bool,
+    pub link_lost_timeout_ms: i64,
+    pub dense_stage_silence_timeout_ms: i64,
+    pub amt_silence_timeout_ms: i64,
+    pub amt_max_duration_ms: i64,
+    pub mt_silence_timeout_ms: i64,
+    pub mt_max_duration_ms: i64,
+    pub reboot_on_hang: bool,
+    pub max_consecutive_hangs: u32,
+    pub reconnect_prompt_probe_delay_ms: i64,
+}
+
+impl Default for WatchdogConfig {
+    fn default() -> Self {
+        Self {
+            enabled: true,
+            link_lost_timeout_ms: 240_000,           // 4 min (3~5 min dual-disconnect ceiling)
+            dense_stage_silence_timeout_ms: 150_000, // 150s (120~180s for boot/post/training/rmt)
+            amt_silence_timeout_ms: 420_000,         // 7 min (5~10 min for 24-DIMM AMT single algo)
+            amt_max_duration_ms: 3_600_000,          // 60 min total AMT stage cap
+            mt_silence_timeout_ms: 480_000,          // 8 min (5~10 min for MemTest86 block silence)
+            mt_max_duration_ms: 3_600_000,           // 60 min total MemTest86 stage cap
+            reboot_on_hang: false,                   // Level-1 default: preserve hang scene!
+            max_consecutive_hangs: 2,                // Circuit breaker for unattended reboot_on_hang
+            reconnect_prompt_probe_delay_ms: 1_500,  // 1.5s silent delay before probing prompt with CR
+        }
+    }
+}
+
+impl WatchdogConfig {
+    pub fn to_json(&self) -> JsonVal {
+        let mut o = JsonVal::obj();
+        o.set("enabled", JsonVal::Bool(self.enabled));
+        o.set(
+            "link_lost_timeout_ms",
+            JsonVal::Num(self.link_lost_timeout_ms as f64),
+        );
+        o.set(
+            "link_lost_timeout_s",
+            JsonVal::Num((self.link_lost_timeout_ms / 1000) as f64),
+        );
+        o.set(
+            "dense_stage_silence_timeout_ms",
+            JsonVal::Num(self.dense_stage_silence_timeout_ms as f64),
+        );
+        o.set(
+            "dense_stage_silence_timeout_s",
+            JsonVal::Num((self.dense_stage_silence_timeout_ms / 1000) as f64),
+        );
+        o.set(
+            "amt_silence_timeout_ms",
+            JsonVal::Num(self.amt_silence_timeout_ms as f64),
+        );
+        o.set(
+            "amt_silence_timeout_s",
+            JsonVal::Num((self.amt_silence_timeout_ms / 1000) as f64),
+        );
+        o.set(
+            "amt_max_duration_ms",
+            JsonVal::Num(self.amt_max_duration_ms as f64),
+        );
+        o.set(
+            "amt_max_duration_s",
+            JsonVal::Num((self.amt_max_duration_ms / 1000) as f64),
+        );
+        o.set(
+            "mt_silence_timeout_ms",
+            JsonVal::Num(self.mt_silence_timeout_ms as f64),
+        );
+        o.set(
+            "mt_silence_timeout_s",
+            JsonVal::Num((self.mt_silence_timeout_ms / 1000) as f64),
+        );
+        o.set(
+            "mt_max_duration_ms",
+            JsonVal::Num(self.mt_max_duration_ms as f64),
+        );
+        o.set(
+            "mt_max_duration_s",
+            JsonVal::Num((self.mt_max_duration_ms / 1000) as f64),
+        );
+        o.set("reboot_on_hang", JsonVal::Bool(self.reboot_on_hang));
+        o.set(
+            "max_consecutive_hangs",
+            JsonVal::Num(self.max_consecutive_hangs as f64),
+        );
+        o.set(
+            "reconnect_prompt_probe_delay_ms",
+            JsonVal::Num(self.reconnect_prompt_probe_delay_ms as f64),
+        );
+        o
+    }
+
+    pub fn apply_patch(&mut self, raw: &JsonVal) {
+        if let Some(en) = raw.get_bool("enabled") {
+            self.enabled = en;
+        }
+        if let Some(ms) = raw.get_i64("link_lost_timeout_ms") {
+            self.link_lost_timeout_ms = ms.clamp(5_200, 86_400_000);
+        } else if let Some(sec) = raw.get_i64("link_lost_timeout_s") {
+            self.link_lost_timeout_ms = (sec * 1000).clamp(6_000, 86_400_000);
+        }
+        if let Some(ms) = raw.get_i64("dense_stage_silence_timeout_ms") {
+            self.dense_stage_silence_timeout_ms = ms.clamp(1_000, 86_400_000);
+        } else if let Some(sec) = raw.get_i64("dense_stage_silence_timeout_s") {
+            self.dense_stage_silence_timeout_ms = (sec * 1000).clamp(5_000, 86_400_000);
+        }
+        if let Some(ms) = raw.get_i64("amt_silence_timeout_ms") {
+            self.amt_silence_timeout_ms = ms.clamp(1_000, 86_400_000);
+        } else if let Some(sec) = raw.get_i64("amt_silence_timeout_s") {
+            self.amt_silence_timeout_ms = (sec * 1000).clamp(5_000, 86_400_000);
+        }
+        if let Some(ms) = raw.get_i64("amt_max_duration_ms") {
+            self.amt_max_duration_ms = ms.clamp(0, 172_800_000);
+        } else if let Some(sec) = raw.get_i64("amt_max_duration_s") {
+            self.amt_max_duration_ms = (sec * 1000).clamp(0, 172_800_000);
+        }
+        if let Some(ms) = raw.get_i64("mt_silence_timeout_ms") {
+            self.mt_silence_timeout_ms = ms.clamp(1_000, 86_400_000);
+        } else if let Some(sec) = raw.get_i64("mt_silence_timeout_s") {
+            self.mt_silence_timeout_ms = (sec * 1000).clamp(5_000, 86_400_000);
+        }
+        if let Some(ms) = raw.get_i64("mt_max_duration_ms") {
+            self.mt_max_duration_ms = ms.clamp(0, 172_800_000);
+        } else if let Some(sec) = raw.get_i64("mt_max_duration_s") {
+            self.mt_max_duration_ms = (sec * 1000).clamp(0, 172_800_000);
+        }
+        if let Some(roh) = raw.get_bool("reboot_on_hang") {
+            self.reboot_on_hang = roh;
+        }
+        if let Some(mch) = raw.get_i64("max_consecutive_hangs") {
+            self.max_consecutive_hangs = mch.clamp(1, 20) as u32;
+        }
+        if let Some(pms) = raw.get_i64("reconnect_prompt_probe_delay_ms") {
+            self.reconnect_prompt_probe_delay_ms = pms.clamp(100, 30_000);
+        }
+    }
+}
+
 #[derive(Clone, Debug)]
 pub struct StationBaselineSnapshot {
     pub uip_overrides: Vec<JsonVal>,
@@ -394,6 +535,7 @@ pub struct StationBaselineSnapshot {
     pub amt_settings: JsonVal,
     pub mt_selection: JsonVal,
     pub boot_plan: JsonVal,
+    pub watchdog: WatchdogConfig,
 }
 
 pub struct StationState {
@@ -428,6 +570,7 @@ pub struct StationState {
     pub pty_child_pid: i32,
     pub tcp_listener_fd: i32,
     pub tcp_listener_port: i32,
+    pub pty_open_gen: u64,
     pub next_reconnect_probe_ms: i64,
     pub raw_ring: lib::MonotonicRingBuffer,
     pub clean_ring: lib::MonotonicRingBuffer,
@@ -516,6 +659,24 @@ pub struct StationState {
     pub power_seq_in_progress: bool,
     pub power_seq_started_ms: i64,
     pub power_seq_id: u64,
+    pub power_seq_completed_unix_ms: i64,
+    pub amt_started_unix_ms: i64,
+    pub watchdog: WatchdogConfig,
+    pub link_offline_since_unix_ms: i64,
+    pub serial_offline_since_unix_ms: i64,
+    pub serial_gap_detected: bool,
+    pub serial_gap_count: u32,
+    pub serial_gap_total_ms: i64,
+    pub serial_gaps: Vec<JsonVal>,
+    pub reconnect_power_verify_until_ms: i64,
+    pub pending_reconnect_prompt_probe_ms: i64,
+    pub reconnect_prompt_probed_for_session: bool,
+    pub last_fault_code: String,
+    pub last_fault_message: String,
+    pub last_fault_stage: String,
+    pub last_fault_unix_ms: i64,
+    pub hang_scene_preserved: bool,
+    pub consecutive_hang_count: u32,
     pub debug_log_path: Option<PathBuf>,
     pub persistent_baseline: Option<StationBaselineSnapshot>,
     pub dimm_seen_in_boot: [bool; 24],
@@ -582,7 +743,7 @@ impl StationState {
         task_batch.set("runs", JsonVal::Arr(Vec::new()));
 
         let mut stage_errors = BTreeMap::new();
-        for k in ["training", "rmt", "amt", "mt"] {
+        for k in ["training", "rmt", "amt", "mt", "system"] {
             stage_errors.insert(k.to_string(), Vec::new());
         }
 
@@ -629,6 +790,7 @@ impl StationState {
             pty_child_pid: -1,
             tcp_listener_fd: -1,
             tcp_listener_port: 0,
+            pty_open_gen: 0,
             next_reconnect_probe_ms: 0,
             raw_ring: lib::MonotonicRingBuffer::new(RAW_RING_CAPACITY),
             clean_ring: lib::MonotonicRingBuffer::new(CLEAN_RING_CAPACITY),
@@ -716,6 +878,24 @@ impl StationState {
             power_seq_in_progress: false,
             power_seq_started_ms: 0,
             power_seq_id: 0,
+            power_seq_completed_unix_ms: 0,
+            amt_started_unix_ms: 0,
+            watchdog: WatchdogConfig::default(),
+            link_offline_since_unix_ms: 0,
+            serial_offline_since_unix_ms: 0,
+            serial_gap_detected: false,
+            serial_gap_count: 0,
+            serial_gap_total_ms: 0,
+            serial_gaps: Vec::new(),
+            reconnect_power_verify_until_ms: 0,
+            pending_reconnect_prompt_probe_ms: 0,
+            reconnect_prompt_probed_for_session: false,
+            last_fault_code: String::new(),
+            last_fault_message: String::new(),
+            last_fault_stage: String::new(),
+            last_fault_unix_ms: 0,
+            hang_scene_preserved: false,
+            consecutive_hang_count: 0,
             debug_log_path: None,
             persistent_baseline: None,
             dimm_seen_in_boot: [false; 24],
@@ -832,6 +1012,7 @@ impl StationState {
             amt_settings: self.amt_settings.clone(),
             mt_selection: self.mt_selection.clone(),
             boot_plan: self.boot_plan.clone(),
+            watchdog: self.watchdog.clone(),
         };
         self.log_debug(
             "BASELINE",
@@ -864,6 +1045,7 @@ impl StationState {
         self.amt_settings = snap.amt_settings;
         self.mt_selection = snap.mt_selection;
         self.boot_plan = snap.boot_plan;
+        self.watchdog = snap.watchdog;
         self.log_debug(
             "BASELINE",
             &format!(
@@ -953,6 +1135,9 @@ impl StationState {
             }
         }
         self.mt_started_unix_ms = 0;
+        self.amt_started_unix_ms = 0;
+        self.power_seq_completed_unix_ms = 0;
+        self.reset_boot_fault_and_gap_tracking();
         self.mt_report_sync_pending = false;
         self.mt_report_fetched_for_boot = false;
         self.mt_waiting_report_until_ms = 0;
@@ -978,6 +1163,8 @@ impl StationState {
         self.tx_pacer.clear();
         self.pending_complete_signal = None;
         if !keep_active_run {
+            self.clear_serial_gaps();
+            self.consecutive_hang_count = 0;
             self.task_status = "not_started".to_string();
             self.stage_intents.clear();
             self.restore_persistent_baseline(&format!("external_restart:{}", reason_detail));
@@ -1108,6 +1295,11 @@ impl StationState {
         self.run_started_unix_ms = 0;
         self.run_ended_unix_ms = 0;
         self.mt_started_unix_ms = 0;
+        self.amt_started_unix_ms = 0;
+        self.power_seq_completed_unix_ms = 0;
+        self.reset_boot_fault_and_gap_tracking();
+        self.clear_serial_gaps();
+        self.consecutive_hang_count = 0;
         self.mt_report_sync_pending = false;
         self.mt_report_fetched_for_boot = false;
         self.mt_waiting_report_until_ms = 0;
@@ -1198,6 +1390,7 @@ impl StationState {
     #[inline]
     pub fn has_any_failure_state(&self) -> bool {
         self.awaiting_dimm_replacement
+            || !self.last_fault_code.is_empty()
             || self.hot.mt_fail_complete
             || self.mt_result.get_str_or("status", "") == "fail"
             || self
@@ -1207,6 +1400,215 @@ impl StationState {
             || self.stage_errors.values().any(|v| !v.is_empty())
     }
 
+    pub fn reset_boot_fault_and_gap_tracking(&mut self) {
+        self.link_offline_since_unix_ms = 0;
+        self.serial_offline_since_unix_ms = 0;
+        self.reconnect_power_verify_until_ms = 0;
+        self.pending_reconnect_prompt_probe_ms = 0;
+        self.reconnect_prompt_probed_for_session = false;
+        self.last_fault_code.clear();
+        self.last_fault_message.clear();
+        self.last_fault_stage.clear();
+        self.last_fault_unix_ms = 0;
+        self.hang_scene_preserved = false;
+    }
+
+    pub fn clear_serial_gaps(&mut self) {
+        self.serial_gap_detected = false;
+        self.serial_gap_count = 0;
+        self.serial_gap_total_ms = 0;
+        self.serial_gaps.clear();
+    }
+
+    pub fn record_serial_gap(&mut self, offline_since_ms: i64, now: i64) {
+        if offline_since_ms <= 0 || now <= offline_since_ms {
+            return;
+        }
+        let gap_ms = now.saturating_sub(offline_since_ms);
+        if gap_ms < 2_000 {
+            return;
+        }
+        self.serial_gap_detected = true;
+        self.serial_gap_count = self.serial_gap_count.saturating_add(1);
+        self.serial_gap_total_ms = self.serial_gap_total_ms.saturating_add(gap_ms);
+        if self.serial_gaps.len() >= 50 {
+            self.serial_gaps.remove(0);
+        }
+        let mut g = JsonVal::obj();
+        g.set("index", JsonVal::Num(self.serial_gap_count as f64));
+        g.set("offline_unix_ms", JsonVal::Num(offline_since_ms as f64));
+        g.set("recovered_unix_ms", JsonVal::Num(now as f64));
+        g.set("duration_ms", JsonVal::Num(gap_ms as f64));
+        g.set("phase", JsonVal::Str(self.observed_phase.clone()));
+        self.serial_gaps.push(g);
+        self.log_debug(
+            "CONN",
+            &format!(
+                "SERIAL_GAP_DETECTED count={} duration_ms={} total_ms={} phase={} boot_id={}",
+                self.serial_gap_count,
+                gap_ms,
+                self.serial_gap_total_ms,
+                self.observed_phase,
+                self.boot_id
+            ),
+        );
+    }
+
+    pub fn active_stage_silence_limit_ms(&self) -> i64 {
+        match self.observed_phase.as_str() {
+            "amt" => self.watchdog.amt_silence_timeout_ms,
+            "mt" => self.watchdog.mt_silence_timeout_ms,
+            _ => self.watchdog.dense_stage_silence_timeout_ms,
+        }
+    }
+
+    pub fn last_activity_anchor_ms(&self) -> i64 {
+        self.hot
+            .last_rx_unix_ms
+            .max(self.observed_unix_ms)
+            .max(self.power_seq_completed_unix_ms)
+            .max(self.run_started_unix_ms)
+    }
+
+    pub fn latch_watchdog_or_link_fault(
+        &mut self,
+        fault_code: &str,
+        stage_hint: &str,
+        msg: &str,
+        preserve_scene: bool,
+        silence_ms: i64,
+        now: i64,
+    ) {
+        let stage_key = match stage_hint {
+            "training" | "rmt" | "amt" | "mt" => stage_hint,
+            _ => match self.observed_phase.as_str() {
+                "training" | "rmt" | "amt" | "mt" => self.observed_phase.as_str(),
+                _ => "system",
+            },
+        }
+        .to_string();
+        let display_stage = if !stage_hint.is_empty() && stage_hint != "unknown" {
+            stage_hint.to_string()
+        } else if !self.observed_phase.is_empty() && self.observed_phase != "unknown" {
+            self.observed_phase.clone()
+        } else {
+            "boot".to_string()
+        };
+
+        let mut err = JsonVal::obj();
+        err.set("stage", JsonVal::Str(display_stage.clone()));
+        err.set("kind", JsonVal::Str(fault_code.to_string()));
+        err.set("fault_code", JsonVal::Str(fault_code.to_string()));
+        if let Some(c) = self.observed_cpu {
+            err.set("cpu", JsonVal::Num(c as f64));
+        }
+        if silence_ms > 0 {
+            err.set("silence_ms", JsonVal::Num(silence_ms as f64));
+        }
+        err.set("hang_scene_preserved", JsonVal::Bool(preserve_scene));
+        err.set("message", JsonVal::Str(msg.to_string()));
+        err.set("observed_unix_ms", JsonVal::Str(now.to_string()));
+        let list = self.stage_errors.entry(stage_key).or_default();
+        if !list.iter().any(|x| x.get_str_or("fault_code", "") == fault_code) {
+            if list.len() >= 200 {
+                list.remove(0);
+            }
+            list.push(err);
+        }
+
+        self.last_err_stage = display_stage.clone();
+        self.last_fault_code = fault_code.to_string();
+        self.last_fault_message = msg.to_string();
+        self.last_fault_stage = display_stage.clone();
+        self.last_fault_unix_ms = now;
+        self.hang_scene_preserved = preserve_scene;
+        self.observed_detail = fault_code.to_string();
+        self.async_script.clear();
+        self.tx_pacer.clear();
+        self.prompt_ready = false;
+        self.hot.prompt_ready = false;
+        self.task_status = "failed".to_string();
+        self.boot_execution
+            .set("state", JsonVal::Str("failed".to_string()));
+        self.boot_execution
+            .set("current_stage", JsonVal::Str(display_stage.clone()));
+        self.boot_execution
+            .set("fault_code", JsonVal::Str(fault_code.to_string()));
+        self.boot_execution
+            .set("hang_scene_preserved", JsonVal::Bool(preserve_scene));
+        self.boot_execution.set("error", JsonVal::Str(msg.to_string()));
+        self.boot_execution
+            .set("waiting_reason", JsonVal::Str(msg.to_string()));
+        self.boot_execution
+            .set("updated_unix_ms", JsonVal::Num(now as f64));
+        self.log_debug(
+            "WATCHDOG",
+            &format!(
+                "FAULT_LATCHED code={} stage={} preserve_scene={} silence_ms={} consecutive_hangs={} boot_id={} msg={}",
+                fault_code,
+                display_stage,
+                preserve_scene,
+                silence_ms,
+                self.consecutive_hang_count,
+                self.boot_id,
+                msg
+            ),
+        );
+    }
+
+    pub fn build_watchdog_status_json(&self, now: i64) -> JsonVal {
+        let mut o = self.watchdog.to_json();
+        let anchor = self.last_activity_anchor_ms();
+        let silence_ms = if self.is_run_active() && anchor > 0 && now > anchor {
+            now.saturating_sub(anchor)
+        } else {
+            0
+        };
+        let link_offline_ms = if self.link_offline_since_unix_ms > 0 && now > self.link_offline_since_unix_ms {
+            now.saturating_sub(self.link_offline_since_unix_ms)
+        } else {
+            0
+        };
+        o.set("last_rx_unix_ms", JsonVal::Num(self.hot.last_rx_unix_ms as f64));
+        o.set("silence_ms", JsonVal::Num(silence_ms as f64));
+        o.set(
+            "active_stage_silence_limit_ms",
+            JsonVal::Num(self.active_stage_silence_limit_ms() as f64),
+        );
+        o.set(
+            "link_offline_waiting",
+            JsonVal::Bool(self.observed_detail == "link_offline_waiting"),
+        );
+        o.set(
+            "link_offline_since_unix_ms",
+            JsonVal::Num(self.link_offline_since_unix_ms as f64),
+        );
+        o.set("link_offline_elapsed_ms", JsonVal::Num(link_offline_ms as f64));
+        o.set("serial_gap_detected", JsonVal::Bool(self.serial_gap_detected));
+        o.set("serial_gap_count", JsonVal::Num(self.serial_gap_count as f64));
+        o.set(
+            "serial_gap_total_ms",
+            JsonVal::Num(self.serial_gap_total_ms as f64),
+        );
+        o.set("serial_gaps", JsonVal::Arr(self.serial_gaps.clone()));
+        o.set("fault_code", JsonVal::Str(self.last_fault_code.clone()));
+        o.set(
+            "fault_message",
+            JsonVal::Str(self.last_fault_message.clone()),
+        );
+        o.set("fault_stage", JsonVal::Str(self.last_fault_stage.clone()));
+        o.set("fault_unix_ms", JsonVal::Num(self.last_fault_unix_ms as f64));
+        o.set(
+            "hang_scene_preserved",
+            JsonVal::Bool(self.hang_scene_preserved),
+        );
+        o.set(
+            "consecutive_hang_count",
+            JsonVal::Num(self.consecutive_hang_count as f64),
+        );
+        o
+    }
+
     #[inline]
     pub fn has_entered_ddr_training(&self) -> bool {
         self.observed_stages.contains("uip")
@@ -1328,6 +1730,12 @@ impl StationState {
                 ),
             );
         }
+        if new_phase == "amt" && self.amt_started_unix_ms == 0 {
+            self.amt_started_unix_ms = now;
+        }
+        if new_phase == "mt" && self.mt_started_unix_ms == 0 {
+            self.mt_started_unix_ms = now;
+        }
         self.observed_stages.insert(new_phase.to_string());
         self.observed_unix_ms = now;
         self.hot.observed_unix_ms = now;
@@ -2039,6 +2447,11 @@ impl StationState {
             self.run_ended_unix_ms = 0;
             self.single_run_started_ms = 0;
             self.mt_started_unix_ms = 0;
+            self.amt_started_unix_ms = 0;
+            self.power_seq_completed_unix_ms = 0;
+            self.reset_boot_fault_and_gap_tracking();
+            self.clear_serial_gaps();
+            self.consecutive_hang_count = 0;
             self.mt_report_sync_pending = false;
             self.mt_report_fetched_for_boot = false;
             self.mt_waiting_report_until_ms = 0;
@@ -2047,6 +2460,7 @@ impl StationState {
             self.plan_configured.clear();
             self.plan_done.clear();
             self.plan_amt_started.clear();
+            self.stage_intents.clear();
             self.observed_stages.clear();
             self.stage_step_counts.clear();
             self.rmt_results.clear();
@@ -2375,6 +2789,9 @@ impl StationState {
                     self.run_ended_unix_ms = 0;
                 }
                 self.mt_started_unix_ms = 0;
+        self.amt_started_unix_ms = 0;
+        self.power_seq_completed_unix_ms = 0;
+        self.reset_boot_fault_and_gap_tracking();
                 self.mt_report_sync_pending = false;
                 self.mt_report_fetched_for_boot = false;
                 self.mt_waiting_report_until_ms = 0;
@@ -2674,6 +3091,15 @@ impl StationState {
                 } else if real_training {
                     self.hot.ict_stage1_complete = true;
                     self.hot.awaiting_reset_banner = false;
+                    // Self-heal if ICT Stage 1 banner was missed during a serial disconnect while
+                    // `observed_uip_stage` still held `2` from an earlier run: MRC is strictly pre-Stage2!
+                    if self.observed_uip_stage == Some(2) {
+                        self.observed_uip_stage = Some(1);
+                        self.hot.observed_uip_stage = 1;
+                    }
+                    self.hot.ict_stage2_complete = false;
+                    self.plan_done.retain(|k| !k.contains(":uip2:"));
+                    self.plan_configured.retain(|k| !k.contains(":uip2:"));
                     self.advance_phase("training", "training_step", now);
                     *self.stage_step_counts.entry("training".to_string()).or_insert(0) += 1;
                 } else {

+ 79 - 3
native/stl_accel/src/storage.rs

@@ -7,9 +7,37 @@ use std::collections::BTreeMap;
 use std::fs;
 use std::io::Write;
 use std::path::Path;
+use std::sync::atomic::{AtomicU64, Ordering};
 use std::sync::{Mutex, OnceLock};
 
 static DEBUG_LOG_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+static ATOMIC_TMP_SEQ: AtomicU64 = AtomicU64::new(1);
+
+/// Atomic write via sibling `.tmp` + `sync_all` + `rename` so sudden power loss never truncates configs.
+pub fn atomic_write_bytes(path: &Path, data: &[u8]) -> std::io::Result<()> {
+    if let Some(parent) = path.parent() {
+        if !parent.as_os_str().is_empty() {
+            fs::create_dir_all(parent)?;
+        }
+    }
+    let seq = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
+    let fname = path
+        .file_name()
+        .and_then(|s| s.to_str())
+        .unwrap_or("file");
+    let tmp_path = path.with_file_name(format!(".{}.tmp.{}.{}", fname, std::process::id(), seq));
+    let mut f = fs::File::create(&tmp_path)?;
+    if let Err(e) = f.write_all(data).and_then(|_| f.sync_all()) {
+        let _ = fs::remove_file(&tmp_path);
+        return Err(e);
+    }
+    drop(f);
+    if let Err(e) = fs::rename(&tmp_path, path) {
+        let _ = fs::remove_file(&tmp_path);
+        return Err(e);
+    }
+    Ok(())
+}
 
 #[inline]
 fn unix_ms_to_utc_string(ts: i64) -> String {
@@ -233,6 +261,9 @@ pub fn load_station_settings(data_dir: &Path, stations: &mut BTreeMap<String, St
         if let Some(bp) = saved.get("boot_plan") {
             st.boot_plan = bp.clone();
         }
+        if let Some(wd) = saved.get("watchdog") {
+            st.watchdog.apply_patch(wd);
+        }
         if let Some(tb) = saved.get("task_batch") {
             let mut clean_tb = strip_private_keys_recursive(tb);
             let tb_state = clean_tb.get_str_or("state", "idle");
@@ -288,6 +319,7 @@ pub fn save_station_settings(data_dir: &Path, st: &StationState) {
     let mt_sel = base.map(|b| &b.mt_selection).unwrap_or(&st.mt_selection);
     let amt_cfg = base.map(|b| &b.amt_settings).unwrap_or(&st.amt_settings);
     let bp_cfg = base.map(|b| &b.boot_plan).unwrap_or(&st.boot_plan);
+    let wd_cfg = base.map(|b| &b.watchdog).unwrap_or(&st.watchdog);
 
     let mut fw = JsonVal::obj();
     fw.set("uip_overrides", JsonVal::Arr(ovs.clone()));
@@ -336,11 +368,17 @@ pub fn save_station_settings(data_dir: &Path, st: &StationState) {
     root.set("firmware_settings", fw);
     root.set("amt_settings", amt_cfg.clone());
     root.set("boot_plan", bp_cfg.clone());
+    root.set("watchdog", wd_cfg.to_json());
     root.set("task_batch", st.task_batch.clone());
     root.set("task_history", JsonVal::Arr(st.task_history.clone()));
     root.set("saved_profiles", JsonVal::Arr(st.saved_profiles.clone()));
     let p = dir.join(format!("{}.json", st.station_id));
-    let _ = fs::write(p, root.to_json());
+    if let Err(e) = atomic_write_bytes(&p, root.to_json().as_bytes()) {
+        st.log_debug(
+            "STORAGE",
+            &format!("SAVE_SETTINGS_ERR path={} err={}", p.display(), e),
+        );
+    }
     st.log_debug(
         "STORAGE",
         &format!(
@@ -417,6 +455,11 @@ pub fn archive_task_run(
         let arr = st.stage_errors.get(k).cloned().unwrap_or_default();
         stg_errs.set(k, JsonVal::Arr(arr));
     }
+    if let Some(sys_errs) = st.stage_errors.get("system") {
+        if !sys_errs.is_empty() {
+            stg_errs.set("system", JsonVal::Arr(sys_errs.clone()));
+        }
+    }
 
     let mut disk_summary = JsonVal::obj();
     disk_summary.set("run_id", JsonVal::Str(run_id.to_string()));
@@ -438,6 +481,28 @@ pub fn archive_task_run(
     disk_summary.set("amt_results", JsonVal::Arr(amt_arr));
     disk_summary.set("mt_result", st.mt_result.clone());
     disk_summary.set("stage_errors", stg_errs);
+    if !st.last_fault_code.is_empty() {
+        disk_summary.set("fault_code", JsonVal::Str(st.last_fault_code.clone()));
+        disk_summary.set("fault_message", JsonVal::Str(st.last_fault_message.clone()));
+        disk_summary.set("fault_stage", JsonVal::Str(st.last_fault_stage.clone()));
+        disk_summary.set(
+            "hang_scene_preserved",
+            JsonVal::Bool(st.hang_scene_preserved),
+        );
+    }
+    disk_summary.set("serial_gap_detected", JsonVal::Bool(st.serial_gap_detected));
+    disk_summary.set("serial_gap_count", JsonVal::Num(st.serial_gap_count as f64));
+    disk_summary.set(
+        "serial_gap_total_ms",
+        JsonVal::Num(st.serial_gap_total_ms as f64),
+    );
+    if !st.serial_gaps.is_empty() {
+        disk_summary.set("serial_gaps", JsonVal::Arr(st.serial_gaps.clone()));
+    }
+    disk_summary.set(
+        "consecutive_hang_count",
+        JsonVal::Num(st.consecutive_hang_count as f64),
+    );
     disk_summary.set(
         "unsupported_commands",
         JsonVal::Arr(st.unsupported_commands.clone()),
@@ -459,7 +524,12 @@ pub fn archive_task_run(
     let sum_path = dir.join("summary.json");
     let sum_path_str = sum_path.to_string_lossy().to_string();
     disk_summary.set("summary_path", JsonVal::Str(sum_path_str.clone()));
-    let _ = fs::write(&sum_path, disk_summary.to_json());
+    if let Err(e) = atomic_write_bytes(&sum_path, disk_summary.to_json().as_bytes()) {
+        st.log_debug(
+            "ARCHIVE",
+            &format!("SUMMARY_WRITE_ERR path={} err={}", sum_path.display(), e),
+        );
+    }
     st.log_debug(
         "ARCHIVE",
         &format!(
@@ -507,7 +577,13 @@ pub fn load_pxe_state(data_dir: &Path) -> JsonVal {
             return val;
         }
     }
-    let _ = fs::write(&p, def.to_json());
+    if let Err(e) = atomic_write_bytes(&p, def.to_json().as_bytes()) {
+        append_system_debug_log(
+            data_dir,
+            "STORAGE",
+            &format!("PXE_STATE_INIT_ERR path={} err={}", p.display(), e),
+        );
+    }
     def
 }
 

+ 84 - 5
native/stl_accel/src/thermal_mcu.rs

@@ -1298,6 +1298,7 @@ struct ThermalSlotRuntime {
     tcp_host: String,
     tcp_port: i32,
     fd: i32,
+    fd_open_gen: u64,
     mock_dev: Option<MockMcuDevice>,
     next_reconnect_ms: i64,
     last_conn_error: String,
@@ -1323,6 +1324,8 @@ struct ThermalSlotRuntime {
     rx_frames_ok: u64,
     tx_frames_sent: u64,
     cooling_requested: bool,
+    heat_commanded: bool,
+    last_heat_cmd_ms: i64,
 
     mcu_bmc_temps: [Option<u8>; 24],
     mcu_bmc_updated_ms: i64,
@@ -1402,6 +1405,7 @@ impl ThermalSlotRuntime {
             tcp_host: String::new(),
             tcp_port: 4002,
             fd: -1,
+            fd_open_gen: 0,
             mock_dev: None,
             next_reconnect_ms: 0,
             last_conn_error: String::new(),
@@ -1424,6 +1428,8 @@ impl ThermalSlotRuntime {
             rx_frames_ok: 0,
             tx_frames_sent: 0,
             cooling_requested: false,
+            heat_commanded: false,
+            last_heat_cmd_ms: 0,
             mcu_bmc_temps: [None; 24],
             mcu_bmc_updated_ms: 0,
             ct_temps: [None; 8],
@@ -1608,9 +1614,11 @@ impl ThermalSlotRuntime {
         if self.fd >= 0 {
             lib::close_fd(self.fd);
             self.fd = -1;
+            self.fd_open_gen = self.fd_open_gen.wrapping_add(1);
         }
         self.mock_dev = None;
         self.manual_hold_keepalive = false;
+        self.heat_commanded = false;
         self.followup_cmd_queue.clear();
         if let Some(mut w) = self.pending_waiter.take() {
             if let Some(tx) = w.reply_tx.take() {
@@ -1898,6 +1906,11 @@ impl ThermalSlotRuntime {
                     }
                     if (new_flags & 0x06) == 0 && (new_flags & 0x40) == 0 {
                         self.clear_safety_lease();
+                        if self.heat_commanded && now.saturating_sub(self.last_heat_cmd_ms) > 3000 {
+                            self.heat_commanded = false;
+                        }
+                    } else {
+                        self.cooling_requested = false;
                     }
                     self.last_f0_ms = now;
                 }
@@ -3048,6 +3061,7 @@ impl ThermalHubRuntime {
             }
             slot.serial_baud = baud;
             slot.fd = fd;
+            slot.fd_open_gen = slot.fd_open_gen.wrapping_add(1);
             slot.connected_since_ms = now;
             slot.last_conn_error.clear();
             if slot.session_started_ms == 0 {
@@ -3403,6 +3417,7 @@ impl ThermalHubRuntime {
                         slot.tcp_host = host.clone();
                         slot.tcp_port = port;
                         slot.fd = fd;
+                        slot.fd_open_gen = slot.fd_open_gen.wrapping_add(1);
                         slot.transport_mode = "tcp".to_string();
                         slot.desired_connected = true;
                         slot.connected_since_ms = now;
@@ -3492,6 +3507,8 @@ impl ThermalHubRuntime {
                 slot.last_set_target_c = temp_u8;
                 slot.manual_hold_keepalive = false;
                 slot.cooling_requested = false;
+                slot.heat_commanded = true;
+                slot.last_heat_cmd_ms = now;
                 slot.arm_safety_lease(now);
 
                 let mut started_rec = false;
@@ -3553,6 +3570,8 @@ impl ThermalHubRuntime {
             }
             "skip_preheat" => {
                 let slot = self.slots.get_mut(sid).unwrap();
+                slot.heat_commanded = true;
+                slot.last_heat_cmd_ms = now;
                 slot.arm_safety_lease(now);
                 slot.send_command_with_waiter(
                     0x06,
@@ -3566,6 +3585,8 @@ impl ThermalHubRuntime {
             }
             "start_pid" => {
                 let slot = self.slots.get_mut(sid).unwrap();
+                slot.heat_commanded = true;
+                slot.last_heat_cmd_ms = now;
                 slot.arm_safety_lease(now);
                 slot.send_command_with_waiter(
                     0x07,
@@ -3581,6 +3602,7 @@ impl ThermalHubRuntime {
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.manual_hold_keepalive = false;
                 slot.cooling_requested = false;
+                slot.heat_commanded = false;
                 slot.clear_safety_lease();
                 slot.send_command_with_waiter(
                     0x05,
@@ -3597,6 +3619,7 @@ impl ThermalHubRuntime {
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.manual_hold_keepalive = false;
                 slot.cooling_requested = purge;
+                slot.heat_commanded = false;
                 slot.clear_safety_lease();
                 let payload = [if purge { 0x00 } else { 0x01 }];
                 let label = if purge {
@@ -3608,6 +3631,7 @@ impl ThermalHubRuntime {
             }
             "stop_heaters" => {
                 let slot = self.slots.get_mut(sid).unwrap();
+                slot.heat_commanded = false;
                 for d in &mut slot.manual_duty[..24] {
                     *d = 0;
                 }
@@ -3644,6 +3668,7 @@ impl ThermalHubRuntime {
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.manual_hold_keepalive = false;
                 slot.cooling_requested = false;
+                slot.heat_commanded = false;
                 slot.manual_duty.fill(0);
                 slot.clear_safety_lease();
                 slot.followup_cmd_queue.clear();
@@ -3734,8 +3759,11 @@ impl ThermalHubRuntime {
                 slot.manual_hold_keepalive = keepalive && any_nonzero;
                 slot.next_manual_keepalive_ms = now + 4000;
                 if any_nonzero {
+                    slot.heat_commanded = true;
+                    slot.last_heat_cmd_ms = now;
                     slot.arm_safety_lease(now);
                 } else {
+                    slot.heat_commanded = false;
                     slot.clear_safety_lease();
                 }
                 slot.send_command_with_waiter(
@@ -3921,6 +3949,10 @@ enum ThermalActorMsg {
         bytes: Vec<u8>,
         reply_tx: mpsc::Sender<()>,
     },
+    AutoPurgeOnStationFault {
+        station_id: String,
+        reason: String,
+    },
 }
 
 pub struct ThermalMcuHub {
@@ -3956,16 +3988,16 @@ impl ThermalMcuHub {
                         }
                     }
                 }
-                let mut tracked_fds: BTreeMap<String, i32> = BTreeMap::new();
+                let mut tracked_fds: BTreeMap<String, (i32, u64)> = BTreeMap::new();
                 let mut tokens = [0u64; 16];
                 let mut ev_masks = [0u32; 16];
 
                 loop {
-                    // Sync epoll watched serial/TCP fds per station
+                    // Sync epoll watched serial/TCP fds per station (track generation to handle OS fd reuse)
                     if epfd >= 0 {
                         for (sid, slot) in &rt.slots {
-                            let prev_fd = tracked_fds.get(sid).copied().unwrap_or(-1);
-                            if slot.fd != prev_fd {
+                            let (prev_fd, prev_gen) = tracked_fds.get(sid).copied().unwrap_or((-1, 0));
+                            if slot.fd != prev_fd || slot.fd_open_gen != prev_gen {
                                 if prev_fd >= 0 {
                                     unsafe {
                                         lib::stl_epoll_ctl_fd(
@@ -3989,7 +4021,7 @@ impl ThermalMcuHub {
                                         );
                                     }
                                 }
-                                tracked_fds.insert(sid.clone(), slot.fd);
+                                tracked_fds.insert(sid.clone(), (slot.fd, slot.fd_open_gen));
                             }
                         }
                         let n = unsafe {
@@ -4052,6 +4084,39 @@ impl ThermalMcuHub {
                                 }
                                 let _ = reply_tx.send(());
                             }
+                            ThermalActorMsg::AutoPurgeOnStationFault {
+                                station_id,
+                                reason,
+                            } => {
+                                if let Some(slot) = rt.slots.get_mut(&station_id) {
+                                    let link_active = slot.fd >= 0
+                                        || (slot.transport_mode == "mock"
+                                            && slot.mock_dev.is_some());
+                                    // flags bits: 0x02=preheating, 0x04=pid_running, 0x40=manual_active
+                                    let heating_or_holding = (slot.flags & 0x46) != 0
+                                        || slot.heat_commanded
+                                        || slot.manual_hold_keepalive;
+                                    if link_active && heating_or_holding && !slot.cooling_requested {
+                                        slot.manual_hold_keepalive = false;
+                                        slot.heat_commanded = false;
+                                        slot.followup_cmd_queue.clear();
+                                        slot.cooling_requested = true;
+                                        slot.clear_safety_lease();
+                                        if slot.send_raw_frame(0x08, &[0x00], now).is_ok() {
+                                            let msg = format!(
+                                                "工位测试异常终止 ({}),已自动下发 0x08 00 停热并开启 8 路风扇 100% 吹扫降温",
+                                                reason
+                                            );
+                                            slot.push_event(
+                                                now,
+                                                "warning",
+                                                "station_fault_auto_purge",
+                                                &msg,
+                                            );
+                                        }
+                                    }
+                                }
+                            }
                         }
                     }
 
@@ -4101,6 +4166,7 @@ impl ThermalMcuHub {
                                     s.next_reconnect_ms = now + 2000;
                                     if new_fd >= 0 {
                                         s.fd = new_fd;
+                                        s.fd_open_gen = s.fd_open_gen.wrapping_add(1);
                                         s.last_conn_error.clear();
                                         s.push_event(
                                             now,
@@ -4341,4 +4407,17 @@ impl ThermalMcuHub {
             let _ = reply_rx.recv_timeout(Duration::from_secs(3));
         }
     }
+
+    pub fn notify_station_fault_purge(&self, station_id: &str, reason: &str) {
+        if self
+            .tx
+            .send(ThermalActorMsg::AutoPurgeOnStationFault {
+                station_id: station_id.to_string(),
+                reason: reason.to_string(),
+            })
+            .is_ok()
+        {
+            self.notify();
+        }
+    }
 }

+ 440 - 24
native/stl_accel/src/workflow.rs

@@ -318,6 +318,39 @@ pub fn tick_async_script(st: &mut StationState) {
                     out_str.trim()
                 );
                 if st.async_script.context_tag.starts_with("plan_") {
+                    if !fw_rejected && st.diag_state != "online" {
+                        // `:2200` serial link dropped mid-script! Do NOT accuse firmware of rejecting
+                        // the command or kill the active run; roll back `plan_done` for this stage so
+                        // disconnect protection (`link_offline_waiting`) preserves the run and resumes on reconnect.
+                        let stage_suffix = match st.async_script.context_tag.as_str() {
+                            "plan_uip1" => ":uip1:",
+                            "plan_uip2" => ":uip2:",
+                            "plan_amt" => ":amt:",
+                            "plan_mt" => ":uefi:",
+                            _ => "",
+                        };
+                        if !stage_suffix.is_empty() && !st.boot_id.is_empty() {
+                            let b_prefix = st.boot_id.clone();
+                            st.plan_done
+                                .retain(|k| !(k.starts_with(&b_prefix) && k.contains(stage_suffix)));
+                            st.plan_configured
+                                .retain(|k| !(k.starts_with(&b_prefix) && k.contains(stage_suffix)));
+                        }
+                        if st.async_script.context_tag == "plan_mt" {
+                            st.plan_mt_started = false;
+                        }
+                        st.log_debug(
+                            "SCRIPT",
+                            &format!(
+                                "ABORT_ON_SERIAL_DROP tag={} cmd='{}' boot_id={} keeping_run_active=true",
+                                st.async_script.context_tag,
+                                st.async_script.step_sent_line,
+                                st.boot_id
+                            ),
+                        );
+                        st.async_script.clear();
+                        return;
+                    }
                     st.task_status = "failed".to_string();
                     let batch_continuing = st.task_batch.get_str_or("state", "idle") == "running"
                         && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
@@ -411,6 +444,34 @@ pub fn tick_async_script(st: &mut StationState) {
         };
         if let Err(e) = write_station_paced(st, &wire_bytes) {
             if st.async_script.context_tag.starts_with("plan_") {
+                if (st.console_enabled || st.bmc_enabled) && st.diag_state != "online" {
+                    let stage_suffix = match st.async_script.context_tag.as_str() {
+                        "plan_uip1" => ":uip1:",
+                        "plan_uip2" => ":uip2:",
+                        "plan_amt" => ":amt:",
+                        "plan_mt" => ":uefi:",
+                        _ => "",
+                    };
+                    if !stage_suffix.is_empty() && !st.boot_id.is_empty() {
+                        let b_prefix = st.boot_id.clone();
+                        st.plan_done
+                            .retain(|k| !(k.starts_with(&b_prefix) && k.contains(stage_suffix)));
+                        st.plan_configured
+                            .retain(|k| !(k.starts_with(&b_prefix) && k.contains(stage_suffix)));
+                    }
+                    if st.async_script.context_tag == "plan_mt" {
+                        st.plan_mt_started = false;
+                    }
+                    st.log_debug(
+                        "SCRIPT",
+                        &format!(
+                            "TX_DROP_DEFER tag={} cmd='{}' boot_id={} err='{}'",
+                            st.async_script.context_tag, step.line, st.boot_id, e
+                        ),
+                    );
+                    st.async_script.clear();
+                    return;
+                }
                 st.task_status = "failed".to_string();
                 let batch_continuing = st.task_batch.get_str_or("state", "idle") == "running"
                     && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
@@ -727,6 +788,15 @@ pub fn control_boot_plan_impl(
                     );
                 }
                 st.mt_started_unix_ms = 0;
+                st.amt_started_unix_ms = 0;
+                st.power_seq_completed_unix_ms = 0;
+                st.reset_boot_fault_and_gap_tracking();
+                st.clear_serial_gaps();
+                st.observed_unix_ms = now;
+                st.hot.observed_unix_ms = now;
+                if !preserve_batch_timer {
+                    st.consecutive_hang_count = 0;
+                }
                 st.mt_per_test_errs.clear();
                 st.mt_completed_test_ids.clear();
                 st.mt_report_sync_pending = false;
@@ -760,6 +830,7 @@ pub fn control_boot_plan_impl(
             } else {
                 if !preserve_batch_timer {
                     st.start_run_timing(now, "control_boot_plan:start");
+                    st.consecutive_hang_count = 0;
                 } else if st.run_started_unix_ms <= 0 {
                     st.start_run_timing(now, "control_boot_plan:start_batch_init");
                 } else {
@@ -772,6 +843,30 @@ pub fn control_boot_plan_impl(
                         ),
                     );
                 }
+                st.reset_boot_fault_and_gap_tracking();
+                st.clear_serial_gaps();
+                st.observed_unix_ms = now;
+                st.hot.observed_unix_ms = now;
+                // If previous run had already finished (or completed/failed MT at UEFI Shell),
+                // clear terminal MT flags so starting a fresh run from UEFI Shell actually launches MT!
+                if st.hot.mt_pass_complete
+                    || st.hot.mt_fail_complete
+                    || matches!(st.task_status.as_str(), "completed" | "failed" | "interrupted")
+                {
+                    st.hot.mt_pass_complete = false;
+                    st.hot.mt_fail_complete = false;
+                    st.hot.mt_banner_seen = false;
+                    st.mt_result = JsonVal::obj();
+                    st.mt_started_unix_ms = 0;
+                    st.mt_per_test_errs.clear();
+                    st.mt_completed_test_ids.clear();
+                    st.mt_report_sync_pending = false;
+                    st.mt_report_fetched_for_boot = false;
+                    st.mt_waiting_report_until_ms = 0;
+                    if let Some(errs) = st.stage_errors.get_mut("mt") {
+                        errs.clear();
+                    }
+                }
                 st.diag_session_id = format!("D-{}-{}-{}", st.station_id, st.boot_seq.max(1), now);
             }
             st.awaiting_dimm_replacement = false;
@@ -846,6 +941,7 @@ pub fn control_boot_plan_impl(
                 st.task_status = "interrupted".to_string();
             }
             st.freeze_run_timing(now);
+            st.stage_intents.clear();
             st.restore_persistent_baseline("control_boot_plan_stop");
             st.log_debug(
                 "PLAN",
@@ -1133,6 +1229,201 @@ pub fn build_uefi_mt_steps(st: &StationState, sel: &JsonVal) -> Vec<AsyncScriptS
     steps
 }
 
+/// Stage-graded silence & total-duration watchdog with Level-1 (preserve hang scene + cool hood)
+/// vs Level-2 (optional unattended `reboot_on_hang` with `max_consecutive_hangs` circuit breaker) decoupling.
+pub fn evaluate_stage_watchdog(st: &mut StationState, now: i64) -> bool {
+    if !st.watchdog.enabled || !st.is_run_active() {
+        return false;
+    }
+    if st.power_seq_in_progress || st.awaiting_dimm_replacement || st.plan_paused {
+        return false;
+    }
+    let bp_state = st.boot_execution.get_str_or("state", "idle");
+    if matches!(
+        bp_state.as_str(),
+        "idle" | "completed" | "blocked" | "failed" | "stopped" | "paused" | "waiting_user"
+    ) {
+        return false;
+    }
+    // Exempt while `:2200` serial or dual-link is disconnected (governed by disconnect policy, not hang watchdog)
+    if st.observed_detail == "link_offline_waiting"
+        || st.link_offline_since_unix_ms > 0
+        || st.serial_offline_since_unix_ms > 0
+    {
+        return false;
+    }
+    if st.mt_report_sync_pending && now < st.mt_waiting_report_until_ms {
+        return false;
+    }
+    // Exempt when stopped at an interactive prompt in manual stage mode
+    if st.prompt_ready {
+        let prompt_stage = match st.prompt_kind.as_str() {
+            "uip" => {
+                if st.prompt_uip_stage.unwrap_or(1) > 1 {
+                    "uip2"
+                } else {
+                    "uip1"
+                }
+            }
+            "amt" => "amt",
+            "uefi" => "uefi",
+            _ => "",
+        };
+        if !prompt_stage.is_empty() {
+            let plan = normalize_boot_plan(&st.boot_plan);
+            let mode = plan
+                .get("stages")
+                .and_then(|s| s.get_str(prompt_stage))
+                .unwrap_or("manual");
+            if mode == "manual" {
+                return false;
+            }
+        }
+    }
+
+    let batch_unattended = st.task_batch.get_str_or("state", "idle") == "running"
+        && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
+    let batch_reboot = st
+        .task_batch
+        .get_bool("reboot_on_hang")
+        .unwrap_or(st.watchdog.reboot_on_hang);
+    let max_hangs = st
+        .task_batch
+        .get_i64("max_consecutive_hangs")
+        .map(|v| v.clamp(1, 20) as u32)
+        .unwrap_or(st.watchdog.max_consecutive_hangs);
+
+    // 1. Check total stage duration caps for MT and AMT (catches ANSI clock-redraw infinite loops)
+    if st.observed_phase == "mt"
+        && st.watchdog.mt_max_duration_ms > 0
+        && st.mt_started_unix_ms > 0
+    {
+        let mt_dur = now.saturating_sub(st.mt_started_unix_ms);
+        if mt_dur >= st.watchdog.mt_max_duration_ms {
+            let next_hangs = st.consecutive_hang_count.saturating_add(1);
+            let will_reboot = batch_unattended && batch_reboot && next_hangs < max_hangs;
+            st.consecutive_hang_count = next_hangs;
+            let msg = if !will_reboot && batch_unattended && batch_reboot && next_hangs >= max_hangs {
+                format!(
+                    "MT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (mt_duration_timeout);连续死机已达 {}/{} 次熔断上限,停止自动重启并保留现场",
+                    mt_dur as f64 / 1000.0,
+                    st.watchdog.mt_max_duration_ms as f64 / 1000.0,
+                    next_hangs,
+                    max_hangs
+                )
+            } else if will_reboot {
+                format!(
+                    "MT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (mt_duration_timeout);将执行第 {}/{} 次自动重启恢复",
+                    mt_dur as f64 / 1000.0,
+                    st.watchdog.mt_max_duration_ms as f64 / 1000.0,
+                    next_hangs,
+                    max_hangs
+                )
+            } else {
+                format!(
+                    "MT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (mt_duration_timeout);已冻结计时并保留死机现场未重启",
+                    mt_dur as f64 / 1000.0,
+                    st.watchdog.mt_max_duration_ms as f64 / 1000.0
+                )
+            };
+            st.latch_watchdog_or_link_fault(
+                "mt_duration_timeout",
+                "mt",
+                &msg,
+                !will_reboot,
+                mt_dur,
+                now,
+            );
+            return true;
+        }
+    }
+
+    if st.observed_phase == "amt"
+        && st.watchdog.amt_max_duration_ms > 0
+        && st.amt_started_unix_ms > 0
+    {
+        let amt_dur = now.saturating_sub(st.amt_started_unix_ms);
+        if amt_dur >= st.watchdog.amt_max_duration_ms {
+            let next_hangs = st.consecutive_hang_count.saturating_add(1);
+            let will_reboot = batch_unattended && batch_reboot && next_hangs < max_hangs;
+            st.consecutive_hang_count = next_hangs;
+            let msg = format!(
+                "AMT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (amt_duration_timeout);{}",
+                amt_dur as f64 / 1000.0,
+                st.watchdog.amt_max_duration_ms as f64 / 1000.0,
+                if will_reboot {
+                    format!("将执行第 {}/{} 次自动重启恢复", next_hangs, max_hangs)
+                } else {
+                    "已冻结计时并保留死机现场未重启".to_string()
+                }
+            );
+            st.latch_watchdog_or_link_fault(
+                "amt_duration_timeout",
+                "amt",
+                &msg,
+                !will_reboot,
+                amt_dur,
+                now,
+            );
+            return true;
+        }
+    }
+
+    // 2. Check stage-graded serial silence timeout (`last_rx_unix_ms` / stage transition anchor)
+    let anchor = st.last_activity_anchor_ms();
+    if anchor <= 0 || now <= anchor {
+        return false;
+    }
+    let silence_ms = now.saturating_sub(anchor);
+    let limit_ms = st.active_stage_silence_limit_ms();
+    if limit_ms > 0 && silence_ms >= limit_ms {
+        let stg = if st.observed_phase.is_empty() || st.observed_phase == "unknown" {
+            "boot".to_string()
+        } else {
+            st.observed_phase.clone()
+        };
+        let next_hangs = st.consecutive_hang_count.saturating_add(1);
+        let will_reboot = batch_unattended && batch_reboot && next_hangs < max_hangs;
+        st.consecutive_hang_count = next_hangs;
+        let msg = if !will_reboot && batch_unattended && batch_reboot && next_hangs >= max_hangs {
+            format!(
+                "阶段 {} 连续 {:.1}s 无串口输出 (阈值 {:.0}s),判定服务器死机卡死 (stage_hang_timeout);连续死机已达 {}/{} 次熔断阈值,停止自动重启并保留现场",
+                stg,
+                silence_ms as f64 / 1000.0,
+                limit_ms as f64 / 1000.0,
+                next_hangs,
+                max_hangs
+            )
+        } else if will_reboot {
+            format!(
+                "阶段 {} 连续 {:.1}s 无串口输出 (阈值 {:.0}s),判定服务器死机卡死 (stage_hang_timeout);将执行第 {}/{} 次自动重启恢复",
+                stg,
+                silence_ms as f64 / 1000.0,
+                limit_ms as f64 / 1000.0,
+                next_hangs,
+                max_hangs
+            )
+        } else {
+            format!(
+                "阶段 {} 连续 {:.1}s 无串口输出 (阈值 {:.0}s),判定服务器死机卡死 (stage_hang_timeout);已冻结计时并保持死机现场未重启",
+                stg,
+                silence_ms as f64 / 1000.0,
+                limit_ms as f64 / 1000.0
+            )
+        };
+        st.latch_watchdog_or_link_fault(
+            "stage_hang_timeout",
+            &stg,
+            &msg,
+            !will_reboot,
+            silence_ms,
+            now,
+        );
+        return true;
+    }
+    false
+}
+
 pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
     tick_async_script(st);
     if st.async_script.active || !st.tx_pacer.is_empty() {
@@ -1443,13 +1734,18 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
         "amt" => {
             let act = st.amt_settings.get_str_or("action", "run");
             if act == "skip" {
-                // Exit dual-CPU AMT strictly in CPU0 then CPU1 order
-                if cpu > 0
-                    && st.cpu_count > 1
-                    && !st
-                        .plan_done
-                        .contains(&format!("{}:amt:cpu0", st.boot_id))
-                {
+                // Exit dual-CPU AMT strictly in CPU0 then CPU1 order when CPU0 is active or within grace;
+                // never deadlock forever if CPU0 prompt was lost during a serial gap.
+                let cpu0_done = st.plan_done.contains(&format!("{}:amt:cpu0", st.boot_id));
+                let cpu0_active = st.active_amt_cpus.contains(&0)
+                    || st
+                        .amt_results
+                        .get(&0)
+                        .map(|r| r.status == "running")
+                        .unwrap_or(false);
+                let in_cpu0_grace =
+                    st.amt_started_unix_ms > 0 && now_ms().saturating_sub(st.amt_started_unix_ms) < 15_000;
+                if cpu > 0 && st.cpu_count > 1 && !cpu0_done && (cpu0_active || in_cpu0_grace) {
                     return;
                 }
                 let _ = write_station_paced(st, b"exit\r");
@@ -1528,13 +1824,17 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
             if (this_cpu_done || all_cpus_done)
                 && st.amt_settings.get_bool("exit_after").unwrap_or(true)
             {
-                // Enforce ordered CPU0 -> CPU1 AMT exit
-                if cpu > 0
-                    && st.cpu_count > 1
-                    && !st
-                        .plan_done
-                        .contains(&format!("{}:amt:cpu0", st.boot_id))
-                {
+                // Enforce ordered CPU0 -> CPU1 AMT exit without deadlocking if CPU0 prompt was missed
+                let cpu0_done = st.plan_done.contains(&format!("{}:amt:cpu0", st.boot_id));
+                let cpu0_active = st.active_amt_cpus.contains(&0)
+                    || st
+                        .amt_results
+                        .get(&0)
+                        .map(|r| r.status == "running")
+                        .unwrap_or(false);
+                let in_cpu0_grace =
+                    st.amt_started_unix_ms > 0 && now_ms().saturating_sub(st.amt_started_unix_ms) < 15_000;
+                if cpu > 0 && st.cpu_count > 1 && !cpu0_done && (cpu0_active || in_cpu0_grace) {
                     return;
                 }
                 let _ = write_station_paced(st, b"exit\r");
@@ -2184,12 +2484,21 @@ pub fn apply_profile_to_station(
     let mut bp = JsonVal::obj();
     bp.set("preset", JsonVal::Str("auto".to_string()));
     bp.set("stages", stages);
-    bp.set("run_rmt", JsonVal::Bool(run_rmt));
+    bp.set("run_rmt", JsonVal::Bool(eff_run_rmt));
     bp.set("run_amt", JsonVal::Bool(run_amt));
     bp.set("run_mt", JsonVal::Bool(run_mt));
     bp.set("mt_enabled", JsonVal::Bool(run_mt));
     bp.set("use_in_runs", JsonVal::Bool(true));
     st.boot_plan = bp;
+    if let Some(wd) = profile.get("watchdog") {
+        st.watchdog.apply_patch(wd);
+    }
+    if let Some(roh) = profile.get_bool("reboot_on_hang") {
+        st.watchdog.reboot_on_hang = roh;
+    }
+    if let Some(mch) = profile.get_i64("max_consecutive_hangs") {
+        st.watchdog.max_consecutive_hangs = mch.clamp(1, 20) as u32;
+    }
     st.single_run_profile = strip_private_keys_recursive(profile);
     save_station_settings(data_dir, st);
     Ok(())
@@ -2252,9 +2561,29 @@ pub fn submit_task_batch(
         .map(|s| s.to_string())
         .unwrap_or_else(|| format!("TB-{}-{}", st.station_id, now));
     let stop_on_fail = args.get_bool("stop_on_fail").unwrap_or(true);
+    let reboot_on_hang = args
+        .get_bool("reboot_on_hang")
+        .or_else(|| args.get("watchdog").and_then(|w| w.get_bool("reboot_on_hang")))
+        .unwrap_or(st.watchdog.reboot_on_hang);
+    let max_consecutive_hangs = args
+        .get_i64("max_consecutive_hangs")
+        .or_else(|| {
+            args.get("watchdog")
+                .and_then(|w| w.get_i64("max_consecutive_hangs"))
+        })
+        .map(|v| v.clamp(1, 20) as u32)
+        .unwrap_or(st.watchdog.max_consecutive_hangs);
+    if let Some(wd) = args.get("watchdog") {
+        st.watchdog.apply_patch(wd);
+    }
+    st.watchdog.reboot_on_hang = reboot_on_hang;
+    st.watchdog.max_consecutive_hangs = max_consecutive_hangs;
     let auto_start = args.get_bool("auto_start").unwrap_or(true);
     let continue_timer =
         args.get_bool("continue_timer") == Some(true) && st.run_started_unix_ms > 0;
+    if !continue_timer {
+        st.consecutive_hang_count = 0;
+    }
 
     let first_profile = &normalized_profiles[0];
     apply_profile_to_station(st, first_profile, contract, pxe_state, data_dir, pxe_tftp_dir)?;
@@ -2317,6 +2646,11 @@ pub fn submit_task_batch(
     tb.set("total_runs_completed", JsonVal::Num(0.0));
     tb.set("total_runs_planned", JsonVal::Num(total_planned as f64));
     tb.set("stop_on_fail", JsonVal::Bool(stop_on_fail));
+    tb.set("reboot_on_hang", JsonVal::Bool(reboot_on_hang));
+    tb.set(
+        "max_consecutive_hangs",
+        JsonVal::Num(max_consecutive_hangs as f64),
+    );
     tb.set("created_unix_ms", JsonVal::Str(now.to_string()));
     tb.set("updated_unix_ms", JsonVal::Str(now.to_string()));
     tb.set("profiles", JsonVal::Arr(normalized_profiles));
@@ -2359,6 +2693,25 @@ fn emit_complete_signal(
         JsonVal::Bool(st.awaiting_dimm_replacement),
     );
     sig.set("stage_completions", st.stage_completions_json());
+    if !st.last_fault_code.is_empty() {
+        sig.set("fault_code", JsonVal::Str(st.last_fault_code.clone()));
+        sig.set("fault_message", JsonVal::Str(st.last_fault_message.clone()));
+        sig.set("fault_stage", JsonVal::Str(st.last_fault_stage.clone()));
+        sig.set(
+            "hang_scene_preserved",
+            JsonVal::Bool(st.hang_scene_preserved),
+        );
+    }
+    sig.set("serial_gap_detected", JsonVal::Bool(st.serial_gap_detected));
+    sig.set("serial_gap_count", JsonVal::Num(st.serial_gap_count as f64));
+    sig.set(
+        "serial_gap_total_ms",
+        JsonVal::Num(st.serial_gap_total_ms as f64),
+    );
+    sig.set(
+        "consecutive_hang_count",
+        JsonVal::Num(st.consecutive_hang_count as f64),
+    );
     sig.set(
         "summary_path",
         JsonVal::Str(
@@ -2388,9 +2741,22 @@ pub fn step_task_batch(
     }
 
     let b_state = st.task_batch.get_str_or("state", "idle");
+    let is_hang_fault = matches!(
+        st.last_fault_code.as_str(),
+        "stage_hang_timeout" | "mt_duration_timeout" | "amt_duration_timeout"
+    );
+    let is_link_or_pwr_fault = matches!(
+        st.last_fault_code.as_str(),
+        "link_lost_timeout" | "reconnect_power_off"
+    );
+    if !is_hang_fault {
+        st.consecutive_hang_count = 0;
+    }
+
     if b_state != "running" {
         let now = now_ms();
         let has_any_err = st.awaiting_dimm_replacement
+            || !st.last_fault_code.is_empty()
             || st.stage_errors.values().any(|v| !v.is_empty());
         let verdict = if bp_state == "completed" && !has_any_err {
             "pass"
@@ -2454,9 +2820,11 @@ pub fn step_task_batch(
             st.log_debug(
                 "BATCH",
                 &format!(
-                    "SINGLE_RUN_DONE run_id={} verdict={} elapsed_ms={}",
+                    "SINGLE_RUN_DONE run_id={} verdict={} fault={} hang_preserved={} elapsed_ms={}",
                     run_id,
                     verdict,
+                    st.last_fault_code,
+                    st.hang_scene_preserved,
                     (ended_ms - started_ms).max(0)
                 ),
             );
@@ -2475,6 +2843,15 @@ pub fn step_task_batch(
         .max(0) as usize;
     let cur_rep = st.task_batch.get_i64("current_repeat").unwrap_or(1).max(1) as usize;
     let stop_on_fail = st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
+    let reboot_on_hang = st
+        .task_batch
+        .get_bool("reboot_on_hang")
+        .unwrap_or(st.watchdog.reboot_on_hang);
+    let max_hangs = st
+        .task_batch
+        .get_i64("max_consecutive_hangs")
+        .map(|v| v.clamp(1, 20) as u32)
+        .unwrap_or(st.watchdog.max_consecutive_hangs);
     let profiles = st.task_batch.get_arr("profiles").cloned().unwrap_or_default();
     if cur_p_idx >= profiles.len() {
         st.task_batch
@@ -2487,7 +2864,14 @@ pub fn step_task_batch(
     let p_name = cur_profile.get_str_or("name", &format!("Profile-{}", cur_p_idx + 1));
     let p_rep_total = cur_profile.get_i64("repeat").unwrap_or(1).max(1) as usize;
     let run_id = format!("{}-P{}-R{}", batch_id, cur_p_idx + 1, cur_rep);
-    let verdict = if bp_state == "completed" { "pass" } else { "fail" };
+    let has_any_err = st.awaiting_dimm_replacement
+        || !st.last_fault_code.is_empty()
+        || st.stage_errors.values().any(|v| !v.is_empty());
+    let verdict = if bp_state == "completed" && !has_any_err {
+        "pass"
+    } else {
+        "fail"
+    };
 
     let mut runs = st.task_batch.get_arr("runs").cloned().unwrap_or_default();
     let started_ms = runs
@@ -2518,6 +2902,16 @@ pub fn step_task_batch(
         last_run.set("ended_unix_ms", JsonVal::Str(now.to_string()));
         last_run.set("log_path", JsonVal::Str(raw_path));
         last_run.set("summary_path", JsonVal::Str(sum_path));
+        if !st.last_fault_code.is_empty() {
+            last_run.set("fault_code", JsonVal::Str(st.last_fault_code.clone()));
+            last_run.set(
+                "hang_scene_preserved",
+                JsonVal::Bool(st.hang_scene_preserved),
+            );
+        }
+        if st.serial_gap_detected {
+            last_run.set("serial_gap_detected", JsonVal::Bool(true));
+        }
     }
 
     st.task_history.push(summary_obj.clone());
@@ -2531,9 +2925,25 @@ pub fn step_task_batch(
     st.task_batch
         .set("updated_unix_ms", JsonVal::Str(now.to_string()));
 
-    if verdict == "fail" && stop_on_fail {
+    let halt_for_hang_policy =
+        is_hang_fault && (!reboot_on_hang || st.consecutive_hang_count >= max_hangs);
+    if verdict == "fail" && (stop_on_fail || is_link_or_pwr_fault || halt_for_hang_policy) {
+        let halt_reason = if is_hang_fault && reboot_on_hang && st.consecutive_hang_count >= max_hangs
+        {
+            st.last_fault_code = "consecutive_hang_limit_exceeded".to_string();
+            st.hang_scene_preserved = true;
+            "consecutive_hang_limit_exceeded".to_string()
+        } else if is_hang_fault && !reboot_on_hang {
+            st.hang_scene_preserved = true;
+            "hang_scene_preserved".to_string()
+        } else if is_link_or_pwr_fault {
+            st.last_fault_code.clone()
+        } else {
+            "stop_on_fail".to_string()
+        };
         st.task_batch.set("runs", JsonVal::Arr(runs));
         st.task_batch.set("state", JsonVal::Str("failed".to_string()));
+        st.task_batch.set("halt_reason", JsonVal::Str(halt_reason.clone()));
         st.task_status = "failed".to_string();
         st.awaiting_dimm_replacement = true;
         st.hot.awaiting_dimm_replacement = true;
@@ -2543,8 +2953,8 @@ pub fn step_task_batch(
         st.log_debug(
             "BATCH",
             &format!(
-                "BATCH_STOP_ON_FAIL batch_id={} run_id={} completed={}",
-                batch_id, run_id, completed_total
+                "BATCH_HALT batch_id={} run_id={} reason={} consecutive_hangs={}/{} completed={}",
+                batch_id, run_id, halt_reason, st.consecutive_hang_count, max_hangs, completed_total
             ),
         );
         st.restore_persistent_baseline("task_batch_failed");
@@ -2560,16 +2970,22 @@ pub fn step_task_batch(
 
     if next_p_idx >= profiles.len() {
         st.task_batch.set("runs", JsonVal::Arr(runs));
+        let final_state = if verdict == "fail" && is_hang_fault {
+            st.hang_scene_preserved = true;
+            "failed"
+        } else {
+            "completed"
+        };
         st.task_batch
-            .set("state", JsonVal::Str("completed".to_string()));
-        st.task_status = "completed".to_string();
+            .set("state", JsonVal::Str(final_state.to_string()));
+        st.task_status = final_state.to_string();
         st.freeze_run_timing(now);
         emit_complete_signal(st, &run_id, &batch_id, verdict, &summary_obj, true);
         st.log_debug(
             "BATCH",
             &format!(
-                "BATCH_COMPLETED batch_id={} last_run_id={} completed={}",
-                batch_id, run_id, completed_total
+                "BATCH_COMPLETED batch_id={} last_run_id={} state={} completed={}",
+                batch_id, run_id, final_state, completed_total
             ),
         );
         st.restore_persistent_baseline("task_batch_completed");

Разница между файлами не показана из-за своего большого размера
+ 36 - 0
sim/README.md


Разница между файлами не показана из-за своего большого размера
+ 1378 - 0
sim/hil_cluster/bmc_ssh_hil_sim.c


+ 451 - 0
sim/hil_cluster/cluster_harness.py

@@ -0,0 +1,451 @@
+#!/usr/bin/env python3
+"""
+cluster_harness.py — Full-Stack HIL Simulation Stack Manager (Tiers 2, 4, 5)
+
+Launches and orchestrates:
+  1. `build/sim/bmc_ssh_hil_sim` (C RMCP+ UDP :623 + SSHv2 TCP :2200 for S1..S4)
+  2. `sim/hil_cluster/dut_and_hood_sim.py` (4x Dual-Socket GNR DUTs + 8x `/dev/pts/*` 6400 Hoods)
+  3. `build/native/stl_native_server` (Unmodified production Rust+C+Zig+ASM+re2c server)
+  4. Async WebSocket RPC clients for `/ws` (full admin view) and `/ws?view=qt-clean` (Qt clean view)
+"""
+
+import asyncio
+import base64
+import contextlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import time
+from typing import Any, Dict, List, Optional
+import uuid
+
+import aiohttp
+
+ROOT_DIR = Path(__file__).resolve().parents[2]
+BMC_SIM_BIN = ROOT_DIR / "build" / "sim" / "bmc_ssh_hil_sim"
+DUT_HOOD_SCRIPT = ROOT_DIR / "sim" / "hil_cluster" / "dut_and_hood_sim.py"
+STL_SERVER_BIN = ROOT_DIR / "build" / "native" / "stl_native_server"
+CONTRACTS_PATH = ROOT_DIR / "contracts" / "firmware-vd012.json"
+WEB_DIR = ROOT_DIR / "web"
+
+DEFAULT_STATION_IPS = ["127.0.2.166", "127.0.2.165", "127.0.2.167", "127.0.2.168"]
+
+
+class WsRpcClient:
+    """Async RFC 6455 JSON-RPC v1 client supporting push event capture (`state`, `task_complete`, `bios_uart`)."""
+
+    def __init__(self, session: aiohttp.ClientSession, url: str, headers: Optional[Dict[str, str]] = None):
+        self.session = session
+        self.url = url
+        self.headers = headers or {}
+        self.ws: Optional[aiohttp.ClientWebSocketResponse] = None
+        self.reader_task: Optional[asyncio.Task] = None
+        self.pending: Dict[str, asyncio.Future] = {}
+        self.seq = 0
+        self.latest_state: Optional[Dict[str, Any]] = None
+        self.task_completes: List[Dict[str, Any]] = []
+        self.state_events: List[Dict[str, Any]] = []
+
+    async def connect(self) -> None:
+        self.ws = await self.session.ws_connect(self.url, heartbeat=20, headers=self.headers)
+        self.reader_task = asyncio.create_task(self._read_loop())
+
+    async def close(self) -> None:
+        if self.ws is not None:
+            with contextlib.suppress(Exception):
+                await self.ws.close()
+        if self.reader_task is not None:
+            self.reader_task.cancel()
+            with contextlib.suppress(asyncio.CancelledError, Exception):
+                await self.reader_task
+
+    async def _read_loop(self) -> None:
+        assert self.ws is not None
+        try:
+            async for msg in self.ws:
+                if msg.type != aiohttp.WSMsgType.TEXT:
+                    continue
+                data = json.loads(msg.data)
+                if not isinstance(data, dict):
+                    continue
+                req_id = data.get("id")
+                if req_id and req_id in self.pending:
+                    fut = self.pending.pop(req_id)
+                    if not fut.done():
+                        fut.set_result(data)
+                    continue
+                ev = data.get("event")
+                res = data.get("result")
+                if ev == "state" and isinstance(res, dict):
+                    self.latest_state = res
+                    self.state_events.append(res)
+                    if len(self.state_events) > 300:
+                        self.state_events = self.state_events[-300:]
+                elif ev == "task_complete" and isinstance(res, dict):
+                    self.task_completes.append(res)
+        except Exception as exc:
+            for fut in self.pending.values():
+                if not fut.done():
+                    fut.set_exception(exc)
+
+    async def call(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 20.0) -> Any:
+        assert self.ws is not None
+        self.seq += 1
+        req_id = f"hil-{self.seq}-{uuid.uuid4().hex[:6]}"
+        fut = asyncio.get_running_loop().create_future()
+        self.pending[req_id] = fut
+        await self.ws.send_json({"v": 1, "id": req_id, "method": method, "params": params or {}})
+        try:
+            resp = await asyncio.wait_for(fut, timeout=timeout)
+        finally:
+            self.pending.pop(req_id, None)
+        if not resp.get("ok"):
+            err = resp.get("error") or {}
+            raise RuntimeError(f"RPC {method} failed: {err}")
+        return resp.get("result")
+
+
+class HilClusterStack:
+    def __init__(
+        self,
+        *,
+        web_port: int = 18980,
+        tftp_port: int = 19069,
+        bmc_ctrl_port: int = 19199,
+        hil_http_port: int = 19198,
+        uart_base: int = 19200,
+        web_password: str = "disabled",
+        speed_scale: float = 0.25,
+        station_ips: Optional[List[str]] = None,
+    ):
+        self.web_port = web_port
+        self.tftp_port = tftp_port
+        self.bmc_ctrl_port = bmc_ctrl_port
+        self.hil_http_port = hil_http_port
+        self.uart_base = uart_base
+        self.web_password = web_password
+        self.speed_scale = speed_scale
+        self.station_ips = station_ips or list(DEFAULT_STATION_IPS)
+
+        self.tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_stl_hil_"))
+        self.data_dir = self.tmp_dir / "data"
+        self.config_path = self.tmp_dir / "station-hil.json"
+        self.manifest_path = self.tmp_dir / "hil_manifest.json"
+
+        self.bmc_proc: Optional[subprocess.Popen] = None
+        self.dut_proc: Optional[subprocess.Popen] = None
+        self.server_proc: Optional[subprocess.Popen] = None
+
+        self.backend_hood_pts: List[str] = []
+        self.qt_hood_pts: List[str] = []
+
+        self.http_session: Optional[aiohttp.ClientSession] = None
+        self.admin_ws: Optional[WsRpcClient] = None
+        self.qt_ws: Optional[WsRpcClient] = None
+
+    def _clean_env(self) -> Dict[str, str]:
+        env = dict(os.environ)
+        for k in (
+            "LD_LIBRARY_PATH",
+            "QT_PLUGIN_PATH",
+            "QT_QPA_PLATFORM_PLUGIN_PATH",
+            "QT_QPA_PLATFORM",
+            "http_proxy",
+            "https_proxy",
+            "HTTP_PROXY",
+            "HTTPS_PROXY",
+            "all_proxy",
+            "ALL_PROXY",
+        ):
+            env.pop(k, None)
+        return env
+
+    def _write_config(self) -> None:
+        self.data_dir.mkdir(parents=True, exist_ok=True)
+        pxe_dir = self.data_dir / "pxe_tftp"
+        pxe_dir.mkdir(parents=True, exist_ok=True)
+        (pxe_dir / "118.efi").write_bytes(b"MZ\x90\x00STL_118_EFI_SIM_STUB")
+
+        stations = []
+        for i, ip in enumerate(self.station_ips):
+            sid = f"S{i + 1}"
+            stations.append({
+                "station_id": sid,
+                "frontend_index": i,
+                "name": f"仿真工位 00{i + 1} ({ip})",
+                "mode": "hardware",
+                "cpu_count": 2,
+                "channels_per_cpu": 12,
+                "target_min_c": 0.0,
+                "target_max_c": 100.0,
+                "supply_mode": "manual",
+                "bmc": {
+                    "enabled": True,
+                    "host": ip,
+                    "user": "ADMIN",
+                    "username": "ADMIN",
+                    "password": "Admin123@pl",
+                    "cipher_suite": 17,
+                    "timeout_s": 5,
+                    "console_transport": "ssh_console",
+                    "ssh_console_port": 2200,
+                },
+                "console": {
+                    "enabled": True,
+                    "transport": "ssh_console",
+                    "host": ip,
+                    "port": 2200,
+                    "user": "ADMIN",
+                    "write_chunk_bytes": 64,
+                    "write_gap_ms": 2.0,
+                },
+            })
+
+        cfg = {
+            "mode": "hardware",
+            "data_dir": str(self.data_dir),
+            "telemetry_interval_s": 1.0,
+            "idle_poll_interval_s": 1,
+            "stations": stations,
+        }
+        self.config_path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
+
+    async def __aenter__(self) -> "HilClusterStack":
+        await self.start()
+        return self
+
+    async def __aexit__(self, *exc: Any) -> None:
+        await self.stop()
+
+    async def start(self) -> None:
+        self._write_config()
+        env = self._clean_env()
+
+        # 1. Start C BMC RMCP+ & SSHv2 :2200 Simulator
+        self.bmc_proc = subprocess.Popen(
+            [
+                str(BMC_SIM_BIN),
+                "--ctrl-port", str(self.bmc_ctrl_port),
+                "--uart-base", str(self.uart_base),
+                "--ipmi-port", "623",
+                "--ssh-port", "2200",
+                "--probe22-port", "0",
+                *self.station_ips,
+            ],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            text=True,
+            env=env,
+        )
+        await self._wait_proc_ready_line(self.bmc_proc, "READY", timeout_s=8.0)
+
+        # 2. Start Python DUT State Machine + 8x `/dev/pts/*` 6400 Hood Simulator
+        py_bin = "/opt/prod2u/venv/bin/python3" if os.path.exists("/opt/prod2u/venv/bin/python3") else "python3"
+        self.dut_proc = subprocess.Popen(
+            [
+                py_bin,
+                str(DUT_HOOD_SCRIPT),
+                "--http-port", str(self.hil_http_port),
+                "--bmc-ctrl-port", str(self.bmc_ctrl_port),
+                "--uart-base", str(self.uart_base),
+                "--num-stations", str(len(self.station_ips)),
+                "--tftp-host", "127.0.0.1",
+                "--tftp-port", str(self.tftp_port),
+                "--speed-scale", str(self.speed_scale),
+                "--manifest-out", str(self.manifest_path),
+            ],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            text=True,
+            env=env,
+        )
+        await self._wait_proc_ready_line(self.dut_proc, "READY", timeout_s=8.0)
+        manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
+        self.backend_hood_pts = manifest["backend_hood_pts"]
+        self.qt_hood_pts = manifest["qt_hood_pts"]
+
+        # 3. Start Production `stl_native_server`
+        self.server_proc = subprocess.Popen(
+            [
+                str(STL_SERVER_BIN),
+                "--config", str(self.config_path),
+                "--data-dir", str(self.data_dir),
+                "--web-listen", f"127.0.0.1:{self.web_port}",
+                "--tftp-listen", f"127.0.0.1:{self.tftp_port}",
+                "--web-dir", str(WEB_DIR),
+                "--contracts", str(CONTRACTS_PATH),
+                "--web-password", self.web_password,
+            ],
+            cwd=str(ROOT_DIR),
+            stdout=subprocess.DEVNULL,
+            stderr=subprocess.PIPE,
+            text=True,
+            env=env,
+        )
+
+        self.http_session = aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True))
+        try:
+            await self._wait_http_up(f"http://127.0.0.1:{self.web_port}/", timeout_s=10.0)
+
+            headers: Dict[str, str] = {}
+            if self.web_password and self.web_password.lower() not in ("disabled", "none", "off"):
+                b64 = base64.b64encode(f"admin:{self.web_password}".encode("utf-8")).decode("ascii")
+                headers["Authorization"] = f"Basic {b64}"
+                async with self.http_session.post(
+                    f"http://127.0.0.1:{self.web_port}/api/auth/login",
+                    json={"password": self.web_password},
+                ) as resp:
+                    assert resp.status == 200, f"Login failed: {resp.status}"
+
+            self.admin_ws = WsRpcClient(self.http_session, f"ws://127.0.0.1:{self.web_port}/ws", headers=headers)
+            await self.admin_ws.connect()
+            self.qt_ws = WsRpcClient(self.http_session, f"ws://127.0.0.1:{self.web_port}/ws?view=qt-clean")
+            await self.qt_ws.connect()
+        except Exception:
+            await self.stop()
+            raise
+
+    async def _wait_proc_ready_line(self, proc: subprocess.Popen, prefix: str, timeout_s: float) -> str:
+        deadline = time.monotonic() + timeout_s
+        assert proc.stdout is not None
+        while time.monotonic() < deadline:
+            if proc.poll() is not None:
+                err = proc.stderr.read() if proc.stderr else ""
+                raise RuntimeError(f"Process exited early ({proc.returncode}): {err}")
+            line = await asyncio.to_thread(proc.stdout.readline)
+            if line and prefix in line:
+                return line.strip()
+            await asyncio.sleep(0.05)
+        raise TimeoutError(f"Timed out waiting for {prefix}")
+
+    async def _wait_http_up(self, url: str, timeout_s: float) -> None:
+        assert self.http_session is not None
+        deadline = time.monotonic() + timeout_s
+        while time.monotonic() < deadline:
+            try:
+                async with self.http_session.get(url, timeout=aiohttp.ClientTimeout(total=1.0)) as r:
+                    if r.status in (200, 401):
+                        return
+            except Exception:
+                pass
+            await asyncio.sleep(0.1)
+        raise TimeoutError(f"Server did not listen at {url}")
+
+    async def stop(self) -> None:
+        for ws in (self.admin_ws, self.qt_ws):
+            if ws is not None:
+                await ws.close()
+        if self.http_session is not None:
+            await self.http_session.close()
+        for proc in (self.server_proc, self.dut_proc, self.bmc_proc):
+            if proc is not None and proc.poll() is None:
+                with contextlib.suppress(Exception):
+                    proc.terminate()
+                    proc.wait(timeout=3.0)
+                if proc.poll() is None:
+                    with contextlib.suppress(Exception):
+                        proc.kill()
+        with contextlib.suppress(Exception):
+            shutil.rmtree(self.tmp_dir, ignore_errors=True)
+
+    # ---- HIL Fault-Injection & Inspection Helpers ----
+
+    async def hil_status(self) -> Dict[str, Any]:
+        assert self.http_session is not None
+        async with self.http_session.get(f"http://127.0.0.1:{self.hil_http_port}/api/status") as r:
+            return await r.json()
+
+    async def set_link(self, idx: int, *, bmc_up: bool, serial_up: bool) -> Dict[str, Any]:
+        assert self.http_session is not None
+        async with self.http_session.post(
+            f"http://127.0.0.1:{self.hil_http_port}/api/bmc/set_link",
+            json={"idx": idx, "bmc_up": bmc_up, "serial_up": serial_up},
+        ) as r:
+            return await r.json()
+
+    async def set_power(self, idx: int, *, power_on: bool) -> Dict[str, Any]:
+        assert self.http_session is not None
+        async with self.http_session.post(
+            f"http://127.0.0.1:{self.hil_http_port}/api/bmc/set_power",
+            json={"idx": idx, "power_on": power_on},
+        ) as r:
+            return await r.json()
+
+    async def configure_dut(self, idx: int, **kwargs: Any) -> Dict[str, Any]:
+        assert self.http_session is not None
+        payload = {"idx": idx, **kwargs}
+        async with self.http_session.post(
+            f"http://127.0.0.1:{self.hil_http_port}/api/dut/configure",
+            json=payload,
+        ) as r:
+            return await r.json()
+
+    async def trigger_dut_boot(self, idx: int, reason: str = "test_boot") -> Dict[str, Any]:
+        assert self.http_session is not None
+        async with self.http_session.post(
+            f"http://127.0.0.1:{self.hil_http_port}/api/dut/trigger_boot",
+            json={"idx": idx, "reason": reason},
+        ) as r:
+            return await r.json()
+
+    async def clear_hood_history(self, idx: Optional[int] = None) -> None:
+        assert self.http_session is not None
+        async with self.http_session.post(
+            f"http://127.0.0.1:{self.hil_http_port}/api/hood/clear_history",
+            json={"idx": idx},
+        ) as r:
+            await r.json()
+
+    async def connect_and_heat_backend_hood(self, station_id: str, idx: int, target_c: int = 70) -> None:
+        """Bind `stl_native_server` ThermalMcuHub for `station_id` to `/dev/pts/*` hood & start heating."""
+        assert self.admin_ws is not None
+        pts = self.backend_hood_pts[idx]
+        await self.admin_ws.call(
+            "ThermalAction",
+            {
+                "station_id": station_id,
+                "action": "connect",
+                "mode": "serial",
+                "serial_path": pts,
+                "serial_baud": 115200,
+            },
+        )
+        # Wait up to 3s for 0xF0 heartbeat so ThermalMcuHub marks MCU online
+        deadline = time.monotonic() + 3.5
+        while time.monotonic() < deadline:
+            snap = await self.admin_ws.call("GetThermalConsole", {"station_id": station_id})
+            if (snap.get("mcu") or {}).get("online"):
+                break
+            await asyncio.sleep(0.2)
+        await self.admin_ws.call(
+            "ThermalAction",
+            {"station_id": station_id, "action": "set_temp", "target_c": target_c},
+        )
+
+    async def enqueue_cmd(self, station_id: str, method: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+        assert self.admin_ws is not None
+        item = await self.admin_ws.call(
+            "EnqueueCommand",
+            {
+                "command_id": f"hil-cmd-{uuid.uuid4().hex[:10]}",
+                "station_id": station_id,
+                "method": method,
+                "arguments": arguments or {},
+            },
+        )
+        if item.get("state") == "failed":
+            raise RuntimeError(f"EnqueueCommand {method} on {station_id} failed: {item}")
+        return item
+
+    async def wait_station_online(self, station_id: str, timeout_s: float = 12.0) -> Dict[str, Any]:
+        assert self.admin_ws is not None
+        deadline = time.monotonic() + timeout_s
+        while time.monotonic() < deadline:
+            st = await self.admin_ws.call("GetStation", {"station_id": station_id})
+            if st.get("bmc_state") == "online" and st.get("console_online") is True:
+                return st
+            await asyncio.sleep(0.25)
+        raise TimeoutError(f"Station {station_id} did not bring BMC + :2200 online within {timeout_s}s")

Разница между файлами не показана из-за своего большого размера
+ 1023 - 0
sim/hil_cluster/dut_and_hood_sim.py


+ 134 - 0
sim/hil_cluster/smoke_test_bmc_ssh.c

@@ -0,0 +1,134 @@
+/*
+ * smoke_test_bmc_ssh.c — Direct C kernel verification against bmc_ssh_hil_sim
+ *
+ * Tests `libstl_kernels.a` (`c_ipmi_open` Cipher Suite 17, `c_ipmi_chassis_status`,
+ * `c_ipmi_chassis_control`, `c_ipmi_sdr_temp_list`, `c_pty_spawn_ssh_console`)
+ * directly against `bmc_ssh_hil_sim` over real loopback sockets.
+ */
+
+#define _GNU_SOURCE
+#include "../../native/stl_accel/stl_accel.h"
+
+#include <arpa/inet.h>
+#include <assert.h>
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+int main(int argc, char **argv) {
+    const char *host = (argc > 1) ? argv[1] : "127.0.2.166";
+    int uart_port    = (argc > 2) ? atoi(argv[2]) : 19200;
+
+    printf("[1/5] Opening IPMI v2.0 RMCP+ Cipher Suite 17 session to %s:623...\n", host);
+    int h = c_ipmi_open(host, "root", "Admin123@pl", 17, 2500);
+    if (h <= 0) {
+        fprintf(stderr, "FAIL: c_ipmi_open returned %d\n", h);
+        return 1;
+    }
+    printf("      OK handle=%d\n", h);
+
+    printf("[2/5] Querying Get Chassis Status...\n");
+    int pwr_on = -1;
+    char sbuf[512];
+    if (c_ipmi_chassis_status(h, &pwr_on, sbuf, sizeof(sbuf)) != 0 || pwr_on != 1) {
+        fprintf(stderr, "FAIL: c_ipmi_chassis_status pwr_on=%d buf=%s\n", pwr_on, sbuf);
+        return 2;
+    }
+    printf("      OK power_on=%d\n", pwr_on);
+
+    printf("[3/5] Reading 24-DIMM Full SDR Repository & Temperature Sensors...\n");
+    char sdr_buf[16384];
+    size_t sdr_len = 0;
+    if (c_ipmi_sdr_temp_list(h, sdr_buf, sizeof(sdr_buf), &sdr_len) != 0 || sdr_len < 100) {
+        fprintf(stderr, "FAIL: c_ipmi_sdr_temp_list len=%zu buf=%s\n", sdr_len, sdr_buf);
+        return 3;
+    }
+    if (!strstr(sdr_buf, "CPU0_DIMM_A0 |") || !strstr(sdr_buf, "CPU1_DIMM_L0 |") ||
+        !strstr(sdr_buf, "degrees C | ok")) {
+        fprintf(stderr, "FAIL: unexpected SDR output:\n%s\n", sdr_buf);
+        return 4;
+    }
+    printf("      OK sdr_len=%zu (CPU0_DIMM_A0 .. CPU1_DIMM_L0 verified)\n", sdr_len);
+
+    printf("[4/5] Connecting UART bridge & spawning SSHv2 :2200 console...\n");
+    int ufd = socket(AF_INET, SOCK_STREAM, 0);
+    struct sockaddr_in ua;
+    memset(&ua, 0, sizeof(ua));
+    ua.sin_family = AF_INET;
+    ua.sin_port   = htons((uint16_t)uart_port);
+    inet_pton(AF_INET, "127.0.0.1", &ua.sin_addr);
+    if (connect(ufd, (struct sockaddr *)&ua, sizeof(ua)) != 0) {
+        perror("connect uart bridge");
+        return 5;
+    }
+
+    int master_fd = -1, child_pid = 0;
+    if (c_pty_spawn_ssh_console(host, 2200, "root", "Admin123@pl", "/dev/null", &master_fd, &child_pid) != 0) {
+        fprintf(stderr, "FAIL: c_pty_spawn_ssh_console failed\n");
+        return 6;
+    }
+
+    const char *bios_banner = "[0][Hovsee]Please input your command:";
+    (void)send(ufd, bios_banner, strlen(bios_banner), 0);
+
+    uint8_t rx[512];
+    ssize_t got = 0;
+    for (int tries = 0; tries < 50 && got == 0; tries++) {
+        usleep(20000);
+        ssize_t n = c_pty_read_nonblock(master_fd, rx, sizeof(rx) - 1);
+        if (n > 0) {
+            rx[n] = '\0';
+            got = n;
+        }
+    }
+    if (got <= 0 || !strstr((char *)rx, "Hovsee")) {
+        fprintf(stderr, "FAIL: did not receive BIOS UART banner over SSH :2200 (got=%zd)\n", got);
+        return 7;
+    }
+    printf("      OK SSH :2200 RX='%s'\n", (char *)rx);
+
+    const char *cmd_tx = "ict -all\r";
+    (void)c_pty_write_bytes(master_fd, (const uint8_t *)cmd_tx, strlen(cmd_tx));
+    char urx[256];
+    memset(urx, 0, sizeof(urx));
+    for (int tries = 0; tries < 50; tries++) {
+        usleep(20000);
+        ssize_t n = recv(ufd, urx, sizeof(urx) - 1, MSG_DONTWAIT);
+        if (n > 0) break;
+    }
+    if (!strstr(urx, "ict -all")) {
+        fprintf(stderr, "FAIL: UART bridge did not receive TX command '%s'\n", urx);
+        return 8;
+    }
+    printf("      OK SSH :2200 TX->UART='%s'\n", urx);
+
+    printf("[5/5] Verifying IPMI Chassis Power Off -> UART event & Chassis Status...\n");
+    if (c_ipmi_chassis_control(h, 0 /* power down */) != 0) {
+        fprintf(stderr, "FAIL: c_ipmi_chassis_control(off) failed\n");
+        return 9;
+    }
+    if (c_ipmi_chassis_status(h, &pwr_on, sbuf, sizeof(sbuf)) != 0 || pwr_on != 0) {
+        fprintf(stderr, "FAIL: expected power_on=0 after off, got %d\n", pwr_on);
+        return 10;
+    }
+    memset(urx, 0, sizeof(urx));
+    for (int tries = 0; tries < 30; tries++) {
+        usleep(10000);
+        ssize_t n = recv(ufd, urx, sizeof(urx) - 1, MSG_DONTWAIT);
+        if (n > 0) break;
+    }
+    if (!strstr(urx, "PWR:OFF")) {
+        fprintf(stderr, "FAIL: expected PWR:OFF event on UART bridge, got '%s'\n", urx);
+        return 11;
+    }
+    (void)c_ipmi_chassis_control(h, 1 /* power up */);
+
+    c_pty_close(master_fd, child_pid);
+    c_ipmi_close(h);
+    close(ufd);
+    printf("ALL 5 HIL KERNEL SMOKE CHECKS PASSED!\n");
+    return 0;
+}

+ 553 - 0
sim/hil_cluster/test_tier2_hil_e2e.py

@@ -0,0 +1,553 @@
+#!/usr/bin/env python3
+"""
+test_tier2_hil_e2e.py — Tier 2 Multi-Station Hardware-in-the-Loop (HIL) Full-Stack Verification
+
+Executes 8 end-to-end real-process scenarios against unmodified `build/native/stl_native_server`
+wired over real IPMI v2.0 RMCP+ (`:623`), SSHv2 (`:2200`), UDP TFTP (`:19069`), and `/dev/pts/*`
+6400 High-Temperature Hood controllers.
+"""
+
+import asyncio
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+from typing import Any, Callable, Dict
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from cluster_harness import HilClusterStack, ROOT_DIR  # noqa: E402
+
+
+async def wait_until(
+    pred: Callable[[], Any],
+    timeout_s: float = 25.0,
+    interval_s: float = 0.2,
+    desc: str = "condition",
+) -> Any:
+    deadline = time.monotonic() + timeout_s
+    last_val = None
+    while time.monotonic() < deadline:
+        res = pred()
+        if asyncio.iscoroutine(res):
+            res = await res
+        last_val = res
+        if res:
+            return res
+        await asyncio.sleep(interval_s)
+    raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}")
+
+
+def auto_all_stages_plan(mt_enabled: bool = True, run_rmt: bool = True, run_amt: bool = True) -> Dict[str, Any]:
+    return {
+        "preset": "auto",
+        "mt_enabled": mt_enabled,
+        "run_rmt": run_rmt,
+        "stages": {
+            "uip1": "auto",
+            "amt": "auto",
+            "uip2": "auto",
+            "uefi": "auto",
+        },
+        "amt_action": "run" if run_amt else "skip",
+    }
+
+
+async def configure_station_auto(
+    stack: HilClusterStack,
+    station_id: str,
+    *,
+    mt_enabled: bool = True,
+    run_rmt: bool = True,
+    run_amt: bool = True,
+    watchdog: Dict[str, Any] | None = None,
+) -> None:
+    await stack.enqueue_cmd(
+        station_id,
+        "SaveBootPlan",
+        {
+            "plan": auto_all_stages_plan(mt_enabled=mt_enabled, run_rmt=run_rmt, run_amt=run_amt),
+            **({"watchdog": watchdog} if watchdog else {}),
+        },
+    )
+    if not run_amt:
+        await stack.enqueue_cmd(
+            station_id,
+            "SaveAmtSettings",
+            {"settings": {"action": "skip", "exit_after": True}},
+        )
+    else:
+        await stack.enqueue_cmd(
+            station_id,
+            "SaveAmtSettings",
+            {"settings": {"action": "run", "test_command": "amemdiag 1", "exit_after": True}},
+        )
+    if watchdog:
+        await stack.enqueue_cmd(station_id, "ConfigureWatchdog", {"watchdog": watchdog})
+
+
+async def run_tier2_suite() -> Dict[str, Any]:
+    results = []
+    t_suite0 = time.monotonic()
+
+    async with HilClusterStack(
+        web_port=18980,
+        tftp_port=19069,
+        bmc_ctrl_port=19199,
+        hil_http_port=19198,
+        uart_base=19200,
+        web_password="disabled",
+        speed_scale=0.18,
+    ) as stack:
+        assert stack.admin_ws is not None
+        assert stack.qt_ws is not None
+
+        print("[Tier2] Waiting for all 4 HIL stations (RMCP+ :623 & SSH :2200) to come online...", flush=True)
+        for sid in ("S1", "S2", "S3", "S4"):
+            await stack.wait_station_online(sid, timeout_s=15.0)
+
+        # ====================================================================
+        # Scenario 1: Full 7-Stage Automated PASS + 24-ch SDR Temps + TFTP HTML
+        # ====================================================================
+        print("[Tier2][1/8] Running full 7-stage automated PASS + 24-DIMM SDR + TFTP HTML report on S1...", flush=True)
+        await stack.connect_and_heat_backend_hood("S1", 0, target_c=70)
+        await configure_station_auto(
+            stack,
+            "S1",
+            mt_enabled=True,
+            watchdog={"dense_stage_silence_timeout_ms": 15000, "amt_silence_timeout_ms": 15000, "mt_silence_timeout_ms": 15000},
+        )
+        await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"})
+
+        async def _s1_done():
+            st = await stack.admin_ws.call("GetStation", {"station_id": "S1"})
+            return st if st.get("task_status") in ("completed", "failed") else None
+
+        st_s1 = await wait_until(_s1_done, timeout_s=35.0, desc="S1 full 7-stage completion")
+        assert st_s1["task_status"] == "completed", f"Expected S1 completed, got {st_s1}"
+        assert st_s1["verdict"] == "pass", f"Expected S1 pass, got {st_s1}"
+        comps = st_s1.get("stage_completions") or {}
+        for k in ("ict_stage1_complete", "training_complete", "rmt_complete", "amt_complete", "ict_stage2_complete", "uefi_complete", "mt_pass_complete"):
+            assert comps.get(k) is True, f"Missing stage completion {k} in {comps}"
+
+        # Verify 24-ch BMC SDR temperatures were read over RMCP+ and TFTP HTML report ingested
+        ctrl_s1 = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
+        dimms_s1 = ctrl_s1.get("dimms") or []
+        assert len(dimms_s1) == 24, f"Expected 24 DIMMs, got {len(dimms_s1)}"
+        valid_temps = [
+            (d.get("temperature") or {}).get("value_c")
+            for d in dimms_s1
+            if isinstance((d.get("temperature") or {}).get("value_c"), (int, float))
+        ]
+        assert len(valid_temps) == 24, f"Expected 24 valid SDR/RMT DIMM temps, got {len(valid_temps)}"
+        pxe_rpts = ((ctrl_s1.get("pxe_control") or {}).get("recent_reports")) or []
+        assert len(pxe_rpts) >= 1, "Expected TFTP WRQ MemTest86 HTML report in recent_reports"
+        results.append({"scenario": "1_full_7stage_pass_sdr_tftp", "status": "PASS"})
+        print("      -> PASS", flush=True)
+
+        # ====================================================================
+        # Scenario 2: Single-Link Drop (<no reset>) + >5s Dual-Disconnect (`link_offline_waiting`)
+        #             + Reconnect Silent Prompt `\r` Re-Probe + `serial_gap_detected`
+        # ====================================================================
+        print("[Tier2][2/8] Testing single-link drop + >5s dual-disconnect + reconnect `\\r` prompt probe on S2...", flush=True)
+        await stack.configure_dut(1, speed_scale=0.18)
+        # 2a. Pause S2 deterministically at ICT Stage 2 (`uip2: manual`) so active run cannot race to completion
+        await stack.enqueue_cmd(
+            "S2",
+            "SaveBootPlan",
+            {
+                "plan": {
+                    "preset": "custom",
+                    "mt_enabled": True,
+                    "run_rmt": True,
+                    "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"},
+                },
+                "watchdog": {"link_lost_timeout_ms": 30000, "dense_stage_silence_timeout_ms": 25000},
+            },
+        )
+        await stack.enqueue_cmd(
+            "S2",
+            "SaveAmtSettings",
+            {"settings": {"action": "run", "test_command": "amemdiag 1", "exit_after": True}},
+        )
+        await stack.enqueue_cmd("S2", "ControlBootPlan", {"action": "restart"})
+
+        async def _s2_at_uip2_manual():
+            st = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
+            return st if (st.get("stage_completions") or {}).get("amt_complete") is True and st.get("task_status") == "running" else None
+
+        await wait_until(_s2_at_uip2_manual, timeout_s=25.0, desc="S2 active run waiting at manual uip2")
+
+        # Drop ONLY BMC (`bmc_up=False, serial_up=True`) until `bmc_state == 'offline'`, hold 2s -> NO reset & NO link_offline_waiting!
+        await stack.set_link(1, bmc_up=False, serial_up=True)
+        await wait_until(
+            lambda: _check_bmc_state(stack, "S2", "offline"),
+            timeout_s=20.0,
+            desc="S2 single-link BMC offline",
+        )
+        await asyncio.sleep(2.0)
+        st_single = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
+        assert st_single.get("observed_detail") != "link_offline_waiting", (
+            f"Single-link BMC drop must not trigger link_offline_waiting: {st_single}"
+        )
+        assert st_single.get("task_status") == "running", f"Expected S2 still running, got {st_single}"
+        await stack.set_link(1, bmc_up=True, serial_up=True)
+        await stack.wait_station_online("S2", timeout_s=20.0)
+
+        # 2b. Switch S2 to full auto, start active run, then drop BOTH BMC + :2200 (`bmc_up=False, serial_up=False`).
+        #     While disconnected, reboot DUT so ICT Stage 1 prompt is emitted into the void and missed!
+        await configure_station_auto(
+            stack,
+            "S2",
+            mt_enabled=True,
+            watchdog={
+                "link_lost_timeout_ms": 30000,
+                "dense_stage_silence_timeout_ms": 25000,
+                "amt_silence_timeout_ms": 25000,
+                "mt_silence_timeout_ms": 25000,
+                "reconnect_prompt_probe_delay_ms": 800,
+            },
+        )
+        await stack.enqueue_cmd("S2", "ControlBootPlan", {"action": "start"})
+        await stack.set_link(1, bmc_up=False, serial_up=False)
+        await asyncio.sleep(0.5)
+        await stack.trigger_dut_boot(1, reason="missed_prompt_during_outage")
+
+        async def _s2_link_waiting():
+            st = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
+            return st if st.get("observed_detail") == "link_offline_waiting" else None
+
+        st_wait = await wait_until(_s2_link_waiting, timeout_s=35.0, desc="S2 link_offline_waiting (>5s dual drop)")
+        assert st_wait["task_status"] == "running", "Active test must NOT clear or fail during >5s grace window"
+
+        # Restore BMC + :2200! `stl_native_server` reconnects to silent prompt, marks `serial_gap_detected=True`,
+        # fires automatic `\r` probe after 800ms, receives re-echoed prompt, and completes all 7 stages!
+        await stack.set_link(1, bmc_up=True, serial_up=True)
+
+        async def _s2_recovered_and_done():
+            st = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
+            return st if st.get("task_status") in ("completed", "failed") else None
+
+        st_s2_done = await wait_until(_s2_recovered_and_done, timeout_s=35.0, desc="S2 recovery via CR probe & completion")
+        if st_s2_done["task_status"] != "completed":
+            hs_dbg = await stack.hil_status()
+            uart_dbg = await stack.admin_ws.call("ReadCleanedUart", {"station_id": "S2", "offset": 0, "max_bytes": 8192})
+            raise AssertionError(
+                f"Expected S2 completed, got {st_s2_done}\nDUT={hs_dbg['duts'][1]}\nUART_TAIL={uart_dbg.get('text', '')[-1500:]}"
+            )
+        assert st_s2_done["serial_gap_detected"] is True, f"Expected serial_gap_detected=True on S2, got {st_s2_done}"
+
+        # Check archived task history / GetTaskStatus also carries `serial_gap_detected: true`
+        ts_s2 = await stack.admin_ws.call("GetTaskStatus", {"station_id": "S2"})
+        latest_s2 = ts_s2.get("latest_run") or {}
+        assert ts_s2.get("serial_gap_detected") is True and latest_s2.get("serial_gap_detected") is True, (
+            f"Archived summary must record serial_gap_detected: {ts_s2}"
+        )
+        results.append({"scenario": "2_dual_drop_grace_serial_gap_and_cr_probe", "status": "PASS"})
+        print("      -> PASS", flush=True)
+
+        # ====================================================================
+        # Scenario 3: Post-Reconnect `server_power == "off"` Verification + Hood Purge
+        # ====================================================================
+        print("[Tier2][3/8] Testing dual-disconnect + AC power loss -> `reconnect_power_off` FAIL + 6400 Hood 0x08 00 purge on S3...", flush=True)
+        await stack.clear_hood_history(2)
+        await stack.configure_dut(2, speed_scale=1.0)
+        await stack.connect_and_heat_backend_hood("S3", 2, target_c=70)
+        await stack.enqueue_cmd(
+            "S3",
+            "SaveBootPlan",
+            {
+                "plan": {
+                    "preset": "custom",
+                    "mt_enabled": True,
+                    "run_rmt": True,
+                    "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"},
+                },
+                "watchdog": {"link_lost_timeout_ms": 40000},
+            },
+        )
+        await stack.enqueue_cmd("S3", "ControlBootPlan", {"action": "start"})
+        await stack.trigger_dut_boot(2, reason="reset")
+
+        await asyncio.sleep(0.5)
+        # Unplug network AND cut server power (`power_on=False`) while S3 is actively running
+        await stack.set_link(2, bmc_up=False, serial_up=False)
+        await stack.set_power(2, power_on=False)
+
+        try:
+            await wait_until(
+                lambda: _check_detail(stack, "S3", "link_offline_waiting"),
+                timeout_s=35.0,
+                desc="S3 link_offline_waiting",
+            )
+        except AssertionError:
+            st_dbg = await stack.admin_ws.call("GetStation", {"station_id": "S3"})
+            hs_dbg = await stack.hil_status()
+            raise AssertionError(f"S3 link_offline_waiting timed out! S3={st_dbg}\nBMC={hs_dbg['bmc'][2]}")
+        # Restore network while server remains powered OFF!
+        await stack.set_link(2, bmc_up=True, serial_up=True)
+
+        st_s3_fail = await wait_until(
+            lambda: _check_failed(stack, "S3"),
+            timeout_s=20.0,
+            desc="S3 reconnect_power_off failure",
+        )
+        assert st_s3_fail.get("fault_code") == "reconnect_power_off", f"Expected reconnect_power_off, got {st_s3_fail}"
+        assert int(st_s3_fail.get("ended_unix_ms") or "0") > 0, "Timer must be frozen on reconnect_power_off"
+
+        await wait_until(lambda: _check_hood_purged(stack, 2), timeout_s=5.0, desc="S3 hood 0x08 00 cooling purge")
+        await stack.set_power(2, power_on=True)
+        await stack.wait_station_online("S3", timeout_s=20.0)
+        results.append({"scenario": "3_reconnect_power_off_and_hood_purge", "status": "PASS"})
+        print("      -> PASS", flush=True)
+
+        # ====================================================================
+        # Scenario 4: Dual-Disconnect Timeout Ceiling (`link_lost_timeout`) + Hood Purge
+        # ====================================================================
+        print("[Tier2][4/8] Testing prolonged dual-disconnect -> `link_lost_timeout` FAIL + timer freeze + Hood purge on S3...", flush=True)
+        await stack.clear_hood_history(2)
+        await stack.configure_dut(2, speed_scale=1.0)
+        await stack.connect_and_heat_backend_hood("S3", 2, target_c=70)
+        await stack.enqueue_cmd(
+            "S3",
+            "SaveBootPlan",
+            {
+                "plan": {
+                    "preset": "custom",
+                    "mt_enabled": True,
+                    "run_rmt": True,
+                    "stages": {"uip1": "auto", "amt": "auto", "uip2": "manual", "uefi": "auto"},
+                },
+                "watchdog": {"link_lost_timeout_ms": 9500},
+            },
+        )
+        await stack.enqueue_cmd("S3", "ControlBootPlan", {"action": "start"})
+        await stack.trigger_dut_boot(2, reason="reset")
+        await asyncio.sleep(0.5)
+
+        await stack.set_link(2, bmc_up=False, serial_up=False)
+        await wait_until(lambda: _check_detail(stack, "S3", "link_offline_waiting"), timeout_s=35.0, desc="S3 link_offline_waiting")
+        st_s3_to = await wait_until(lambda: _check_failed(stack, "S3"), timeout_s=20.0, desc="S3 link_lost_timeout")
+        assert st_s3_to.get("fault_code") == "link_lost_timeout", f"Expected link_lost_timeout, got {st_s3_to}"
+        elapsed_1 = st_s3_to.get("elapsed_ms")
+        await asyncio.sleep(0.8)
+        st_s3_to2 = await stack.admin_ws.call("GetStation", {"station_id": "S3"})
+        assert st_s3_to2.get("elapsed_ms") == elapsed_1, f"Stopwatch must freeze on link_lost_timeout ({elapsed_1} vs {st_s3_to2.get('elapsed_ms')})"
+        await wait_until(lambda: _check_hood_purged(stack, 2), timeout_s=5.0, desc="S3 hood 0x08 00 purge after link_lost_timeout")
+
+        # Restore S3 links
+        await stack.set_link(2, bmc_up=True, serial_up=True)
+        await stack.wait_station_online("S3", timeout_s=20.0)
+        results.append({"scenario": "4_dual_disconnect_link_lost_timeout", "status": "PASS"})
+        print("      -> PASS", flush=True)
+
+        # ====================================================================
+        # Scenario 5: Level-1 Hard Hang in RMT (`reboot_on_hang=False` default)
+        #             -> FAIL + Timer Freeze + Hood Purge + ZERO BMC Resets (Scene Preserved!)
+        # ====================================================================
+        print("[Tier2][5/8] Testing Level-1 RMT hard hang -> `stage_hang_timeout` + 0 BMC resets (scene preserved) + Hood purge on S1...", flush=True)
+        await stack.clear_hood_history(0)
+        await stack.connect_and_heat_backend_hood("S1", 0, target_c=70)
+        await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.15)
+
+        await stack.admin_ws.call(
+            "SubmitTaskBatch",
+            {
+                "station_id": "S1",
+                "stop_on_fail": False,
+                "reboot_on_hang": False,  # Level-1 default: preserve hang scene even in multi-run batch!
+                "watchdog": {"dense_stage_silence_timeout_ms": 2500},
+                "profiles": [{"name": "Level1-RMT-Hang", "repeat": 3, "run_rmt": True, "run_amt": False, "run_mt": False}],
+            },
+        )
+
+        # Wait until DUT enters `rmt` and freezes (`hung_now == True`)
+        async def _s1_hung_in_rmt():
+            hs = await stack.hil_status()
+            d0 = hs["duts"][0]
+            return hs if d0.get("hung_now") is True and d0.get("stage") == "rmt" else None
+
+        hs_at_hang = await wait_until(_s1_hung_in_rmt, timeout_s=20.0, desc="S1 DUT frozen in RMT")
+        bmc_before = hs_at_hang["bmc"][0]
+        off_before = bmc_before["off_count"]
+        rst_before = bmc_before["reset_count"]
+        cyc_before = bmc_before["cycle_count"]
+        boot_before = hs_at_hang["duts"][0]["hw_boot_count"]
+
+        st_s1_hang = await wait_until(lambda: _check_failed(stack, "S1"), timeout_s=10.0, desc="S1 stage_hang_timeout")
+        assert st_s1_hang.get("fault_code") == "stage_hang_timeout", f"Expected stage_hang_timeout, got {st_s1_hang}"
+        assert st_s1_hang.get("hang_scene_preserved") is True, f"Expected hang_scene_preserved=True, got {st_s1_hang}"
+
+        # Wait 1.5s to ensure NO delayed BMC reset is issued!
+        await asyncio.sleep(1.5)
+        hs_after = await stack.hil_status()
+        bmc_after = hs_after["bmc"][0]
+        assert bmc_after["off_count"] == off_before, f"Level-1 hang MUST NOT power-off BMC ({off_before} -> {bmc_after['off_count']})"
+        assert bmc_after["reset_count"] == rst_before, f"Level-1 hang MUST NOT reset BMC ({rst_before} -> {bmc_after['reset_count']})"
+        assert bmc_after["cycle_count"] == cyc_before, "Level-1 hang MUST NOT power-cycle BMC"
+        assert hs_after["duts"][0]["hw_boot_count"] == boot_before, "DUT must remain in exact hung boot scene"
+        assert hs_after["bmc"][0]["ssh_active"] is True, "SSH :2200 console must remain open so R&D can inspect last line"
+
+        batch_s1_resp = await stack.admin_ws.call("GetTaskBatch", {"station_id": "S1"})
+        batch_s1 = batch_s1_resp.get("task_batch") or {}
+        assert batch_s1.get("halt_reason") == "hang_scene_preserved", f"Expected halt_reason=hang_scene_preserved, got {batch_s1}"
+        assert len(batch_s1.get("runs") or []) == 1, "Batch must halt immediately after Run 1 without rebooting into Run 2"
+        await wait_until(lambda: _check_hood_purged(stack, 0), timeout_s=5.0, desc="S1 hood 0x08 00 purge on RMT hang")
+        await stack.configure_dut(0, hang_stage="", hang_remaining_boots=0)
+        results.append({"scenario": "5_level1_hang_preserve_scene_and_hood_purge", "status": "PASS"})
+        print("      -> PASS", flush=True)
+
+        # ====================================================================
+        # Scenario 6: MemTest86 Infinite ANSI Clock Redraw Caught by `mt_max_duration_ms`
+        # ====================================================================
+        print("[Tier2][6/8] Testing non-silent MT ANSI clock-redraw infinite loop caught by `mt_duration_timeout` on S4...", flush=True)
+        await stack.clear_hood_history(3)
+        await stack.connect_and_heat_backend_hood("S4", 3, target_c=70)
+        await stack.configure_dut(3, hang_stage="mt_clock_loop", hang_remaining_boots=1, speed_scale=0.12)
+        await configure_station_auto(
+            stack,
+            "S4",
+            mt_enabled=True,
+            run_rmt=False,
+            run_amt=False,
+            watchdog={
+                "dense_stage_silence_timeout_ms": 20000,
+                "mt_silence_timeout_ms": 60000,  # Silence threshold high (ANSI clock keeps sending bytes!)
+                "mt_max_duration_ms": 2500,      # Stage duration cap catches infinite clock loop!
+            },
+        )
+        await stack.enqueue_cmd("S4", "ControlBootPlan", {"action": "restart"})
+        st_s4_mt = await wait_until(lambda: _check_failed(stack, "S4"), timeout_s=25.0, desc="S4 mt_duration_timeout")
+        assert st_s4_mt.get("fault_code") == "mt_duration_timeout", f"Expected mt_duration_timeout, got {st_s4_mt}"
+        await wait_until(lambda: _check_hood_purged(stack, 3), timeout_s=5.0, desc="S4 hood purge on mt_duration_timeout")
+        await stack.configure_dut(3, hang_stage="", hang_remaining_boots=0)
+        results.append({"scenario": "6_mt_ansi_clock_loop_duration_watchdog", "status": "PASS"})
+        print("      -> PASS", flush=True)
+
+        # ====================================================================
+        # Scenario 7: Level-2 Unattended `reboot_on_hang=True` SmartRestart Recovery & Circuit Breaker
+        # ====================================================================
+        print("[Tier2][7/8] Testing Level-2 `reboot_on_hang=True` SmartRestart recovery (S1) + `max_consecutive_hangs=2` circuit breaker (S2)...", flush=True)
+        # 7a: S1 hangs ONCE in RMT (`hang_remaining_boots=1`), Round 2 recovers via real RMCP+ SmartRestart and PASSES!
+        await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12)
+        await stack.admin_ws.call(
+            "SubmitTaskBatch",
+            {
+                "station_id": "S1",
+                "stop_on_fail": False,
+                "reboot_on_hang": True,
+                "max_consecutive_hangs": 2,
+                "watchdog": {"dense_stage_silence_timeout_ms": 2200},
+                "profiles": [{"name": "Level2-Transient-Hang-Recovery", "repeat": 2, "run_rmt": True, "run_amt": False, "run_mt": False}],
+            },
+        )
+
+        async def _s1_batch_done():
+            resp = await stack.admin_ws.call("GetTaskBatch", {"station_id": "S1"})
+            b = resp.get("task_batch") or {}
+            return b if b.get("state") in ("completed", "failed") else None
+
+        b_s1_rec = await wait_until(_s1_batch_done, timeout_s=45.0, desc="S1 Level-2 2-round batch completion")
+        runs_s1 = b_s1_rec.get("runs") or []
+        assert len(runs_s1) == 2, f"Expected 2 runs (R1 hang -> SmartRestart -> R2 pass), got {b_s1_rec}"
+        assert runs_s1[0].get("verdict") == "fail", f"Expected R1 fail, got {runs_s1[0]}"
+        assert runs_s1[1].get("verdict") == "pass", f"Expected R2 pass after SmartRestart recovery, got {runs_s1[1]}"
+
+        # 7b: S2 permanently dead board (`hang_remaining_boots=99`, `repeat=4`, `max_consecutive_hangs=2`)
+        #     -> hangs in R1, auto-reboots into R2, hangs in R2 -> trips `consecutive_hang_limit_exceeded` & cools hood!
+        await stack.clear_hood_history(1)
+        await stack.connect_and_heat_backend_hood("S2", 1, target_c=70)
+        await stack.configure_dut(1, hang_stage="rmt", hang_remaining_boots=99, speed_scale=0.12)
+        await stack.admin_ws.call(
+            "SubmitTaskBatch",
+            {
+                "station_id": "S2",
+                "stop_on_fail": False,
+                "reboot_on_hang": True,
+                "max_consecutive_hangs": 2,
+                "watchdog": {"dense_stage_silence_timeout_ms": 2200},
+                "profiles": [{"name": "Level2-DeadBoard-Breaker", "repeat": 4, "run_rmt": True, "run_amt": False, "run_mt": False}],
+            },
+        )
+
+        async def _s2_batch_done():
+            resp = await stack.admin_ws.call("GetTaskBatch", {"station_id": "S2"})
+            b = resp.get("task_batch") or {}
+            return b if b.get("state") in ("completed", "failed") else None
+
+        b_s2_brk = await wait_until(_s2_batch_done, timeout_s=45.0, desc="S2 Level-2 circuit breaker halt")
+        runs_s2 = b_s2_brk.get("runs") or []
+        assert len(runs_s2) == 2, f"Circuit breaker must stop at 2 consecutive hangs (not run all 4!), got {len(runs_s2)}"
+        assert b_s2_brk.get("halt_reason") == "consecutive_hang_limit_exceeded", f"Unexpected halt_reason: {b_s2_brk}"
+        st_s2_brk = await stack.admin_ws.call("GetStation", {"station_id": "S2"})
+        assert st_s2_brk.get("hang_scene_preserved") is True, "Circuit breaker halt must preserve final hang scene"
+        await wait_until(lambda: _check_hood_purged(stack, 1), timeout_s=5.0, desc="S2 hood purge on circuit breaker")
+        await stack.configure_dut(1, hang_stage="", hang_remaining_boots=0)
+        results.append({"scenario": "7_level2_smart_restart_recovery_and_circuit_breaker", "status": "PASS"})
+        print("      -> PASS", flush=True)
+
+        # ====================================================================
+        # Scenario 8: Official `tools/validate_qt_clean.py` Contract Audit
+        # ====================================================================
+        print("[Tier2][8/8] Running official `tools/validate_qt_clean.py` against live HIL-backed `/ws?view=qt-clean`...", flush=True)
+        out_json = stack.tmp_dir / "qt_clean_evidence.json"
+        py_bin = "/opt/prod2u/venv/bin/python3" if os.path.exists("/opt/prod2u/venv/bin/python3") else sys.executable
+        proc = await asyncio.to_thread(
+            subprocess.run,
+            [
+                py_bin,
+                str(ROOT_DIR / "tools" / "validate_qt_clean.py"),
+                "--url", f"ws://127.0.0.1:{stack.web_port}/ws?view=qt-clean",
+                "--station", "S1",
+                "--output", str(out_json),
+            ],
+            env=stack._clean_env(),
+            capture_output=True,
+            text=True,
+            timeout=30,
+        )
+        assert proc.returncode == 0, f"validate_qt_clean.py failed (rc={proc.returncode}):\n{proc.stdout}\n{proc.stderr}"
+        ev_data = json.loads(out_json.read_text(encoding="utf-8"))
+        failed_checks = [c for c in ev_data.get("checks", []) if c.get("status") == "FAIL"]
+        assert not failed_checks, f"validate_qt_clean.py reported FAIL checks: {failed_checks}"
+        results.append({"scenario": "8_qt_clean_protocol_validator", "status": "PASS", "checks": len(ev_data.get("checks", []))})
+        print(f"      -> PASS ({len(ev_data.get('checks', []))} protocol & privacy checks clean)", flush=True)
+
+    elapsed_s = round(time.monotonic() - t_suite0, 2)
+    summary = {"tier": "Tier2_MultiStation_HIL_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
+    print("\n[Tier2] ALL 8 MULTI-STATION HIL SCENARIOS PASSED in " + f"{elapsed_s}s!", flush=True)
+    return summary
+
+
+async def _check_bmc_state(stack: HilClusterStack, sid: str, expected: str) -> Any:
+    assert stack.admin_ws is not None
+    st = await stack.admin_ws.call("GetStation", {"station_id": sid})
+    return st if st.get("bmc_state") == expected else None
+
+
+async def _check_detail(stack: HilClusterStack, sid: str, expected_detail: str) -> Any:
+    assert stack.admin_ws is not None
+    st = await stack.admin_ws.call("GetStation", {"station_id": sid})
+    if st.get("observed_detail") == expected_detail:
+        return st
+    return False
+
+
+async def _check_failed(stack: HilClusterStack, sid: str) -> Any:
+    assert stack.admin_ws is not None
+    st = await stack.admin_ws.call("GetStation", {"station_id": sid})
+    return st if st.get("task_status") == "failed" else None
+
+
+async def _check_hood_purged(stack: HilClusterStack, idx: int) -> Any:
+    hs = await stack.hil_status()
+    hood = hs["backend_hoods"][idx]
+    return hood if hood.get("purge_cool_count", 0) >= 1 and hood.get("cooling_purge") is True else None
+
+
+if __name__ == "__main__":
+    res = asyncio.run(run_tier2_suite())
+    out_file = ROOT_DIR / "build" / "sim" / "tier2_hil_report.json"
+    out_file.parent.mkdir(parents=True, exist_ok=True)
+    out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")

+ 657 - 0
sim/kvm_uefi_tier/test_tier3_kvm_uefi_e2e.py

@@ -0,0 +1,657 @@
+#!/usr/bin/env python3
+"""
+test_tier3_kvm_uefi_e2e.py — Tier 3 Real Hardware KVM + EDK2 OVMF UEFI + `mt86plus.efi` E2E
+
+Uses `root@192.168.2.25` hardware `/dev/kvm`, real EDK2 OVMF (`code.fd` + `vars.fd`), and the
+real compiled x86-64 UEFI memory diagnostic binary `mt86plus.efi` inside an isolated ephemeral
+Podman container (`--rm --device /dev/kvm`), bridged via QMP + COM1 UART into `bmc_ssh_hil_sim`
+(`127.0.2.170` UDP :623 RMCP+ & TCP :2200 SSHv2) and unmodified `stl_native_server`.
+
+Verifies:
+  1. Real KVM + OVMF UEFI boot -> EDK2 `UEFI Interactive Shell` -> automated UEFI MT script PASS.
+  2. Real x86-64 `mt86plus.efi` execution on KVM RAM + live ANSI serial cleaning + QMP hardware
+     vCPU freeze (`{"execute": "stop"}`) -> `stl_native_server` stage watchdog (`stage_hang_timeout`),
+     Level-1 scene preservation (QMP `query-status` confirms VM stays `"paused"` with 0 resets),
+     and `/dev/pts/*` 6400 High-Temperature Hood `0x08 00` cooling purge.
+  3. Real IPMI RMCP+ `StationPower: host_reset` -> `PWR:RESET` -> QMP `cont` + `system_reset`
+     rebooting the KVM OVMF guest cleanly back to `UEFI Interactive Shell`.
+"""
+
+import asyncio
+import contextlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from typing import Any, Callable, Dict, Optional
+import uuid
+
+import aiohttp
+
+ROOT_DIR = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
+from cluster_harness import BMC_SIM_BIN, CONTRACTS_PATH, STL_SERVER_BIN, WEB_DIR, WsRpcClient  # noqa: E402
+from dut_and_hood_sim import HoodPtsSim  # noqa: E402
+
+REMOTE_HOST = os.environ.get("STL_KVM_HOST", "192.168.2.25")
+REMOTE_USER = os.environ.get("STL_KVM_USER", "root")
+PODMAN_IMAGE = "localhost/omo-lab:13-iso-20260921T030408Z"
+
+
+async def wait_until(
+    pred: Callable[[], Any],
+    timeout_s: float = 30.0,
+    interval_s: float = 0.25,
+    desc: str = "condition",
+) -> Any:
+    deadline = time.monotonic() + timeout_s
+    last_val = None
+    while time.monotonic() < deadline:
+        res = pred()
+        if asyncio.iscoroutine(res):
+            res = await res
+        last_val = res
+        if res:
+            return res
+        await asyncio.sleep(interval_s)
+    raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}")
+
+
+class QmpClient:
+    """Async QEMU Machine Protocol (QMP) client for vCPU freeze, status query, and hardware reset."""
+
+    def __init__(self, host: str, port: int):
+        self.host = host
+        self.port = port
+        self.reader: Optional[asyncio.StreamReader] = None
+        self.writer: Optional[asyncio.StreamWriter] = None
+        self.lock = asyncio.Lock()
+
+    async def connect(self, timeout_s: float = 12.0) -> None:
+        deadline = time.monotonic() + timeout_s
+        while time.monotonic() < deadline:
+            try:
+                self.reader, self.writer = await asyncio.open_connection(self.host, self.port)
+                greeting = await asyncio.wait_for(self.reader.readline(), timeout=3.0)
+                if b"QMP" in greeting:
+                    await self.execute("qmp_capabilities")
+                    return
+            except Exception:
+                await asyncio.sleep(0.2)
+        raise TimeoutError(f"Failed to connect QMP at {self.host}:{self.port}")
+
+    async def execute(self, cmd: str, arguments: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+        async with self.lock:
+            assert self.reader is not None and self.writer is not None
+            req: Dict[str, Any] = {"execute": cmd}
+            if arguments:
+                req["arguments"] = arguments
+            self.writer.write((json.dumps(req) + "\r\n").encode("utf-8"))
+            await self.writer.drain()
+            while True:
+                line = await asyncio.wait_for(self.reader.readline(), timeout=5.0)
+                if not line:
+                    raise RuntimeError("QMP connection closed")
+                msg = json.loads(line.decode("utf-8", errors="replace"))
+                if "return" in msg:
+                    return msg["return"]
+                if "error" in msg:
+                    raise RuntimeError(f"QMP error on {cmd}: {msg['error']}")
+                # Ignore async `EVENT` lines (STOP, RESUME, RESET, etc.)
+
+    async def close(self) -> None:
+        if self.writer is not None:
+            with contextlib.suppress(Exception):
+                self.writer.close()
+
+
+async def bridge_kvm_uart_and_pwr(
+    qemu_serial_port: int,
+    bmc_uart_bridge_port: int,
+    qmp: QmpClient,
+    stats: Dict[str, Any],
+) -> None:
+    """Bridges QEMU KVM COM1 TCP socket <-> `bmc_ssh_hil_sim` UART bridge + translates `\x01PWR:*` to QMP."""
+    while True:
+        q_writer = None
+        b_writer = None
+        try:
+            q_reader, q_writer = await asyncio.open_connection("127.0.0.1", qemu_serial_port)
+            b_reader, b_writer = await asyncio.open_connection("127.0.0.1", bmc_uart_bridge_port)
+
+            async def qemu_to_bmc() -> None:
+                while True:
+                    data = await q_reader.read(4096)
+                    if not data:
+                        break
+                    stats["kvm_uart_rx_bytes"] = stats.get("kvm_uart_rx_bytes", 0) + len(data)
+                    stats["tail_text"] = (stats.get("tail_text", "") + data.decode("utf-8", errors="replace"))[-6000:]
+                    b_writer.write(data)
+                    await b_writer.drain()
+
+            async def bmc_to_qemu() -> None:
+                while True:
+                    data = await b_reader.read(4096)
+                    if not data:
+                        break
+                    txt = data.decode("utf-8", errors="replace")
+                    idx = 0
+                    out_chars = []
+                    while idx < len(txt):
+                        if txt[idx] == "\x01" and txt.startswith("\x01PWR:", idx):
+                            nl = txt.find("\n", idx)
+                            if nl < 0:
+                                nl = len(txt)
+                            ev = txt[idx + 5 : nl].strip()
+                            stats.setdefault("pwr_events", []).append(ev)
+                            if ev == "OFF":
+                                with contextlib.suppress(Exception):
+                                    await qmp.execute("stop")
+                            elif ev in ("ON", "RESET", "CYCLE"):
+                                with contextlib.suppress(Exception):
+                                    await qmp.execute("cont")
+                                with contextlib.suppress(Exception):
+                                    await qmp.execute("system_reset")
+                            idx = nl + 1
+                            continue
+                        out_chars.append(txt[idx])
+                        idx += 1
+                    if out_chars:
+                        q_writer.write("".join(out_chars).encode("utf-8"))
+                        await q_writer.drain()
+
+            await asyncio.gather(qemu_to_bmc(), bmc_to_qemu())
+        except asyncio.CancelledError:
+            raise
+        except Exception:
+            pass
+        finally:
+            for w in (q_writer, b_writer):
+                if w is not None:
+                    with contextlib.suppress(Exception):
+                        w.close()
+        await asyncio.sleep(0.2)
+
+
+async def run_tier3_kvm_suite() -> Dict[str, Any]:
+    t0 = time.monotonic()
+    run_tag = f"xjkj-stl-kvm-{os.getpid()}-{int(time.time())}"
+    remote_dir = f"/tmp/{run_tag}"
+    cname = run_tag
+    q_serial_port = 29210
+    q_qmp_port = 29211
+    bmc_ctrl_port = 29199
+    bmc_uart_port = 29200
+    web_port = 28980
+    station_ip = "127.0.2.170"
+
+    local_tmp = Path(tempfile.mkdtemp(prefix="xjkj_stl_tier3_"))
+    ssh_tunnel_proc: Optional[subprocess.Popen] = None
+    bmc_proc: Optional[subprocess.Popen] = None
+    server_proc: Optional[subprocess.Popen] = None
+    hood: Optional[HoodPtsSim] = None
+    hood_task: Optional[asyncio.Task] = None
+    bridge_task: Optional[asyncio.Task] = None
+    qmp = QmpClient("127.0.0.1", q_qmp_port)
+
+    env = dict(os.environ)
+    for k in (
+        "LD_LIBRARY_PATH",
+        "http_proxy",
+        "https_proxy",
+        "HTTP_PROXY",
+        "HTTPS_PROXY",
+        "all_proxy",
+        "ALL_PROXY",
+    ):
+        env.pop(k, None)
+
+    try:
+        print(f"[Tier3] Provisioning isolated KVM + OVMF + mt86plus.efi workspace on {REMOTE_HOST}:{remote_dir}...", flush=True)
+        setup_sh = rf"""
+set -euo pipefail
+mkdir -p {remote_dir}/esp/EFI/BOOT
+cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/code.fd {remote_dir}/code.fd
+cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/vars.fd {remote_dir}/vars.fd
+cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/hda-contents/EFI/BOOT/BOOTX64.EFI {remote_dir}/esp/EFI/BOOT/BOOTX64.EFI
+cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/mt86plus.efi {remote_dir}/esp/EFI/mt86plus.efi
+
+cat > {remote_dir}/esp/startup.nsh << 'EOF'
+@echo -off
+echo [HS_BIOS]Version: 108_VD012_KVM_OVMF
+echo [HS_StartMemTrain]
+echo [HS_DRAM] N0.C0.D0 DDR5 Present Size:65536
+echo [HS_EndMemTrain]
+echo MRC Done
+echo START_RMT_N0
+echo N0.C0.D0.R0 : -18 19 -17 18
+echo STOP_RMT_N0
+fs0:
+cd \EFI
+EOF
+
+cat > {remote_dir}/esp/EFI/kvm_mt_pass.nsh << 'EOF'
+@echo -off
+echo Launching 118.efi
+echo PassMark MemTest86 V11.1 Pro (KVM-OVMF-UEFI)
+echo Running test #0 (Test: 0/26 0%)
+echo Running test #13 (Test: 13/26 50%)
+echo Running test #25 (Test: 25/26 96%)
+echo Tests Passed: 26/26
+echo Pass complete, no errors
+echo Test Result: PASS
+EOF
+
+cat > {remote_dir}/esp/EFI/launch_real_mt86.nsh << 'EOF'
+@echo -off
+echo Launching 118.efi
+FS0:\EFI\mt86plus.efi console=ttyS0,115200 newline nopause nosmp nosm nobench keyboard=legacy testlist=0,1
+EOF
+
+podman run -d --rm --name {cname} \
+  --device /dev/kvm \
+  -v {remote_dir}:/sim:rw \
+  -p 127.0.0.1:{q_serial_port}:{q_serial_port} \
+  -p 127.0.0.1:{q_qmp_port}:{q_qmp_port} \
+  {PODMAN_IMAGE} \
+  qemu-system-x86_64 \
+    -machine q35,accel=kvm -cpu host -smp 2 -m 512M \
+    -display none -net none \
+    -drive if=pflash,format=raw,readonly=on,file=/sim/code.fd \
+    -drive if=pflash,format=raw,file=/sim/vars.fd \
+    -drive file=fat:rw:/sim/esp,format=raw,if=ide \
+    -serial tcp:0.0.0.0:{q_serial_port},server=on,wait=off \
+    -qmp tcp:0.0.0.0:{q_qmp_port},server=on,wait=off
+"""
+        subprocess.run(
+            ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", setup_sh],
+            check=True,
+            timeout=25,
+            capture_output=True,
+            text=True,
+        )
+
+        # Open SSH local port forward for QEMU COM1 serial & QMP sockets
+        ssh_tunnel_proc = subprocess.Popen(
+            [
+                "ssh",
+                "-o", "BatchMode=yes",
+                "-o", "ExitOnForwardFailure=yes",
+                "-N",
+                "-L", f"127.0.0.1:{q_serial_port}:127.0.0.1:{q_serial_port}",
+                "-L", f"127.0.0.1:{q_qmp_port}:127.0.0.1:{q_qmp_port}",
+                f"{REMOTE_USER}@{REMOTE_HOST}",
+            ],
+            stdout=subprocess.DEVNULL,
+            stderr=subprocess.PIPE,
+            text=True,
+        )
+        await qmp.connect(timeout_s=12.0)
+        qstatus0 = await qmp.execute("query-status")
+        assert qstatus0.get("running") is True, f"Expected KVM guest running, got {qstatus0}"
+
+        # Start C BMC RMCP+ (:623) & SSHv2 (:2200) simulator on `127.0.2.170`
+        bmc_proc = subprocess.Popen(
+            [
+                str(BMC_SIM_BIN),
+                "--ctrl-port", str(bmc_ctrl_port),
+                "--uart-base", str(bmc_uart_port),
+                "--ipmi-port", "623",
+                "--ssh-port", "2200",
+                "--probe22-port", "0",
+                station_ip,
+            ],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            text=True,
+            env=env,
+        )
+        await asyncio.sleep(0.4)
+
+        stats: Dict[str, Any] = {}
+        bridge_task = asyncio.create_task(
+            bridge_kvm_uart_and_pwr(q_serial_port, bmc_uart_port, qmp, stats)
+        )
+
+        # Start `/dev/pts/*` 6400 Hood simulator for S1
+        hood = HoodPtsSim("kvm-hood-S1", 0, ("127.0.0.1", bmc_ctrl_port), sync_bmc=True)
+        hood_task = asyncio.create_task(hood.physics_and_heartbeat_loop())
+
+        # Start unmodified `stl_native_server` pointing S1 -> `127.0.2.170`
+        data_dir = local_tmp / "data"
+        data_dir.mkdir(parents=True, exist_ok=True)
+        cfg_path = local_tmp / "station-kvm.json"
+        cfg_path.write_text(
+            json.dumps(
+                {
+                    "mode": "hardware",
+                    "data_dir": str(data_dir),
+                    "telemetry_interval_s": 1.0,
+                    "idle_poll_interval_s": 1,
+                    "stations": [
+                        {
+                            "station_id": "S1",
+                            "frontend_index": 0,
+                            "name": "KVM-OVMF 真机虚拟化工位",
+                            "mode": "hardware",
+                            "cpu_count": 1,
+                            "channels_per_cpu": 12,
+                            "bmc": {
+                                "enabled": True,
+                                "host": station_ip,
+                                "user": "ADMIN",
+                                "username": "ADMIN",
+                                "password": "Admin123@pl",
+                                "cipher_suite": 17,
+                                "timeout_s": 5,
+                                "console_transport": "ssh_console",
+                                "ssh_console_port": 2200,
+                            },
+                            "console": {
+                                "enabled": True,
+                                "transport": "ssh_console",
+                                "host": station_ip,
+                                "port": 2200,
+                                "user": "ADMIN",
+                                "write_chunk_bytes": 64,
+                                "write_gap_ms": 5.0,
+                            },
+                        }
+                    ],
+                },
+                indent=2,
+            ),
+            encoding="utf-8",
+        )
+
+        server_proc = subprocess.Popen(
+            [
+                str(STL_SERVER_BIN),
+                "--config", str(cfg_path),
+                "--data-dir", str(data_dir),
+                "--web-listen", f"127.0.0.1:{web_port}",
+                "--tftp-listen", "disabled",
+                "--web-dir", str(WEB_DIR),
+                "--contracts", str(CONTRACTS_PATH),
+                "--web-password", "disabled",
+            ],
+            cwd=str(ROOT_DIR),
+            stdout=subprocess.DEVNULL,
+            stderr=subprocess.PIPE,
+            text=True,
+            env=env,
+        )
+
+        results = []
+        async with aiohttp.ClientSession() as http:
+            # Wait HTTP up
+            await wait_until(
+                lambda: _http_ok(http, f"http://127.0.0.1:{web_port}/"),
+                timeout_s=10.0,
+                desc="stl_native_server HTTP up",
+            )
+            ws = WsRpcClient(http, f"ws://127.0.0.1:{web_port}/ws")
+            await ws.connect()
+            try:
+                # Wait for S1 BMC + :2200 SSH console online AND real OVMF UEFI Shell prompt!
+                print("[Tier3][1/3] Booting real KVM + EDK2 OVMF guest into UEFI Interactive Shell & running automated MT PASS...", flush=True)
+                await wait_until(
+                    lambda: _station_online(ws, "S1"),
+                    timeout_s=15.0,
+                    desc="S1 KVM station online",
+                )
+                # Reset KVM guest via QMP so `stl_native_server` observes the full OVMF boot + startup.nsh + `Shell>`!
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-cfg-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "SaveFirmwareSettings",
+                        "arguments": {"mt_selection": {"efi_path": "FS0:\\EFI\\kvm_mt_pass.nsh"}},
+                    },
+                )
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-plan-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "SaveBootPlan",
+                        "arguments": {
+                            "plan": {
+                                "preset": "auto",
+                                "mt_enabled": True,
+                                "run_rmt": True,
+                                "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"},
+                            },
+                            "watchdog": {"dense_stage_silence_timeout_ms": 20000, "mt_silence_timeout_ms": 20000},
+                        },
+                    },
+                )
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-start1-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "ControlBootPlan",
+                        "arguments": {"action": "start"},
+                    },
+                )
+                await qmp.execute("system_reset")
+
+                st_pass = await wait_until(
+                    lambda: _station_terminal(ws, "S1"),
+                    timeout_s=30.0,
+                    desc="KVM OVMF UEFI automated MT PASS",
+                )
+                if st_pass["task_status"] != "completed":
+                    clean_u = await ws.call("ReadCleanedUart", {"station_id": "S1", "offset": 0, "max_bytes": 8192})
+                    raise AssertionError(
+                        f"Unexpected KVM S1 state: {st_pass}\nRAW_TAIL={repr(stats.get('tail_text', '')[-1200:])}\nCLEAN_TAIL={repr(clean_u.get('text', '')[-1200:])}"
+                    )
+                assert st_pass["verdict"] == "pass", f"Unexpected KVM S1 state: {st_pass}"
+                assert (st_pass.get("stage_completions") or {}).get("uefi_complete") is True
+                assert (st_pass.get("stage_completions") or {}).get("mt_pass_complete") is True
+                results.append({"scenario": "1_kvm_ovmf_uefi_shell_auto_pass", "status": "PASS"})
+                print("      -> PASS", flush=True)
+
+                # ============================================================
+                # Scenario 2: Real `mt86plus.efi` Execution on KVM RAM + QMP Hardware vCPU Freeze
+                #             -> Watchdog `stage_hang_timeout` + Level-1 Scene Preserved + Hood Purge
+                # ============================================================
+                print("[Tier3][2/3] Launching real x86-64 `mt86plus.efi` on KVM RAM + QMP `stop` hardware vCPU freeze...", flush=True)
+                hood.clear_history()
+                await ws.call(
+                    "ThermalAction",
+                    {"station_id": "S1", "action": "connect", "mode": "serial", "serial_path": hood.pts_path, "serial_baud": 115200},
+                )
+                await wait_until(
+                    lambda: _thermal_online(ws, "S1"),
+                    timeout_s=4.0,
+                    desc="KVM Hood 0xF0 online",
+                )
+                await ws.call("ThermalAction", {"station_id": "S1", "action": "set_temp", "target_c": 70})
+
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-cfg2-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "SaveFirmwareSettings",
+                        "arguments": {"mt_selection": {"efi_path": "FS0:\\EFI\\launch_real_mt86.nsh"}},
+                    },
+                )
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-wd2a-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "ConfigureWatchdog",
+                        "arguments": {
+                            "watchdog": {
+                                "enabled": True,
+                                "reboot_on_hang": False,
+                                "dense_stage_silence_timeout_ms": 20000,
+                                "mt_silence_timeout_ms": 20000,
+                                "mt_max_duration_ms": 60000,
+                            }
+                        },
+                    },
+                )
+                rx_before_mt86 = stats.get("kvm_uart_rx_bytes", 0)
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-start2-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "ControlBootPlan",
+                        "arguments": {"action": "start"},
+                    },
+                )
+
+                # Wait until S1 enters `mt` phase AND real `mt86plus.efi` streams serial output from KVM RAM!
+                async def _in_real_mt86():
+                    st = await ws.call("GetStation", {"station_id": "S1"})
+                    if st.get("phase") == "mt" and stats.get("kvm_uart_rx_bytes", 0) > rx_before_mt86 + 250:
+                        return st
+                    return None
+
+                await wait_until(_in_real_mt86, timeout_s=30.0, desc="Real mt86plus.efi active on KVM guest")
+                await asyncio.sleep(0.8)  # Let mt86plus.efi render initial test progress lines
+
+                # Tighten MT silence watchdog to 2.5s and freeze physical KVM vCPU via QMP `stop`!
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-wd2b-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "ConfigureWatchdog",
+                        "arguments": {"watchdog": {"mt_silence_timeout_ms": 2500}},
+                    },
+                )
+                await qmp.execute("stop")
+                q_frozen = await qmp.execute("query-status")
+                assert q_frozen.get("status") == "paused", f"Expected QMP status=paused, got {q_frozen}"
+
+                st_hang = await wait_until(
+                    lambda: _station_terminal(ws, "S1"),
+                    timeout_s=12.0,
+                    desc="Watchdog catching real KVM vCPU freeze",
+                )
+                assert st_hang["task_status"] == "failed", f"Expected failed on KVM freeze, got {st_hang}"
+                assert st_hang.get("fault_code") == "stage_hang_timeout", f"Expected stage_hang_timeout, got {st_hang}"
+                assert st_hang.get("hang_scene_preserved") is True
+
+                # Confirm Level-1 preserved the exact paused KVM vCPU state (no QMP reset issued!)
+                await asyncio.sleep(1.0)
+                q_still_paused = await qmp.execute("query-status")
+                assert q_still_paused.get("status") == "paused", f"Level-1 MUST preserve paused KVM vCPU, got {q_still_paused}"
+                await wait_until(
+                    lambda: hood.snapshot().get("purge_cool_count", 0) >= 1 and hood.cooling_purge is True,
+                    timeout_s=5.0,
+                    desc="6400 Hood 0x08 00 cooling purge on KVM vCPU freeze",
+                )
+                results.append({"scenario": "2_kvm_real_mt86plus_qmp_vcpu_hang_and_hood_purge", "status": "PASS"})
+                print("      -> PASS", flush=True)
+
+                # ============================================================
+                # Scenario 3: Real IPMI RMCP+ `StationPower: host_reset` -> QMP Reboot Recovery
+                # ============================================================
+                print("[Tier3][3/3] Issuing real IPMI RMCP+ `host_reset` -> QMP `cont` + `system_reset` -> OVMF Shell recovery...", flush=True)
+                rx_before_rst = stats.get("kvm_uart_rx_bytes", 0)
+                stats["tail_text"] = ""
+                await ws.call(
+                    "EnqueueCommand",
+                    {
+                        "command_id": f"kvm-rst-{uuid.uuid4().hex[:8]}",
+                        "station_id": "S1",
+                        "method": "StationPower",
+                        "arguments": {"action": "host_reset"},
+                    },
+                )
+
+                async def _kvm_rebooted_to_shell():
+                    qst = await qmp.execute("query-status")
+                    if not qst.get("running"):
+                        return None
+                    tail = stats.get("tail_text", "")
+                    if (
+                        stats.get("kvm_uart_rx_bytes", 0) > rx_before_rst + 300
+                        and "STOP_RMT_N0" in tail
+                        and ("FS0:" in tail or "Shell>" in tail or "UEFI Interactive Shell" in tail)
+                    ):
+                        return True
+                    return None
+
+                await wait_until(_kvm_rebooted_to_shell, timeout_s=25.0, desc="KVM OVMF rebooted back to UEFI Shell")
+                results.append({"scenario": "3_ipmi_rmcp_to_qmp_reset_recovery", "status": "PASS"})
+                print("      -> PASS", flush=True)
+            finally:
+                await ws.close()
+
+        elapsed_s = round(time.monotonic() - t0, 2)
+        summary = {"tier": "Tier3_KVM_OVMF_UEFI_mt86plus_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
+        print(f"\n[Tier3] ALL 3 REAL KVM + OVMF + mt86plus.efi SCENARIOS PASSED in {elapsed_s}s!", flush=True)
+        return summary
+
+    finally:
+        if bridge_task:
+            bridge_task.cancel()
+        if hood_task:
+            hood_task.cancel()
+        if hood:
+            hood.close()
+        await qmp.close()
+        for proc in (server_proc, bmc_proc, ssh_tunnel_proc):
+            if proc and proc.poll() is None:
+                with contextlib.suppress(Exception):
+                    proc.terminate()
+                    proc.wait(timeout=3.0)
+                if proc.poll() is None:
+                    with contextlib.suppress(Exception):
+                        proc.kill()
+        with contextlib.suppress(Exception):
+            subprocess.run(
+                [
+                    "ssh",
+                    "-o", "BatchMode=yes",
+                    f"{REMOTE_USER}@{REMOTE_HOST}",
+                    f"podman rm -f {cname} >/dev/null 2>&1 || true; rm -rf {remote_dir}",
+                ],
+                timeout=10,
+                capture_output=True,
+            )
+        shutil.rmtree(local_tmp, ignore_errors=True)
+
+
+async def _http_ok(http: aiohttp.ClientSession, url: str) -> bool:
+    try:
+        async with http.get(url, timeout=aiohttp.ClientTimeout(total=1.0)) as r:
+            return r.status == 200
+    except Exception:
+        return False
+
+
+async def _station_online(ws: WsRpcClient, sid: str) -> Any:
+    st = await ws.call("GetStation", {"station_id": sid})
+    return st if st.get("bmc_state") == "online" and st.get("console_online") is True else None
+
+
+async def _station_terminal(ws: WsRpcClient, sid: str) -> Any:
+    st = await ws.call("GetStation", {"station_id": sid})
+    return st if st.get("task_status") in ("completed", "failed") else None
+
+
+async def _thermal_online(ws: WsRpcClient, sid: str) -> Any:
+    snap = await ws.call("GetThermalConsole", {"station_id": sid})
+    return snap if (snap.get("mcu") or {}).get("online") else None
+
+
+if __name__ == "__main__":
+    res = asyncio.run(run_tier3_kvm_suite())
+    out_file = ROOT_DIR / "build" / "sim" / "tier3_kvm_uefi_report.json"
+    out_file.parent.mkdir(parents=True, exist_ok=True)
+    out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")

+ 90 - 0
sim/qt_e2e/qt_hil_e2e_test.pro

@@ -0,0 +1,90 @@
+QT       += core gui widgets serialport websockets printsupport network testlib
+CONFIG   += c++11 testcase no_testcase_installs
+
+TARGET    = qt_hil_e2e_test
+TEMPLATE  = app
+
+ROOT_SRC  = $$PWD/../../src
+INCLUDEPATH += $$ROOT_SRC
+INCLUDEPATH += $$ROOT_SRC/3rdparty/qcustomplot
+INCLUDEPATH += $$ROOT_SRC/3rdparty/libxlsxwriter/include
+INCLUDEPATH += $$ROOT_SRC/3rdparty/libxlsxwriter/include/xlsxwriter
+INCLUDEPATH += $$ROOT_SRC/3rdparty/libxlsxwriter/src
+INCLUDEPATH += $$ROOT_SRC/3rdparty/libxlsxwriter/third_party/minizip
+INCLUDEPATH += $$ROOT_SRC/3rdparty/libxlsxwriter/third_party/tmpfileplus
+DEPENDPATH  += $$ROOT_SRC
+
+LIBS += -lz
+
+contains(QT_ARCH, x86_64) {
+    QMAKE_CFLAGS   += -march=x86-64 -mtune=generic
+    QMAKE_CXXFLAGS += -march=x86-64 -mtune=generic
+}
+
+SOURCES += \
+    tst_qt_hil_e2e.cpp \
+    $$ROOT_SRC/mainwindow.cpp \
+    $$ROOT_SRC/overviewview.cpp \
+    $$ROOT_SRC/detailview.cpp \
+    $$ROOT_SRC/createtaskdialog.cpp \
+    $$ROOT_SRC/powerbutton.cpp \
+    $$ROOT_SRC/stationdata.cpp \
+    $$ROOT_SRC/backendlink.cpp \
+    $$ROOT_SRC/localplans.cpp \
+    $$ROOT_SRC/comworker.cpp \
+    $$ROOT_SRC/sltproto.cpp \
+    $$ROOT_SRC/comanager.cpp \
+    $$ROOT_SRC/3rdparty/qcustomplot/qcustomplot.cpp \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/app.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/chart.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/chartsheet.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/comment.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/content_types.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/core.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/custom.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/drawing.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/format.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/hash_table.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/metadata.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/packager.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/relationships.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/rich_value.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/rich_value_rel.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/rich_value_structure.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/rich_value_types.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/shared_strings.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/styles.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/table.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/theme.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/utility.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/vml.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/workbook.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/worksheet.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/src/xmlwriter.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/third_party/md5/md5.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/third_party/minizip/ioapi.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/third_party/minizip/zip.c \
+    $$ROOT_SRC/3rdparty/libxlsxwriter/third_party/tmpfileplus/tmpfileplus.c
+
+HEADERS += \
+    $$ROOT_SRC/appconfig.h \
+    $$ROOT_SRC/mainwindow.h \
+    $$ROOT_SRC/overviewview.h \
+    $$ROOT_SRC/detailview.h \
+    $$ROOT_SRC/createtaskdialog.h \
+    $$ROOT_SRC/powerbutton.h \
+    $$ROOT_SRC/stationdata.h \
+    $$ROOT_SRC/backendlink.h \
+    $$ROOT_SRC/localplans.h \
+    $$ROOT_SRC/uiformat.h \
+    $$ROOT_SRC/comworker.h \
+    $$ROOT_SRC/sltproto.h \
+    $$ROOT_SRC/comanager.h \
+    $$ROOT_SRC/3rdparty/qcustomplot/qcustomplot.h
+
+FORMS += \
+    $$ROOT_SRC/mainwindow.ui \
+    $$ROOT_SRC/createtaskdialog.ui
+
+RESOURCES += \
+    $$ROOT_SRC/resources.qrc

+ 230 - 0
sim/qt_e2e/test_tier5_qt_xvfb_e2e.py

@@ -0,0 +1,230 @@
+#!/usr/bin/env python3
+"""
+test_tier5_qt_xvfb_e2e.py — Tier 5 Headless Xvfb Qt5 C++ Desktop Client Full-Stack HIL E2E
+
+Builds (if needed) and runs `qt_hil_e2e_test` (linking real `MainWindow`, `BackendLink`,
+`ComManager`, `ComWorker`, `StationStore`, `OverviewView`, `DetailView`, `SltProto`)
+under `xvfb-run -a` against live `stl_native_server` (`/ws?view=qt-clean`) + 4x `/dev/pts/*`
+6400 High-Temperature Hoods + 4-station C RMCP+/SSHv2 HIL cluster.
+"""
+
+import asyncio
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from typing import Any, Dict
+
+from aiohttp import web
+
+ROOT_DIR = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
+from cluster_harness import HilClusterStack  # noqa: E402
+
+QT_TEST_DIR = ROOT_DIR / "sim" / "qt_e2e"
+QT_BUILD_DIR = ROOT_DIR / "build" / "qt_e2e"
+QT_TEST_BIN = QT_BUILD_DIR / "qt_hil_e2e_test"
+
+
+def clean_qt_env() -> Dict[str, str]:
+    env = dict(os.environ)
+    for k in (
+        "LD_LIBRARY_PATH",
+        "QT_PLUGIN_PATH",
+        "QT_QPA_PLATFORM_PLUGIN_PATH",
+        "QT_QPA_PLATFORM",
+        "http_proxy",
+        "https_proxy",
+        "HTTP_PROXY",
+        "HTTPS_PROXY",
+        "all_proxy",
+        "ALL_PROXY",
+    ):
+        env.pop(k, None)
+    return env
+
+
+def build_qt_e2e_binary() -> None:
+    QT_BUILD_DIR.mkdir(parents=True, exist_ok=True)
+    env = clean_qt_env()
+    subprocess.run(
+        ["qmake", str(QT_TEST_DIR / "qt_hil_e2e_test.pro")],
+        cwd=str(QT_BUILD_DIR),
+        env=env,
+        check=True,
+    )
+    nproc = str(max(2, os.cpu_count() or 4))
+    subprocess.run(
+        ["make", f"-j{nproc}"],
+        cwd=str(QT_BUILD_DIR),
+        env=env,
+        check=True,
+    )
+
+
+async def run_tier5_qt_suite() -> Dict[str, Any]:
+    t0 = time.monotonic()
+    print("[Tier5] Building Qt5 C++ `qt_hil_e2e_test` binary...", flush=True)
+    await asyncio.to_thread(build_qt_e2e_binary)
+
+    qt_cfg_dir = Path(tempfile.mkdtemp(prefix="xjkj_stl_qt_cfg_"))
+    driver_port = 19498
+
+    try:
+        async with HilClusterStack(
+            web_port=18985,
+            tftp_port=19075,
+            bmc_ctrl_port=19399,
+            hil_http_port=19398,
+            uart_base=19340,
+            web_password="disabled",
+            speed_scale=0.22,
+            station_ips=["127.0.4.166", "127.0.4.165", "127.0.4.167", "127.0.4.168"],
+        ) as stack:
+            for sid in ("S1", "S2", "S3", "S4"):
+                await stack.wait_station_online(sid, timeout_s=15.0)
+
+            # Write isolated `config.json` & `port.json` for `MainWindow` via `STL_QT_CONFIG_DIR`
+            base_cfg = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
+            base_cfg["backend"] = {"url": f"ws://127.0.0.1:{stack.web_port}/ws?view=qt-clean"}
+            base_cfg.setdefault("memoryParams", {})["target_temp"] = 70
+            (qt_cfg_dir / "config.json").write_text(json.dumps(base_cfg, ensure_ascii=False, indent=2), encoding="utf-8")
+
+            port_cfg = {
+                "serialPorts": [
+                    {"port": pts, "serialNumber": "", "baud": 115200}
+                    for pts in stack.qt_hood_pts
+                ]
+            }
+            (qt_cfg_dir / "port.json").write_text(json.dumps(port_cfg, ensure_ascii=False, indent=2), encoding="utf-8")
+
+            # Tiny local HTTP driver allowing `tst_qt_hil_e2e.cpp` to trigger HIL scenarios deterministically
+            app = web.Application()
+
+            async def step_start_s1_normal(_req: web.Request) -> web.Response:
+                await stack.clear_hood_history(0)
+                # Slow RMT slightly (0.35) so Qt sees `training` -> `rmt` transition cleanly at 1Hz state push!
+                await stack.configure_dut(0, hang_stage="", hang_remaining_boots=0, speed_scale=0.35)
+                await stack.enqueue_cmd(
+                    "S1",
+                    "SaveBootPlan",
+                    {
+                        "plan": {
+                            "preset": "auto",
+                            "mt_enabled": True,
+                            "run_rmt": True,
+                            "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"},
+                        },
+                        "watchdog": {"dense_stage_silence_timeout_ms": 20000, "amt_silence_timeout_ms": 20000, "mt_silence_timeout_ms": 20000},
+                    },
+                )
+                await stack.enqueue_cmd(
+                    "S1",
+                    "SaveAmtSettings",
+                    {"settings": {"action": "skip", "exit_after": True}},
+                )
+                await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"})
+                return web.json_response({"ok": True})
+
+            async def step_start_s1_dual_drop(_req: web.Request) -> web.Response:
+                await stack.clear_hood_history(0)
+                await stack.configure_dut(0, hang_stage="", hang_remaining_boots=0, speed_scale=0.5)
+                await stack.enqueue_cmd(
+                    "S1",
+                    "ConfigureWatchdog",
+                    {"watchdog": {"link_lost_timeout_ms": 45000, "dense_stage_silence_timeout_ms": 40000}},
+                )
+                await stack.trigger_dut_boot(0, reason="qt_dual_drop")
+                await asyncio.sleep(0.3)
+                await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "start"})
+                await stack.set_link(0, bmc_up=False, serial_up=False)
+                return web.json_response({"ok": True})
+
+            async def step_restore_s1_links(_req: web.Request) -> web.Response:
+                await stack.set_link(0, bmc_up=True, serial_up=True)
+                return web.json_response({"ok": True})
+
+            async def step_start_s1_rmt_hang(_req: web.Request) -> web.Response:
+                await stack.wait_station_online("S1", timeout_s=12.0)
+                await stack.clear_hood_history(0)
+                await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.25)
+                await stack.enqueue_cmd(
+                    "S1",
+                    "SaveBootPlan",
+                    {
+                        "plan": {
+                            "preset": "auto",
+                            "mt_enabled": False,
+                            "run_rmt": True,
+                            "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"},
+                        },
+                        "watchdog": {"dense_stage_silence_timeout_ms": 2400, "reboot_on_hang": False},
+                    },
+                )
+                await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"})
+                return web.json_response({"ok": True})
+
+            async def step_qt_hood0_status(_req: web.Request) -> web.Response:
+                hs = await stack.hil_status()
+                return web.json_response(hs["qt_hoods"][0])
+
+            app.router.add_post("/step/start_s1_normal", step_start_s1_normal)
+            app.router.add_post("/step/start_s1_dual_drop", step_start_s1_dual_drop)
+            app.router.add_post("/step/restore_s1_links", step_restore_s1_links)
+            app.router.add_post("/step/start_s1_rmt_hang", step_start_s1_rmt_hang)
+            app.router.add_post("/step/qt_hood0_status", step_qt_hood0_status)
+
+            runner = web.AppRunner(app)
+            await runner.setup()
+            site = web.TCPSite(runner, "127.0.0.1", driver_port)
+            await site.start()
+
+            try:
+                print("[Tier5] Running `xvfb-run -a qt_hil_e2e_test` against live HIL cluster...", flush=True)
+                env = clean_qt_env()
+                env["STL_QT_CONFIG_DIR"] = str(qt_cfg_dir)
+                env["STL_QT_DRIVER_URL"] = f"http://127.0.0.1:{driver_port}"
+
+                proc = await asyncio.to_thread(
+                    subprocess.run,
+                    ["xvfb-run", "-a", str(QT_TEST_BIN), "-v2"],
+                    env=env,
+                    capture_output=True,
+                    text=True,
+                    timeout=150,
+                )
+                print(proc.stdout, flush=True)
+                if proc.returncode != 0:
+                    raise AssertionError(
+                        f"Qt5 Xvfb E2E failed (rc={proc.returncode}):\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
+                    )
+            finally:
+                await runner.cleanup()
+
+        elapsed_s = round(time.monotonic() - t0, 2)
+        summary = {
+            "tier": "Tier5_Headless_Xvfb_Qt5_Cpp_HIL_E2E",
+            "ok": True,
+            "elapsed_s": elapsed_s,
+            "tests": [
+                "test1_ConnectCleanWsAnd4PtsHoods",
+                "test2_PostTrainingSends0x01Heat70CAndPassPurge",
+                "test3_DualDisconnect5sGraceBadgeWithoutPremature0x08",
+                "test4_RmtHardHangTriggersQt0x08CoolingPurgeAndScenePreservedUi",
+            ],
+        }
+        print(f"\n[Tier5] ALL 4 HEADLESS XVFB QT5 C++ HIL SCENARIOS PASSED in {elapsed_s}s!", flush=True)
+        return summary
+    finally:
+        shutil.rmtree(qt_cfg_dir, ignore_errors=True)
+
+
+if __name__ == "__main__":
+    res = asyncio.run(run_tier5_qt_suite())
+    out_file = ROOT_DIR / "build" / "sim" / "tier5_qt_xvfb_report.json"
+    out_file.parent.mkdir(parents=True, exist_ok=True)
+    out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")

+ 173 - 0
sim/qt_e2e/tst_qt_hil_e2e.cpp

@@ -0,0 +1,173 @@
+// tst_qt_hil_e2e.cpp — Tier 5 Headless Xvfb Qt5 C++ Full-Stack HIL Integration Test
+//
+// Instantiates the real production `MainWindow` connected to:
+//   - Live `stl_native_server` (`/ws?view=qt-clean`)
+//   - 4x live `/dev/pts/N` 6400 High-Temperature Hood simulators via `ComManager` / `QSerialPort`
+//   - Live 4-station RMCP+ / SSHv2 HIL cluster orchestrated via HTTP test driver
+
+#include <QtTest/QtTest>
+#include <QEventLoop>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLabel>
+#include <QNetworkAccessManager>
+#include <QNetworkProxy>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QUrl>
+
+#include "mainwindow.h"
+#include "stationdata.h"
+
+class QtHilE2ETest : public QObject
+{
+    Q_OBJECT
+
+private:
+    MainWindow *m_win = nullptr;
+    QNetworkAccessManager m_nam;
+    QString m_driverBase;
+
+    void callDriver(const QString &path, QJsonObject &out, int timeoutMs = 20000)
+    {
+        out = QJsonObject();
+        QNetworkRequest req(QUrl(m_driverBase + path));
+        req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
+        QNetworkReply *rep = m_nam.post(req, QByteArray("{}"));
+        QEventLoop loop;
+        QTimer timer;
+        timer.setSingleShot(true);
+        connect(rep, &QNetworkReply::finished, &loop, &QEventLoop::quit);
+        connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
+        timer.start(timeoutMs);
+        loop.exec();
+        QVERIFY2(rep->isFinished(), qPrintable(QStringLiteral("Driver HTTP timeout on ") + path));
+        QVERIFY2(rep->error() == QNetworkReply::NoError, qPrintable(rep->errorString()));
+        const QByteArray raw = rep->readAll();
+        rep->deleteLater();
+        out = QJsonDocument::fromJson(raw).object();
+    }
+
+    bool anyLabelContains(const QString &needle) const
+    {
+        if (!m_win)
+            return false;
+        const QList<QLabel *> labels = m_win->findChildren<QLabel *>();
+        for (QLabel *lbl : labels) {
+            if (lbl && lbl->text().contains(needle))
+                return true;
+        }
+        return false;
+    }
+
+private slots:
+    void initTestCase()
+    {
+        QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
+        m_driverBase = qEnvironmentVariable("STL_QT_DRIVER_URL", QStringLiteral("http://127.0.0.1:19498"));
+        m_win = new MainWindow();
+        m_win->resize(1600, 960);
+        m_win->show();
+        QVERIFY(QTest::qWaitForWindowExposed(m_win));
+    }
+
+    void cleanupTestCase()
+    {
+        delete m_win;
+        m_win = nullptr;
+    }
+
+    void test1_ConnectCleanWsAnd4PtsHoods()
+    {
+        QVERIFY(m_win && m_win->store());
+        QTRY_VERIFY_WITH_TIMEOUT(
+            m_win->store()->station(0).connection == QLatin1String("online")
+            && m_win->store()->station(0).currentTemp > 20.0
+            && m_win->store()->station(1).currentTemp > 20.0,
+            15000);
+    }
+
+    void test2_PostTrainingSends0x01Heat70CAndPassPurge()
+    {
+        QJsonObject startRes;
+        callDriver(QStringLiteral("/step/start_s1_normal"), startRes);
+        QVERIFY(startRes.value(QStringLiteral("ok")).toBool());
+
+        QTRY_VERIFY_WITH_TIMEOUT(
+            m_win->store()->station(0).taskStatus == QLatin1String("completed")
+            && m_win->store()->station(0).verdict == QLatin1String("pass"),
+            35000);
+
+        bool hoodOk = false;
+        for (int tries = 0; tries < 25 && !hoodOk; ++tries) {
+            QTest::qWait(200);
+            QJsonObject hs;
+            callDriver(QStringLiteral("/step/qt_hood0_status"), hs);
+            if (hs.value(QStringLiteral("heat_cmd_count")).toInt() >= 1
+                && hs.value(QStringLiteral("purge_cool_count")).toInt() >= 1) {
+                hoodOk = true;
+            }
+        }
+        QVERIFY2(hoodOk, "Qt MainWindow must send 0x01 (70C) post-training and 0x08 00 cooling purge on completion");
+    }
+
+    void test3_DualDisconnect5sGraceBadgeWithoutPremature0x08()
+    {
+        QJsonObject dropRes;
+        callDriver(QStringLiteral("/step/start_s1_dual_drop"), dropRes);
+        QVERIFY(dropRes.value(QStringLiteral("ok")).toBool());
+
+        QTRY_COMPARE_WITH_TIMEOUT(
+            m_win->store()->station(0).observedDetail,
+            QStringLiteral("link_offline_waiting"),
+            35000);
+
+        QTRY_VERIFY_WITH_TIMEOUT(anyLabelContains(QStringLiteral("双断保护")), 3000);
+
+        QJsonObject hsDuring;
+        callDriver(QStringLiteral("/step/qt_hood0_status"), hsDuring);
+        QCOMPARE(hsDuring.value(QStringLiteral("purge_cool_count")).toInt(), 0);
+
+        QJsonObject recRes;
+        callDriver(QStringLiteral("/step/restore_s1_links"), recRes);
+        QVERIFY(recRes.value(QStringLiteral("ok")).toBool());
+        QTRY_VERIFY_WITH_TIMEOUT(m_win->store()->station(0).serialGapDetected, 15000);
+    }
+
+    void test4_RmtHardHangTriggersQt0x08CoolingPurgeAndScenePreservedUi()
+    {
+        QJsonObject hangRes;
+        callDriver(QStringLiteral("/step/start_s1_rmt_hang"), hangRes);
+        QVERIFY(hangRes.value(QStringLiteral("ok")).toBool());
+
+        QTRY_COMPARE_WITH_TIMEOUT(
+            m_win->store()->station(0).faultCode,
+            QStringLiteral("stage_hang_timeout"),
+            28000);
+        QCOMPARE(m_win->store()->station(0).taskStatus, QStringLiteral("failed"));
+        QVERIFY(m_win->store()->station(0).hangScenePreserved);
+        QVERIFY(m_win->store()->station(0).backendEndedMs > 0);
+
+        const qint64 frozenElapsed = m_win->store()->runtimeMs(0);
+        QTest::qWait(1100);
+        QCOMPARE(m_win->store()->runtimeMs(0), frozenElapsed);
+
+        QTRY_VERIFY_WITH_TIMEOUT(anyLabelContains(QStringLiteral("卡死超时 FAIL")), 3000);
+
+        bool purged = false;
+        for (int tries = 0; tries < 25 && !purged; ++tries) {
+            QTest::qWait(200);
+            QJsonObject hs;
+            callDriver(QStringLiteral("/step/qt_hood0_status"), hs);
+            if (hs.value(QStringLiteral("heat_cmd_count")).toInt() >= 1
+                && hs.value(QStringLiteral("purge_cool_count")).toInt() >= 1
+                && hs.value(QStringLiteral("cooling_purge")).toBool()) {
+                purged = true;
+            }
+        }
+        QVERIFY2(purged, "Qt MainWindow must immediately transmit AA 55 08 01 00 D8 cooling purge to 6400 Hood on RMT hang!");
+    }
+};
+
+QTEST_MAIN(QtHilE2ETest)
+#include "tst_qt_hil_e2e.moc"

+ 230 - 0
sim/run_all_tiers.py

@@ -0,0 +1,230 @@
+#!/usr/bin/env python3
+"""
+run_all_tiers.py — XJKJ-STL Five-Tier Full-Stack Simulation & Verification Master Runner
+
+Executes all 5 simulation & verification tiers end-to-end and generates an aggregated
+JSON audit report at `build/sim/full_sim_report.json`:
+
+  - Tier 1: Native Kernel / Actor / Watchdog Unit & Integration Suite (`stl_native_tests` 28 tests)
+            + `bmc_ssh_hil_sim` C RMCP+/SSHv2 Kernel Smoke Test + `web/*.js` Syntax Check
+            + Production `DDR5_SLT_Monitor` Qt5 Binary Build Verification
+  - Tier 2: 4-Station Hardware-in-the-Loop (HIL) Full-Stack E2E (`bmc_ssh_hil_sim` UDP :623 RMCP+
+            Cipher Suite 17 + 24-ch SDR + SSHv2 :2200 + UDP TFTP WRQ + `/dev/pts/*` 6400 Hood v1.1
+            + Official `tools/validate_qt_clean.py` Protocol & Privacy Validator)
+  - Tier 3: Real Hardware KVM (`/dev/kvm` on `192.168.2.25`) + EDK2 OVMF UEFI + Real `mt86plus.efi`
+            + QMP Hardware vCPU Freeze & IPMI-to-QMP Reset E2E
+  - Tier 4: Real Headless Chrome 156 CDP Web Frontend E2E (Login, Watchdog Config, Live Banners, G27 Fix)
+  - Tier 5: Real Headless Xvfb Qt5 C++ Desktop Client (`MainWindow` + `QSerialPort` `/dev/pts/*` 6400 Hoods)
+"""
+
+import argparse
+import datetime as dt
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+from typing import Any, Dict, List
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+PY_BIN = "/opt/prod2u/venv/bin/python3" if os.path.exists("/opt/prod2u/venv/bin/python3") else sys.executable
+
+
+def clean_env() -> Dict[str, str]:
+    env = dict(os.environ)
+    for k in (
+        "LD_LIBRARY_PATH",
+        "QT_PLUGIN_PATH",
+        "QT_QPA_PLATFORM_PLUGIN_PATH",
+        "QT_QPA_PLATFORM",
+        "http_proxy",
+        "https_proxy",
+        "HTTP_PROXY",
+        "HTTPS_PROXY",
+        "all_proxy",
+        "ALL_PROXY",
+    ):
+        env.pop(k, None)
+    return env
+
+
+def run_step(name: str, cmd: List[str], cwd: Path = ROOT_DIR, timeout_s: int = 300) -> Dict[str, Any]:
+    print(f"\n{'=' * 78}\n>>> RUNNING {name}\n    CMD: {' '.join(cmd)}\n{'=' * 78}", flush=True)
+    t0 = time.monotonic()
+    proc = subprocess.run(
+        cmd,
+        cwd=str(cwd),
+        env=clean_env(),
+        text=True,
+        capture_output=True,
+        timeout=timeout_s,
+    )
+    elapsed = round(time.monotonic() - t0, 2)
+    if proc.stdout:
+        print(proc.stdout.rstrip(), flush=True)
+    if proc.returncode != 0:
+        if proc.stderr:
+            print(proc.stderr.rstrip(), file=sys.stderr, flush=True)
+        raise RuntimeError(f"{name} FAILED with exit code {proc.returncode} after {elapsed}s")
+    print(f"<<< {name} PASSED in {elapsed}s", flush=True)
+    return {"name": name, "ok": True, "elapsed_s": elapsed}
+
+
+def run_tier1(skip_native_rebuild: bool = False) -> Dict[str, Any]:
+    t0 = time.monotonic()
+    sub = []
+    # 1a. Full native C/Zig/ASM/re2c/Rust server + 28 unit/integration tests
+    if skip_native_rebuild and (ROOT_DIR / "build" / "native" / "stl_native_tests").is_file():
+        sub.append(
+            run_step(
+                "Tier1.1 Native 28 Rust/C/Zig/ASM Tests",
+                [str(ROOT_DIR / "build" / "native" / "stl_native_tests")],
+                cwd=ROOT_DIR,
+                timeout_s=180,
+            )
+        )
+    else:
+        sub.append(
+            run_step(
+                "Tier1.1 Native Build & 28 Rust/C/Zig/ASM Tests",
+                ["bash", str(ROOT_DIR / "native" / "stl_accel" / "build.sh")],
+                cwd=ROOT_DIR,
+                timeout_s=420,
+            )
+        )
+
+    # 1b. Compile C HIL BMC RMCP+/SSHv2 daemon + direct `libstl_kernels.a` smoke test
+    build_sim = ROOT_DIR / "build" / "sim"
+    build_sim.mkdir(parents=True, exist_ok=True)
+    bmc_sim_bin = build_sim / "bmc_ssh_hil_sim"
+    smoke_bin = build_sim / "smoke_test_bmc_ssh"
+
+    sub.append(
+        run_step(
+            "Tier1.2a Compile bmc_ssh_hil_sim & smoke_test_bmc_ssh",
+            [
+                "gcc",
+                "-O2",
+                "-Wall",
+                "-Wextra",
+                str(ROOT_DIR / "sim" / "hil_cluster" / "bmc_ssh_hil_sim.c"),
+                "-o",
+                str(bmc_sim_bin),
+                "-lfreeipmi",
+                "-lssh",
+                "-lcrypto",
+                "-lpthread",
+            ],
+            cwd=ROOT_DIR,
+            timeout_s=60,
+        )
+    )
+    run_step(
+        "Tier1.2b Link smoke_test_bmc_ssh against libstl_kernels.a",
+        [
+            "gcc",
+            "-O2",
+            "-Wall",
+            "-Wextra",
+            str(ROOT_DIR / "sim" / "hil_cluster" / "smoke_test_bmc_ssh.c"),
+            f"-L{ROOT_DIR / 'build' / 'native'}",
+            "-lstl_kernels",
+            "-lfreeipmi",
+            "-lipmiconsole",
+            "-lssh",
+            "-lutil",
+            "-ldl",
+            "-lpthread",
+            "-o",
+            str(smoke_bin),
+        ],
+        cwd=ROOT_DIR,
+        timeout_s=60,
+    )
+
+    t_smk = time.monotonic()
+    print(f"\n{'=' * 78}\n>>> RUNNING Tier1.2c Execute Kernel RMCP+/SSHv2 Smoke Test\n{'=' * 78}", flush=True)
+    sim_proc = subprocess.Popen(
+        [
+            str(bmc_sim_bin),
+            "--ctrl-port", "19199",
+            "--uart-base", "19200",
+            "--ipmi-port", "623",
+            "--ssh-port", "2200",
+            "--probe22-port", "0",
+            "127.0.2.166",
+        ],
+        cwd=str(ROOT_DIR),
+        env=clean_env(),
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        text=True,
+    )
+    try:
+        time.sleep(0.5)
+        sub.append(
+            run_step(
+                "Tier1.2c Execute Kernel RMCP+/SSHv2 Smoke Test",
+                [str(smoke_bin), "127.0.2.166", "19200"],
+                cwd=ROOT_DIR,
+                timeout_s=30,
+            )
+        )
+    finally:
+        sim_proc.terminate()
+        try:
+            sim_proc.wait(timeout=3.0)
+        except Exception:
+            sim_proc.kill()
+    _ = t_smk
+
+    # 1c. Web JS syntax check across all frontend modules
+    js_files = sorted((ROOT_DIR / "web").glob("*.js"))
+    assert js_files, "No web/*.js files found"
+    for jf in js_files:
+        run_step(f"Tier1.3 JS Syntax Check ({jf.name})", ["node", "--check", str(jf)], cwd=ROOT_DIR, timeout_s=30)
+    sub.append({"name": f"Tier1.3 Web Frontend JS Syntax ({len(js_files)} files)", "ok": True, "elapsed_s": 0.0})
+
+    # 1d. Production Qt5 desktop client binary build check
+    qt_build = ROOT_DIR / "build" / "qt"
+    qt_build.mkdir(parents=True, exist_ok=True)
+    run_step("Tier1.4a qmake DDR5_SLT_Monitor.pro", ["qmake", str(ROOT_DIR / "DDR5_SLT_Monitor.pro")], cwd=qt_build, timeout_s=60)
+    nproc = str(max(2, os.cpu_count() or 4))
+    sub.append(run_step("Tier1.4b make DDR5_SLT_Monitor", ["make", f"-j{nproc}"], cwd=qt_build, timeout_s=180))
+
+    return {"tier": "Tier1_Build_And_Native_Unit_Suite", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2), "steps": sub}
+
+
+def main() -> None:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--skip-kvm", action="store_true", help="Skip Tier 3 remote 192.168.2.25 KVM tier")
+    parser.add_argument("--skip-native-rebuild", action="store_true", help="Run prebuilt stl_native_tests directly instead of full build.sh")
+    args = parser.parse_args()
+
+    t_all = time.monotonic()
+    tiers: List[Dict[str, Any]] = []
+
+    tiers.append(run_tier1(skip_native_rebuild=args.skip_native_rebuild))
+    tiers.append(run_step("Tier2 4-Station HIL Full-Stack E2E", [PY_BIN, str(ROOT_DIR / "sim" / "hil_cluster" / "test_tier2_hil_e2e.py")], timeout_s=360))
+    if not args.skip_kvm:
+        tiers.append(run_step("Tier3 Real KVM + OVMF UEFI + mt86plus.efi E2E", [PY_BIN, str(ROOT_DIR / "sim" / "kvm_uefi_tier" / "test_tier3_kvm_uefi_e2e.py")], timeout_s=300))
+    tiers.append(run_step("Tier4 Headless Chrome 156 CDP Web E2E", [PY_BIN, str(ROOT_DIR / "sim" / "web_e2e" / "test_tier4_chrome_web_e2e.py")], timeout_s=300))
+    tiers.append(run_step("Tier5 Headless Xvfb Qt5 C++ Client E2E", [PY_BIN, str(ROOT_DIR / "sim" / "qt_e2e" / "test_tier5_qt_xvfb_e2e.py")], timeout_s=300))
+
+    total_s = round(time.monotonic() - t_all, 2)
+    report = {
+        "schema": "xjkj-stl-5tier-full-sim-v1",
+        "completed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
+        "all_passed": True,
+        "total_elapsed_s": total_s,
+        "tiers": tiers,
+    }
+    out_path = ROOT_DIR / "build" / "sim" / "full_sim_report.json"
+    out_path.parent.mkdir(parents=True, exist_ok=True)
+    out_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+    print(f"\n{'#' * 78}\nALL {len(tiers)} SIMULATION & VERIFICATION TIERS PASSED 100% in {total_s}s!\nReport: {out_path}\n{'#' * 78}", flush=True)
+
+
+if __name__ == "__main__":
+    main()

+ 394 - 0
sim/web_e2e/test_tier4_chrome_web_e2e.py

@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+"""
+test_tier4_chrome_web_e2e.py — Tier 4 Real Headless Chrome 156 CDP Web Frontend E2E
+
+Drives real Chromium 156 (`/root/.cache/puppeteer/chrome/linux-156.0.8078.47/chrome-linux64/chrome`)
+over Chrome DevTools Protocol (CDP WebSocket) against live `stl_native_server` + HIL cluster:
+  1. Real password login (`#login-form`, `xjkj123456!`) & workbench initialization (0 JS exceptions)
+  2. Tab 5 Watchdog settings UI (`#wd-link-lost-s`, `#wd-dense-silence-s`, `#btn-save-watchdog`)
+     persisting via `ConfigureWatchdog` RPC to `stl_native_server`
+  3. Live Overview DOM alerting during >5s dual-disconnect (`#watchdog-alert-banner`
+     `dataset.alertKind == "link_offline_waiting"`) -> recovery (`dataset.alertKind == "serial_gap_detected"`)
+  4. Live RMT hard-hang DOM alerting (`dataset.alertKind == "stage_hang_timeout"`,
+     scene-preserved & `0x08 00` cooling badges, AND G27 fix keeping `#dimm-replacement-banner` visible)
+"""
+
+import asyncio
+import contextlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from typing import Any, Callable, Dict, List, Optional
+
+import aiohttp
+
+ROOT_DIR = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
+from cluster_harness import HilClusterStack  # noqa: E402
+
+CHROME_CANDIDATES = [
+    "/root/.cache/puppeteer/chrome/linux-156.0.8078.47/chrome-linux64/chrome",
+    shutil.which("google-chrome") or "",
+    shutil.which("chromium") or "",
+    shutil.which("chromium-browser") or "",
+]
+
+
+def find_chrome_binary() -> str:
+    for c in CHROME_CANDIDATES:
+        if c and os.path.isfile(c) and os.access(c, os.X_OK):
+            return c
+    raise FileNotFoundError("Headless Chrome binary not found")
+
+
+async def wait_until(
+    pred: Callable[[], Any],
+    timeout_s: float = 25.0,
+    interval_s: float = 0.25,
+    desc: str = "condition",
+) -> Any:
+    deadline = time.monotonic() + timeout_s
+    last_val = None
+    while time.monotonic() < deadline:
+        res = pred()
+        if asyncio.iscoroutine(res):
+            res = await res
+        last_val = res
+        if res:
+            return res
+        await asyncio.sleep(interval_s)
+    raise AssertionError(f"Timed out ({timeout_s}s) waiting for {desc}; last={last_val}")
+
+
+class CdpPageClient:
+    """Lightweight async Chrome DevTools Protocol (CDP) page controller over `aiohttp`."""
+
+    def __init__(self, http: aiohttp.ClientSession, debug_port: int):
+        self.http = http
+        self.debug_port = debug_port
+        self.ws: Optional[aiohttp.ClientWebSocketResponse] = None
+        self.reader_task: Optional[asyncio.Task] = None
+        self.seq = 0
+        self.pending: Dict[int, asyncio.Future] = {}
+        self.js_exceptions: List[str] = []
+
+    async def connect_first_page(self, target_url: str, timeout_s: float = 12.0) -> None:
+        deadline = time.monotonic() + timeout_s
+        ws_url = ""
+        while time.monotonic() < deadline:
+            try:
+                async with self.http.put(
+                    f"http://127.0.0.1:{self.debug_port}/json/new?{target_url}",
+                    timeout=aiohttp.ClientTimeout(total=2.0),
+                ) as r:
+                    if r.status == 200:
+                        info = await r.json()
+                        ws_url = info.get("webSocketDebuggerUrl", "")
+                        if ws_url:
+                            break
+            except Exception:
+                pass
+            await asyncio.sleep(0.2)
+        if not ws_url:
+            raise TimeoutError("Failed to open CDP page target")
+
+        self.ws = await self.http.ws_connect(ws_url, max_msg_size=16 * 1024 * 1024)
+        self.reader_task = asyncio.create_task(self._read_loop())
+        await self.send("Page.enable")
+        await self.send("Runtime.enable")
+
+    async def _read_loop(self) -> None:
+        assert self.ws is not None
+        try:
+            async for msg in self.ws:
+                if msg.type != aiohttp.WSMsgType.TEXT:
+                    continue
+                data = json.loads(msg.data)
+                if "id" in data and data["id"] in self.pending:
+                    fut = self.pending.pop(data["id"])
+                    if not fut.done():
+                        fut.set_result(data)
+                elif data.get("method") == "Runtime.exceptionThrown":
+                    details = (data.get("params") or {}).get("exceptionDetails") or {}
+                    self.js_exceptions.append(json.dumps(details, ensure_ascii=False))
+        except Exception as exc:
+            for fut in self.pending.values():
+                if not fut.done():
+                    fut.set_exception(exc)
+
+    async def send(self, method: str, params: Optional[Dict[str, Any]] = None, timeout: float = 10.0) -> Dict[str, Any]:
+        assert self.ws is not None
+        self.seq += 1
+        cid = self.seq
+        fut = asyncio.get_running_loop().create_future()
+        self.pending[cid] = fut
+        await self.ws.send_json({"id": cid, "method": method, "params": params or {}})
+        try:
+            resp = await asyncio.wait_for(fut, timeout=timeout)
+        finally:
+            self.pending.pop(cid, None)
+        if "error" in resp:
+            raise RuntimeError(f"CDP {method} error: {resp['error']}")
+        return resp.get("result") or {}
+
+    async def eval_js(self, expression: str) -> Any:
+        res = await self.send(
+            "Runtime.evaluate",
+            {"expression": expression, "returnByValue": True, "awaitPromise": True},
+        )
+        if "exceptionDetails" in res:
+            raise RuntimeError(f"JS eval exception: {res['exceptionDetails']}")
+        return (res.get("result") or {}).get("value")
+
+    async def close(self) -> None:
+        if self.ws is not None:
+            with contextlib.suppress(Exception):
+                await self.ws.close()
+        if self.reader_task is not None:
+            self.reader_task.cancel()
+            with contextlib.suppress(asyncio.CancelledError, Exception):
+                await self.reader_task
+
+
+async def run_tier4_web_suite() -> Dict[str, Any]:
+    t0 = time.monotonic()
+    chrome_bin = find_chrome_binary()
+    cdp_port = 19322
+    user_data_dir = Path(tempfile.mkdtemp(prefix="xjkj_stl_chrome_"))
+    chrome_proc: Optional[subprocess.Popen] = None
+    results = []
+
+    try:
+        async with HilClusterStack(
+            web_port=18984,
+            tftp_port=19074,
+            bmc_ctrl_port=19299,
+            hil_http_port=19298,
+            uart_base=19240,
+            web_password="xjkj123456!",
+            speed_scale=0.18,
+            station_ips=["127.0.3.166", "127.0.3.165", "127.0.3.167", "127.0.3.168"],
+        ) as stack:
+            assert stack.admin_ws is not None
+            assert stack.http_session is not None
+            await stack.wait_station_online("S1", timeout_s=15.0)
+
+            env = dict(os.environ)
+            for k in (
+                "LD_LIBRARY_PATH",
+                "http_proxy",
+                "https_proxy",
+                "HTTP_PROXY",
+                "HTTPS_PROXY",
+                "all_proxy",
+                "ALL_PROXY",
+            ):
+                env.pop(k, None)
+            chrome_proc = subprocess.Popen(
+                [
+                    chrome_bin,
+                    "--headless=new",
+                    "--no-sandbox",
+                    "--no-proxy-server",
+                    "--disable-gpu",
+                    "--disable-dev-shm-usage",
+                    "--no-first-run",
+                    "--window-size=1600,1080",
+                    f"--user-data-dir={user_data_dir}",
+                    f"--remote-debugging-port={cdp_port}",
+                    "about:blank",
+                ],
+                stdout=subprocess.DEVNULL,
+                stderr=subprocess.PIPE,
+                env=env,
+            )
+
+            cdp = CdpPageClient(stack.http_session, cdp_port)
+            await cdp.connect_first_page(f"http://127.0.0.1:{stack.web_port}/")
+
+            try:
+                # ============================================================
+                # Scenario 1: Real Web Login Flow (`#login-form` -> Workbench)
+                # ============================================================
+                print("[Tier4][1/4] Verifying Chrome 156 password login gate & live workbench initialization...", flush=True)
+                await wait_until(
+                    lambda: cdp.eval_js("!!document.getElementById('admin-password')"),
+                    timeout_s=10.0,
+                    desc="Login page #admin-password",
+                )
+                await cdp.eval_js(
+                    """(() => {
+                        const inp = document.getElementById('admin-password');
+                        inp.value = 'xjkj123456!';
+                        document.getElementById('login-form').requestSubmit();
+                        return true;
+                    })()"""
+                )
+                await wait_until(
+                    lambda: cdp.eval_js("!!document.getElementById('watchdog-alert-banner') && document.querySelectorAll('#cpu0-grid .dimm-slot').length === 12"),
+                    timeout_s=15.0,
+                    desc="Main workbench loaded with 24 DIMM slots",
+                )
+                assert not cdp.js_exceptions, f"Unexpected JS exceptions after login: {cdp.js_exceptions}"
+                results.append({"scenario": "1_chrome_login_and_workbench_boot", "status": "PASS"})
+                print("      -> PASS", flush=True)
+
+                # ============================================================
+                # Scenario 2: Tab 5 Watchdog Settings Panel -> `ConfigureWatchdog`
+                # ============================================================
+                print("[Tier4][2/4] Verifying Tab 5 Watchdog settings UI & persistence in Chrome...", flush=True)
+                await cdp.eval_js(
+                    """(() => {
+                        const tabBtn = document.querySelector('[data-page="plans"], [data-nav-page="plans"]');
+                        if (tabBtn) tabBtn.click();
+                        return !!tabBtn;
+                    })()"""
+                )
+                await wait_until(
+                    lambda: cdp.eval_js("!!document.getElementById('btn-save-watchdog')"),
+                    timeout_s=8.0,
+                    desc="#btn-save-watchdog present",
+                )
+                await cdp.eval_js(
+                    """(() => {
+                        document.getElementById('wd-link-lost-s').value = '180';
+                        document.getElementById('wd-dense-silence-s').value = '95';
+                        document.getElementById('wd-reboot-on-hang').checked = true;
+                        document.getElementById('wd-max-hangs').value = '3';
+                        document.getElementById('btn-save-watchdog').click();
+                        return true;
+                    })()"""
+                )
+
+                async def _wd_persisted():
+                    ctrl = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
+                    wd = ctrl.get("watchdog") or {}
+                    return wd if wd.get("link_lost_timeout_ms") == 180000 and wd.get("dense_stage_silence_timeout_ms") == 95000 and wd.get("max_consecutive_hangs") == 3 else None
+
+                await wait_until(_wd_persisted, timeout_s=8.0, desc="Watchdog config persisted via Web UI")
+                # Switch back to Overview tab (`overview`)
+                await cdp.eval_js(
+                    """(() => {
+                        const ovBtn = document.querySelector('[data-page="overview"], [data-nav-page="overview"]');
+                        if (ovBtn) ovBtn.click();
+                        return true;
+                    })()"""
+                )
+                results.append({"scenario": "2_tab5_watchdog_config_save", "status": "PASS"})
+                print("      -> PASS", flush=True)
+
+                # ============================================================
+                # Scenario 3: Live `link_offline_waiting` -> `serial_gap_detected` Banner in Chrome
+                # ============================================================
+                print("[Tier4][3/4] Verifying live `link_offline_waiting` & `serial_gap_detected` banners in Chrome DOM...", flush=True)
+                await stack.enqueue_cmd(
+                    "S1",
+                    "ConfigureWatchdog",
+                    {"watchdog": {"link_lost_timeout_ms": 45000, "dense_stage_silence_timeout_ms": 40000, "reboot_on_hang": False}},
+                )
+                await stack.trigger_dut_boot(0, reason="tier4_dual_drop")
+                await asyncio.sleep(0.3)
+                await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "start"})
+                await stack.set_link(0, bmc_up=False, serial_up=False)
+
+                async def _dom_link_waiting():
+                    return await cdp.eval_js(
+                        """(() => {
+                            const b = document.getElementById('watchdog-alert-banner');
+                            if (!b || b.classList.contains('hidden')) return null;
+                            return b.dataset.alertKind === 'link_offline_waiting' ? b.textContent : null;
+                        })()"""
+                    )
+
+                banner_wait_txt = await wait_until(_dom_link_waiting, timeout_s=35.0, desc="Chrome #watchdog-alert-banner link_offline_waiting")
+                assert "同时断联保护中" in banner_wait_txt, f"Unexpected banner text: {banner_wait_txt}"
+
+                # Restore S1 links -> verify banner switches live to `serial_gap_detected`!
+                await stack.set_link(0, bmc_up=True, serial_up=True)
+
+                async def _dom_serial_gap():
+                    return await cdp.eval_js(
+                        """(() => {
+                            const b = document.getElementById('watchdog-alert-banner');
+                            if (!b || b.classList.contains('hidden')) return null;
+                            return b.dataset.alertKind === 'serial_gap_detected' ? b.textContent : null;
+                        })()"""
+                    )
+
+                banner_gap_txt = await wait_until(_dom_serial_gap, timeout_s=15.0, desc="Chrome #watchdog-alert-banner serial_gap_detected")
+                assert "serial_gap_detected" in banner_gap_txt, f"Unexpected gap banner text: {banner_gap_txt}"
+                results.append({"scenario": "3_chrome_live_dual_drop_and_serial_gap_banners", "status": "PASS"})
+                print("      -> PASS", flush=True)
+
+                # ============================================================
+                # Scenario 4: Live RMT Hard-Hang `stage_hang_timeout` Banner + G27 Fix
+                # ============================================================
+                print("[Tier4][4/4] Verifying live `stage_hang_timeout` red alert banner + G27 `#dimm-replacement-banner` visibility in Chrome...", flush=True)
+                await stack.connect_and_heat_backend_hood("S1", 0, target_c=70)
+                await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.15)
+                await stack.enqueue_cmd(
+                    "S1",
+                    "SaveBootPlan",
+                    {
+                        "plan": {
+                            "preset": "auto",
+                            "mt_enabled": False,
+                            "run_rmt": True,
+                            "stages": {"uip1": "auto", "amt": "auto", "uip2": "auto", "uefi": "auto"},
+                        },
+                        "watchdog": {"dense_stage_silence_timeout_ms": 2200, "reboot_on_hang": False},
+                    },
+                )
+                await stack.enqueue_cmd("S1", "ControlBootPlan", {"action": "restart"})
+
+                async def _dom_hang_alert():
+                    return await cdp.eval_js(
+                        """(() => {
+                            const wb = document.getElementById('watchdog-alert-banner');
+                            const db = document.getElementById('dimm-replacement-banner');
+                            if (!wb || wb.classList.contains('hidden')) return null;
+                            if (wb.dataset.alertKind !== 'stage_hang_timeout') return null;
+                            return {
+                                wdText: wb.textContent,
+                                dimmBannerVisible: !!(db && !db.classList.contains('hidden')),
+                                dimmBannerText: db ? db.textContent : ''
+                            };
+                        })()"""
+                    )
+
+                hang_dom = await wait_until(_dom_hang_alert, timeout_s=25.0, desc="Chrome #watchdog-alert-banner stage_hang_timeout")
+                assert "stage_hang_timeout" in hang_dom["wdText"]
+                assert "主板保持死机现场" in hang_dom["wdText"]
+                assert "0x08 00" in hang_dom["wdText"]
+                assert hang_dom["dimmBannerVisible"] is True, f"G27 regression: #dimm-replacement-banner hidden on hang fault! {hang_dom}"
+                assert not cdp.js_exceptions, f"Uncaught JS exceptions during Web E2E: {cdp.js_exceptions}"
+                results.append({"scenario": "4_chrome_stage_hang_alert_and_g27_banner_fix", "status": "PASS"})
+                print("      -> PASS", flush=True)
+            finally:
+                await cdp.close()
+
+        elapsed_s = round(time.monotonic() - t0, 2)
+        summary = {"tier": "Tier4_Headless_Chrome156_Web_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
+        print(f"\n[Tier4] ALL 4 HEADLESS CHROME 156 WEB E2E SCENARIOS PASSED in {elapsed_s}s!", flush=True)
+        return summary
+    finally:
+        if chrome_proc and chrome_proc.poll() is None:
+            with contextlib.suppress(Exception):
+                chrome_proc.terminate()
+                chrome_proc.wait(timeout=3.0)
+            if chrome_proc.poll() is None:
+                with contextlib.suppress(Exception):
+                    chrome_proc.kill()
+        shutil.rmtree(user_data_dir, ignore_errors=True)
+
+
+if __name__ == "__main__":
+    res = asyncio.run(run_tier4_web_suite())
+    out_file = ROOT_DIR / "build" / "sim" / "tier4_chrome_web_report.json"
+    out_file.parent.mkdir(parents=True, exist_ok=True)
+    out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False), encoding="utf-8")

+ 1 - 1
src/backendlink.cpp

@@ -798,7 +798,7 @@ void BackendLink::applyStation(int station, const QJsonObject &st)
                 QJsonDocument(stageErrors).toJson(QJsonDocument::Compact));
         if (compact != m_stageErrorsJson[station]) {
             m_stageErrorsJson[station] = compact;
-            const char *const kStages[] = {"training", "rmt", "amt", "mt"};
+            const char *const kStages[] = {"training", "rmt", "amt", "mt", "system"};
             for (const char *stage : kStages) {
                 const QJsonArray errors =
                         stageErrors.value(QString::fromLatin1(stage)).toArray();

+ 27 - 4
src/detailview.cpp

@@ -297,13 +297,36 @@ void DetailView::renderTasks(int station)
         QString stateText = QStringLiteral("未开始");
         if (d.taskFailed >= 0 && i == d.taskFailed) {
             state = QStringLiteral("failed");
-            stateText = d.awaitingDimmReplacement ? QStringLiteral("等待换条") : QStringLiteral("执行失败");
+            if (d.faultCode == QLatin1String("stage_hang_timeout")
+                || d.faultCode == QLatin1String("mt_duration_timeout")
+                || d.faultCode == QLatin1String("amt_duration_timeout")) {
+                stateText = QStringLiteral("卡死超时 FAIL");
+            } else if (d.faultCode == QLatin1String("link_lost_timeout")) {
+                stateText = QStringLiteral("双断失联 FAIL");
+            } else if (d.faultCode == QLatin1String("reconnect_power_off")) {
+                stateText = QStringLiteral("异常掉电 FAIL");
+            } else {
+                stateText = d.awaitingDimmReplacement ? QStringLiteral("等待换条") : QStringLiteral("执行失败");
+            }
         } else if (d.taskCurrent >= 0 && i == d.taskCurrent) {
             state = QStringLiteral("running");
-            stateText = QStringLiteral("执行中");
+            stateText = (d.observedDetail == QLatin1String("link_offline_waiting"))
+                            ? QStringLiteral("双断等待恢复")
+                            : QStringLiteral("执行中");
             // 手册 9.2:后端 task_status / awaiting_dimm_replacement 比本地进度更精确,
             // 直接用于「当前任务」这一条的显示;其余任务仍按本地队列进度。
-            if (d.awaitingDimmReplacement) {
+            if (d.faultCode == QLatin1String("stage_hang_timeout")
+                || d.faultCode == QLatin1String("mt_duration_timeout")
+                || d.faultCode == QLatin1String("amt_duration_timeout")) {
+                state = QStringLiteral("failed");
+                stateText = QStringLiteral("卡死超时 FAIL");
+            } else if (d.faultCode == QLatin1String("link_lost_timeout")) {
+                state = QStringLiteral("failed");
+                stateText = QStringLiteral("双断失联 FAIL");
+            } else if (d.faultCode == QLatin1String("reconnect_power_off")) {
+                state = QStringLiteral("failed");
+                stateText = QStringLiteral("异常掉电 FAIL");
+            } else if (d.awaitingDimmReplacement) {
                 state = QStringLiteral("failed");
                 stateText = QStringLiteral("等待换条");
             } else if (d.taskStatus == QStringLiteral("queued")) {
@@ -313,7 +336,7 @@ void DetailView::renderTasks(int station)
                 stateText = QStringLiteral("执行失败");
             } else if (d.taskStatus == QStringLiteral("completed")) {
                 state = QStringLiteral("done");
-                stateText = QStringLiteral("已完成");
+                stateText = d.serialGapDetected ? QStringLiteral("已完成 (曾丢字)") : QStringLiteral("已完成");
             }
         } else if (i < d.taskDone) {
             state = QStringLiteral("done");

+ 22 - 4
src/mainwindow.cpp

@@ -485,14 +485,22 @@ MainWindow::MainWindow(QWidget *parent)
                                || runState == QStringLiteral("timeout")
                                || runState == QStringLiteral("blocked"));
         if (running) {
-            if (!m_backendRunning[station]) {
-                // 新一轮起跑:本轮「训练结束已下发目标温度」的标记清零,允许再发一次
+            const bool bootRotatedWhileRunning =
+                !bootId.isEmpty() && !m_activeRunBootId[station].isEmpty()
+                && bootId != m_activeRunBootId[station];
+            if (!m_backendRunning[station] || bootRotatedWhileRunning) {
+                // 新一轮起跑(或网页端在运行态下直接重启了新一轮 boot_id):
+                // 本轮「训练结束已下发目标温度」与「终态 0x08 结束指令」标记清零,允许再发一次
                 m_tempSent[station] = false;
-                m_endCmdSent[station] = false; // 只在进入新一轮运行态时复位,避免每秒 state 重复放开结束命令
+                m_endCmdSent[station] = false;
                 m_endSignalReceived[station] = false;
                 m_terminalSince[station].invalidate();
                 m_taskCompleteVerdict[station].clear();
+                if (m_taskIndex[station] < 0)
+                    m_taskAdvanceGuard[station] = false;
             }
+            if (!bootId.isEmpty())
+                m_activeRunBootId[station] = bootId;
             m_backendRunning[station] = true;
             if (m_startClicked[station])
                 m_sawRunning[station] = true;   // 见过运行态,之后的 idle/终态 才算本轮结束
@@ -571,7 +579,11 @@ MainWindow::MainWindow(QWidget *parent)
         const bool restartClick = m_backend->lastStartWasRestart(station);
         const bool idleSettled = !restartClick || m_clickTimer[station].elapsed() > 60000;
 
-        if ((terminal
+        // 注意:terminal 刚到达时若本轮尚未发过 0x08(!m_endCmdSent),正在等紧随其后的
+        // task_complete 或 kEndSignalWaitMs 兜底进 finalizeRound;此时绝不能提前把
+        // m_backendRunning 清零,否则网页端/批次发起的测试在 finalizeRound 检查
+        // (m_backendRunning || m_startClicked) 时会漏发 0x08 降温指令!
+        if (((terminal && m_endCmdSent[station])
              || (runState == QLatin1String("idle") && !hostStillActive
                  && (!m_startClicked[station] || idleSettled)))
             && !waitingInitialRun) {
@@ -719,6 +731,7 @@ MainWindow::MainWindow(QWidget *parent)
             m_taskCompleteVerdict[i].clear();
             m_tempSent[i] = false;
             m_awaitingNewStart[i] = false;
+            m_activeRunBootId[i].clear();
             m_taskAdvanceGuard[i] = false;
             if (m_taskIndex[i] >= 0) {
                 m_taskFailed[i] = m_taskIndex[i];
@@ -1029,6 +1042,11 @@ void MainWindow::finalizeRound(int station, bool failed, const QString &reason)
         m_store->appendLog(station, dissipate
             ? QStringLiteral("[qt] 收到后端结束指令(%1):已向 MCU 下发 AA 55 08 01 00 D8(散热)").arg(reason)
             : QStringLiteral("[qt] 收到后端结束指令(%1)、后面还有任务:已向 MCU 下发 AA 55 08 01 01 DF(不散热,保持腔体温度)").arg(reason));
+        if (dissipate) {
+            m_backendRunning[station] = false;
+            if (m_overview)
+                m_overview->setStartRunning(station, m_startClicked[station] || m_backendRunning[station]);
+        }
     }
 
     finishCurrentTask(station, failed, reason);

+ 1 - 0
src/mainwindow.h

@@ -134,6 +134,7 @@ private:
     bool m_awaitingNewStart[4] = {false, false, false, false};
     QString m_waitOldBootId[4];
     qint64 m_waitOldStartedMs[4] = {0, 0, 0, 0};
+    QString m_activeRunBootId[4];
 
 
     // ---- 多任务串行执行 ----

+ 39 - 3
src/overviewview.cpp

@@ -214,7 +214,24 @@ void OverviewView::renderInfo(int index)
         if (scopeLabel.isEmpty())
             scopeLabel = QStringLiteral("本轮");
 
-        if (offline) {
+        const bool isLinkWaiting = (d.observedDetail == QLatin1String("link_offline_waiting")
+                                    && d.taskStatus == QLatin1String("running"));
+        const bool isHangFault = (d.faultCode == QLatin1String("stage_hang_timeout")
+                                  || d.faultCode == QLatin1String("mt_duration_timeout")
+                                  || d.faultCode == QLatin1String("amt_duration_timeout")
+                                  || d.faultCode == QLatin1String("consecutive_hang_limit_exceeded"));
+        const bool isLinkLostFault = (d.faultCode == QLatin1String("link_lost_timeout"));
+        const bool isPowerOffFault = (d.faultCode == QLatin1String("reconnect_power_off"));
+
+        if (isLinkWaiting) {
+            text = QStringLiteral("双断保护 · 等待恢复");
+        } else if (isHangFault) {
+            text = QStringLiteral("%1 卡死超时 FAIL").arg(scopeLabel);
+        } else if (isLinkLostFault) {
+            text = QStringLiteral("双断失联超时 FAIL");
+        } else if (isPowerOffFault) {
+            text = QStringLiteral("重连核验掉电 FAIL");
+        } else if (offline && !isFail && !d.awaitingDimmReplacement) {
             text = QStringLiteral("控制台离线");
         } else if (d.awaitingDimmReplacement) {
             text = QStringLiteral("%1 FAIL · 等待换条").arg(scopeLabel);
@@ -224,11 +241,13 @@ void OverviewView::renderInfo(int index)
                        : QStringLiteral("%1 FAIL · 异常 %2").arg(scopeLabel).arg(d.alarms.size());
         } else if (text.isEmpty()) {
             text = QStringLiteral("在线");   // 控制台确认在线但阶段未知:标题右边不留空白
+        } else if (d.serialGapDetected) {
+            text = QStringLiteral("%1 · 曾丢字").arg(text);
         }
         m_phase[index]->setText(text);
         m_phase[index]->setVisible(!text.isEmpty());
 
-        const QString st = (offline || hasErr)
+        const QString st = (offline || hasErr || isLinkWaiting || !d.faultCode.isEmpty())
                                ? QStringLiteral("offline") : QStringLiteral("normal");
         if (m_phase[index]->property("state").toString() != st) {
             m_phase[index]->setProperty("state", st);
@@ -242,11 +261,28 @@ void OverviewView::renderInfo(int index)
                 if (ch.state == ChannelInfo::Fail)
                     ++failSlots;
             }
-            if ((isFail || d.awaitingDimmReplacement) && failSlots == 0) {
+            if (isHangFault) {
+                m_chTitles[index]->setText(
+                    d.hangScenePreserved
+                        ? QStringLiteral("24 通道内存测试状态 · 阶段无输出卡死 FAIL(已停热降温并保留死机现场)")
+                        : QStringLiteral("24 通道内存测试状态 · 阶段无输出卡死 FAIL(自动复位恢复中)"));
+                m_chTitles[index]->setStyleSheet(QStringLiteral("color:#c92f2f;"));
+            } else if (isLinkLostFault || isPowerOffFault) {
+                m_chTitles[index]->setText(
+                    isPowerOffFault
+                        ? QStringLiteral("24 通道内存测试状态 · 重连核验主板已掉电关机 FAIL")
+                        : QStringLiteral("24 通道内存测试状态 · BMC+2200 双断超时失联 FAIL"));
+                m_chTitles[index]->setStyleSheet(QStringLiteral("color:#c92f2f;"));
+            } else if ((isFail || d.awaitingDimmReplacement) && failSlots == 0) {
                 m_chTitles[index]->setText(
                     QStringLiteral("24 通道内存测试状态 · FAIL(%1 条未映射通道,点查看详情)")
                         .arg(d.alarms.size()));
                 m_chTitles[index]->setStyleSheet(QStringLiteral("color:#c92f2f;"));
+            } else if (d.serialGapDetected) {
+                m_chTitles[index]->setText(
+                    QStringLiteral("24 通道内存测试状态 · 注意:串口曾闪断 %1 次 (serial_gap_detected,建议复核)")
+                        .arg(qMax(1, d.serialGapCount)));
+                m_chTitles[index]->setStyleSheet(QStringLiteral("color:#b45309;"));
             } else {
                 m_chTitles[index]->setText(QStringLiteral("24 通道内存测试状态"));
                 m_chTitles[index]->setStyleSheet(QString());

+ 36 - 0
src/stationdata.cpp

@@ -470,6 +470,12 @@ void StationStore::applyBackendState(int index, const QJsonObject &station)
         d.verdictScope.clear();
         d.firmwareFamily.clear();
         d.taskStatus.clear();
+        d.observedDetail.clear();
+        d.faultCode.clear();
+        d.faultMessage.clear();
+        d.hangScenePreserved = false;
+        d.serialGapDetected = false;
+        d.serialGapCount = 0;
         d.mtResult = QJsonObject();
         d.awaitingDimmReplacement = false;
         channelsChangedFlag = true;
@@ -521,6 +527,36 @@ void StationStore::applyBackendState(int index, const QJsonObject &station)
         d.taskStatus = taskStatus;
         infoDirty = true;
     }
+    const QString observedDetail = station.value(QStringLiteral("observed_detail")).toString();
+    if (d.observedDetail != observedDetail) {
+        d.observedDetail = observedDetail;
+        infoDirty = true;
+    }
+    const QString faultCode = station.value(QStringLiteral("fault_code")).toString();
+    if (d.faultCode != faultCode) {
+        d.faultCode = faultCode;
+        infoDirty = true;
+    }
+    const QString faultMessage = station.value(QStringLiteral("fault_message")).toString();
+    if (d.faultMessage != faultMessage) {
+        d.faultMessage = faultMessage;
+        infoDirty = true;
+    }
+    const bool hangScenePreserved = station.value(QStringLiteral("hang_scene_preserved")).toBool();
+    if (d.hangScenePreserved != hangScenePreserved) {
+        d.hangScenePreserved = hangScenePreserved;
+        infoDirty = true;
+    }
+    const bool serialGapDetected = station.value(QStringLiteral("serial_gap_detected")).toBool();
+    if (d.serialGapDetected != serialGapDetected) {
+        d.serialGapDetected = serialGapDetected;
+        infoDirty = true;
+    }
+    const int serialGapCount = station.value(QStringLiteral("serial_gap_count")).toInt(0);
+    if (d.serialGapCount != serialGapCount) {
+        d.serialGapCount = serialGapCount;
+        infoDirty = true;
+    }
     const QJsonObject taskBatch = station.value(QStringLiteral("task_batch")).toObject();
     if (d.taskBatch != taskBatch) {
         d.taskBatch = taskBatch;

+ 6 - 0
src/stationdata.h

@@ -95,6 +95,12 @@ struct StationData {
     int consoleOnline = -1;                // 1 在线 / 0 离线 / -1 未知
     bool awaitingDimmReplacement = false;  // 换条停机挂起(后端把 run_state 置为 blocked)
     QString taskStatus;                    // not_started / queued / running / completed / failed
+    QString observedDetail;                // link_offline_waiting / link_recovered / stage_hang_timeout ...
+    QString faultCode;                     // stage_hang_timeout / link_lost_timeout / reconnect_power_off ...
+    QString faultMessage;                  // 结构化保护触发原因说明
+    bool hangScenePreserved = false;       // 死机卡死后是否保持主板现场未自动重启
+    bool serialGapDetected = false;        // 本轮是否发生过 2200 串口闪断丢字
+    int serialGapCount = 0;                // 本轮串口闪断次数
     QJsonObject taskBatch;                 // 后端托管批次队列快照(前端自维护队列时仅留档)
     QJsonArray taskHistory;                // 已完成轮次归档摘要
     QJsonObject mtResult;                  // MT 执行摘要(report_file / errors / tests_passed / ecc_*)

+ 27 - 4
web/app.js

@@ -49,6 +49,7 @@
     SetStageIntent:'预设阶段控制状态',
     ApplyErrorPreset:'应用零加压拉偏预设',
     ClearTerminalView:'锚定清空控制台窗口',
+    ConfigureWatchdog:'配置防卡死与断联保护',
   };
   const actionLabels = {
     open:'连接 BIOS 控制台',
@@ -440,10 +441,23 @@
       const d = diagnostics.get(s.station_id);
       const consoleOnline = !!(s.console_online ?? (d?.state === 'online'));
       const nodeOnline = consoleOnline || s.bmc_state === 'online';
-      const kind = (unavailable || !nodeOnline) ? 'offline' : 'idle';
+      const isLinkWaiting = s.observed_detail === 'link_offline_waiting';
+      const faultCode = s.fault_code || '';
+      const hasFail = s.awaiting_dimm_replacement || s.task_status === 'failed' || s.verdict === 'fail' || !!faultCode;
+      const kind = unavailable ? 'offline' : hasFail ? 'error' : isLinkWaiting ? 'warn' : !nodeOnline ? 'offline' : 'idle';
+      const statusTagText = unavailable ? '未配置'
+        : faultCode === 'stage_hang_timeout' || faultCode === 'mt_duration_timeout' || faultCode === 'amt_duration_timeout' ? '卡死超时'
+        : faultCode === 'link_lost_timeout' ? '失联超时'
+        : faultCode === 'reconnect_power_off' ? '异常掉电'
+        : faultCode === 'consecutive_hang_limit_exceeded' ? '死机熔断'
+        : s.awaiting_dimm_replacement ? '待换条'
+        : hasFail ? '测试失败'
+        : isLinkWaiting ? '双断等待恢复'
+        : !nodeOnline ? '离线'
+        : label(state) + (s.serial_gap_detected ? ' · 曾丢字' : '');
       const bmcBadge = s.bmc_state === 'online' ? 'BMC 在线' : (s.bmc_address ? `BMC ${label(s.bmc_state || 'offline')}` : '仅串口模式');
-      return `<div class="station-card ${s.station_id === stationId ? 'active' : ''}" data-id="${escape(s.station_id)}" role="button" tabindex="0" aria-pressed="${s.station_id === stationId}">
-        <div class="station-card-header"><div><span class="station-name">${escape(s.station_id)} · ${escape(shortName)}</span><div class="station-subtitle">${escape(d?.transport ? transportLabel(d) : s.bmc_address ? 'BMC ' + s.bmc_address : '未配置连接')}</div></div><span class="station-status-tag tag-${s.awaiting_dimm_replacement ? 'error' : kind}">${escape(unavailable ? '未配置' : s.awaiting_dimm_replacement ? '待换条' : !nodeOnline ? '离线' : label(state))}</span></div>
+      return `<div class="station-card ${s.station_id === stationId ? 'active' : ''}" data-id="${escape(s.station_id)}" data-fault-code="${escape(faultCode)}" data-observed-detail="${escape(s.observed_detail || '')}" role="button" tabindex="0" aria-pressed="${s.station_id === stationId}">
+        <div class="station-card-header"><div><span class="station-name">${escape(s.station_id)} · ${escape(shortName)}</span><div class="station-subtitle">${escape(d?.transport ? transportLabel(d) : s.bmc_address ? 'BMC ' + s.bmc_address : '未配置连接')}</div></div><span class="station-status-tag tag-${kind}">${escape(statusTagText)}</span></div>
         <div class="station-info-row"><span>主板电源</span><span>${escape(label(s.server_power))} · ${escape(bmcBadge)}</span></div>
         <div class="station-info-row"><span>测试用时</span><span>${escape(formatElapsed(s.elapsed_ms || 0))}</span></div>
         <div class="station-card-footer"><span><i class="status-dot ${consoleOnline ? 'online' : ''}"></i>控制台 ${escape(consoleOnline ? '在线 (活动)' : label(d?.state || 'closed'))}</span><span>${escape(s.firmware_family || '硬件工位')}</span></div>
@@ -624,7 +638,16 @@
       if (!stationUserChosen && stations.length) {
         const cur = current();
         const curOnline = !!(cur && (cur.console_online || cur.bmc_state === 'online'));
-        if (!curOnline) {
+        const curActiveOrAlert = !!(cur && (
+          cur.task_status === 'running' ||
+          cur.observed_detail === 'link_offline_waiting' ||
+          cur.awaiting_dimm_replacement ||
+          cur.task_status === 'failed' ||
+          cur.verdict === 'fail' ||
+          cur.fault_code ||
+          cur.serial_gap_detected
+        ));
+        if (!curOnline && !curActiveOrAlert) {
           const live = stations.find(s => s.console_online || s.bmc_state === 'online');
           if (live) stationId = live.station_id;
         }

Разница между файлами не показана из-за своего большого размера
+ 76 - 6
web/boot-plan-controls.js


+ 5 - 3
web/dimm-overview.js

@@ -4,7 +4,7 @@
   const qualityNames={valid:'有效读数',reported:'BMC 读回',stale:'上次读数',no_reading:'未读取',unavailable:'无读数',unavailable_in_phase:'当前阶段不可读',unverified:'时间未确认',read_error:'读取异常',powered_off:'已断电',unknown:'未读取'};
   const presenceNames={present:'已确认安装',absent:'已确认空槽',unknown:'安装状态未知'};
   const enabledNames={enabled:'已启用',disabled:'已禁用',unknown:'训练状态未知'};
-  const stageLabels={training:'Training',rmt:'RMT',amt:'AMT',mt:'MT'};
+  const stageLabels={training:'Training',rmt:'RMT',amt:'AMT',mt:'MT',system:'系统/链路看门狗'};
   let api;
   function render(control={}) {
     const rows=Array.isArray(control.dimms)?control.dimms:[];
@@ -12,9 +12,11 @@
     const freshCount=rows.filter(fresh).length;
     const passCount=rows.filter(r=>r.state==='pass').length;
     const failCount=rows.filter(r=>r.state==='fail').length;
-    const stObj=window.stlFirmware?.station?.() || {};
+    const stObj=api?.station?.() || {};
+    const wd=control.watchdog || {};
+    const faultCode=wd.fault_code || control.firmware?.fault_code || stObj.fault_code || '';
     const awaiting=!!(control.awaiting_dimm_replacement || stObj.awaiting_dimm_replacement);
-    const hasFailure=failCount>0 || awaiting || control.verdict==='fail' || control.task_status==='failed' || stObj.task_status==='failed';
+    const hasFailure=failCount>0 || awaiting || control.verdict==='fail' || stObj.verdict==='fail' || control.task_status==='failed' || stObj.task_status==='failed' || !!faultCode;
     const mtRes=control.firmware?.mt_result || {};
     const mtTag=mtRes.status?` · MT:${String(mtRes.status).toUpperCase()}${mtRes.errors>0?'('+mtRes.errors+' errs)':''}`:'';
     $('dimm-stage-badge').textContent=`PASS ${passCount} / FAIL ${failCount}${hasFailure&&failCount===0?' (未映射通道 FAIL)':''} · 温度 ${freshCount}/${rows.length}${mtTag}`;

Разница между файлами не показана из-за своего большого размера
+ 1 - 1
web/firmware-controls.js


Разница между файлами не показана из-за своего большого размера
+ 11 - 10
web/index.html


+ 55 - 2
web/stage-progress.js

@@ -85,11 +85,64 @@
       $('station-task-status-badge').classList.toggle('error', tStatus === 'failed');
     }
 
-    // Render awaiting_dimm_replacement or stage_errors banner
+    // Render awaiting_dimm_replacement or stage_errors banner (G27 fix: never hide when task_status==='failed' or fault_code set!)
     const awaitingRep = !!(control.awaiting_dimm_replacement || station.awaiting_dimm_replacement);
     const hasStageErrs = Object.values(stageErrors).some(arr => Array.isArray(arr) && arr.length > 0);
+    const wd = control.watchdog || {};
+    const faultCode = wd.fault_code || firmware.fault_code || station.fault_code || '';
+    const hasFailState = tStatus === 'failed' || control.verdict === 'fail' || station.verdict === 'fail' || !!faultCode;
     if ($('dimm-replacement-banner')) {
-      $('dimm-replacement-banner').classList.toggle('hidden', !awaitingRep && !hasStageErrs);
+      $('dimm-replacement-banner').classList.toggle('hidden', !awaitingRep && !hasStageErrs && !hasFailState);
+    }
+
+    // Render dedicated Dual-Link Offline / Stage-Hang Watchdog / Serial-Gap alert banner
+    const wdBanner = $('watchdog-alert-banner');
+    if (wdBanner) {
+      const obsDetail = firmware.observed_detail || station.observed_detail || '';
+      const isLinkWaiting = obsDetail === 'link_offline_waiting' || wd.link_offline_waiting === true;
+      const serialGap = !!(wd.serial_gap_detected || firmware.serial_gap_detected || station.serial_gap_detected);
+      const gapCount = Number(wd.serial_gap_count || firmware.serial_gap_count || 1);
+      const gapSec = Math.max(1, Math.round(Number(wd.serial_gap_total_ms || firmware.serial_gap_total_ms || 0) / 1000));
+      if (isLinkWaiting) {
+        const offSec = Math.max(5, Math.round(Number(wd.link_offline_elapsed_ms || 0) / 1000));
+        const limSec = Math.round(Number(wd.link_lost_timeout_ms || 240000) / 1000);
+        wdBanner.className = '';
+        wdBanner.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;margin-bottom:8px;background:#fffbeb;border:1px solid #f59e0b;border-radius:6px;color:#92400e;font-size:13px';
+        wdBanner.dataset.alertKind = 'link_offline_waiting';
+        wdBanner.innerHTML = `<div><strong>⚠️ BMC 与 2200 串口同时断联保护中 (link_offline_waiting · 已持续 ${offSec}s / 超时上限 ${limSec}s):</strong>当前测试未清空、计时器未重置,正在等待管理网或 BMC 恢复;若持续超过 ${limSec}s 将自动判 <code>link_lost_timeout</code> 并联动高温罩吹风降温。</div>`;
+      } else if (faultCode) {
+        const preserved = !!(wd.hang_scene_preserved || firmware.hang_scene_preserved || station.hang_scene_preserved);
+        const faultMsg = wd.fault_message || firmware.fault_message || station.fault_message || plan.error || faultCode;
+        const faultTitles = {
+          stage_hang_timeout: '🛑 阶段无输出卡死看门狗触发 (stage_hang_timeout)',
+          mt_duration_timeout: '🛑 MT 阶段总运行时长超限 (mt_duration_timeout)',
+          amt_duration_timeout: '🛑 AMT 阶段总运行时长超限 (amt_duration_timeout)',
+          link_lost_timeout: '🛑 BMC 与 2200 串口持续双断超时 (link_lost_timeout)',
+          reconnect_power_off: '🛑 链路重连后核验主板已掉电关机 (reconnect_power_off)',
+          consecutive_hang_limit_exceeded: '🛑 连续死机达到熔断阈值 · 已停止自动重启 (consecutive_hang_limit_exceeded)',
+        };
+        wdBanner.className = '';
+        wdBanner.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;margin-bottom:8px;background:#fef2f2;border:1px solid #dc2626;border-radius:6px;color:#991b1b;font-size:13px;flex-wrap:wrap';
+        wdBanner.dataset.alertKind = faultCode;
+        wdBanner.innerHTML = `<div>
+          <strong>${esc(faultTitles[faultCode] || ('🛑 保护规则触发 (' + faultCode + ')'))}</strong>
+          <div style="margin-top:3px;font-size:12px">${esc(faultMsg)}</div>
+          <div style="margin-top:4px;display:flex;gap:6px;flex-wrap:wrap;font-size:12px">
+            <span class="badge error" style="background:#fee2e2;color:#991b1b;border-color:#fca5a5">${preserved ? '🔒 主板保持死机现场(默认未发 BMC 重启,可查最后串口/SEL)' : '🔄 已触发无人值守自动复位恢复'}</span>
+            <span class="badge" style="background:#eff6ff;color:#1d4ed8;border-color:#93c5fd">❄️ 已推送 task_complete 联动高温罩停热吹扫 (0x08 00)</span>
+            ${serialGap ? `<span class="badge" style="background:#fef3c7;color:#92400e;border-color:#fcd34d">⚠️ 期间曾发生 ${gapCount} 次串口断联 (${gapSec}s)</span>` : ''}
+          </div>
+        </div>`;
+      } else if (serialGap) {
+        wdBanner.className = '';
+        wdBanner.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;margin-bottom:8px;background:#fffbeb;border:1px solid #fbbf24;border-radius:6px;color:#92400e;font-size:13px';
+        wdBanner.dataset.alertKind = 'serial_gap_detected';
+        wdBanner.innerHTML = `<div><strong>⚠️ 串口断联丢字提醒 (serial_gap_detected):</strong>本轮测试期间 2200 串口曾断联 ${gapCount} 次(累计约 ${gapSec}s)并已自动恢复${obsDetail === 'link_recovered' ? ' (link_recovered)' : ''}。归档报告已打标,若最终结果 PASS 建议人工复核串口日志或重跑确认。</div>`;
+      } else {
+        wdBanner.className = 'hidden';
+        wdBanner.dataset.alertKind = '';
+        wdBanner.innerHTML = '';
+      }
     }
 
     // Render live pending StageIntents (last-write-wins)

+ 19 - 2
web/transport.js

@@ -5,7 +5,21 @@
   const pending = new Map();
   const prefix = `web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 9)}`;
   let socket = null, opening = null, retryTimer = null, enabled = true;
-  let state = 'idle', generation = 0, sequence = 0, failures = 0, sent = 0;
+  let state = 'idle', generation = 0, sequence = 0, failures = 0, sent = 0, authProbePending = false;
+  function probeAuthAndReloadIfExpired() {
+    if (authProbePending || !enabled) return;
+    authProbePending = true;
+    fetch('/contracts/firmware-vd012.json', {method: 'HEAD', cache: 'no-store', credentials: 'same-origin'})
+      .then(res => {
+        if (res.status === 401) {
+          enabled = false;
+          clearTimeout(retryTimer); retryTimer = null;
+          location.reload();
+        }
+      })
+      .catch(() => {})
+      .finally(() => { authProbePending = false; });
+  }
 
   function error(code, message) {
     const value = new Error(`${code}: ${message}`);
@@ -87,12 +101,15 @@
       // Browsers provide the actual disconnect through onclose. Keeping one
       // completion path also prevents one failure from scheduling two retries.
     };
-    candidate.onclose = () => {
+    candidate.onclose = event => {
       clearTimeout(timer);
       if (socket !== candidate) return;
       socket = null; opening = null; failures++;
       const reason = disconnected();
       rejectOpening(reason); rejectPending(reason);
+      if (enabled && event?.code === 1006 && failures >= 2) {
+        probeAuthAndReloadIfExpired();
+      }
       notify(enabled ? 'disconnected' : 'closed'); retry();
     };
     return ready;