Ver código fonte

Release 0.8.1.25: 1-to-1 thermal_mcu console, VD012 Stage 2/PEI timer protection, P0_DIMM & Channel/Slot coords, rmt maskmain, and SDR discrete refresh

XJKJ STL 1 semana atrás
pai
commit
3b2d3a0c00

+ 1 - 1
Dockerfile

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

Diferenças do arquivo suprimidas por serem muito extensas
+ 6 - 6
README.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-0.8.1.24
+0.8.1.25

+ 3 - 3
docker-compose.yml

@@ -3,9 +3,9 @@ services:
     build:
     build:
       context: .
       context: .
       args:
       args:
-        STL_VERSION: ${STL_VERSION:-0.8.1.24}
+        STL_VERSION: ${STL_VERSION:-0.8.1.25}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
-    image: xjkj-stl:0.8.1.24
+    image: xjkj-stl:0.8.1.25
     container_name: xjkj-stl-backend
     container_name: xjkj-stl-backend
     restart: unless-stopped
     restart: unless-stopped
     stop_grace_period: 30s
     stop_grace_period: 30s
@@ -44,7 +44,7 @@ services:
   pxe-dhcp:
   pxe-dhcp:
     build:
     build:
       context: ./deploy/pxe-dhcp
       context: ./deploy/pxe-dhcp
-    image: xjkj-pxe-dhcp:0.8.1.24
+    image: xjkj-pxe-dhcp:0.8.1.25
     container_name: xjkj-pxe-dhcp
     container_name: xjkj-pxe-dhcp
     restart: unless-stopped
     restart: unless-stopped
     network_mode: host
     network_mode: host

Diferenças do arquivo suprimidas por serem muito extensas
+ 23 - 5
docs/WEBSOCKET_API_ZH.md


+ 47 - 7
native/stl_accel/c_bridge.c

@@ -1572,6 +1572,7 @@ int c_ipmi_open(
                 safe_host[hi] = '\0';
                 safe_host[hi] = '\0';
                 snprintf(g_ipmi_slots[i].sdr_cache_path, sizeof(g_ipmi_slots[i].sdr_cache_path),
                 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_%d_%s.cache", i, safe_host);
+                unlink(g_ipmi_slots[i].sdr_cache_path);
             }
             }
             break;
             break;
         }
         }
@@ -1758,6 +1759,18 @@ typedef struct {
     size_t                 used;
     size_t                 used;
 } SdrIterCtx;
 } SdrIterCtx;
 
 
+static int contains_ci_dimm(const char *s) {
+    if (!s) return 0;
+    for (size_t i = 0; s[i] && s[i+1] && s[i+2] && s[i+3]; i++) {
+        char c0 = (s[i] >= 'a' && s[i] <= 'z') ? (char)(s[i] - 32) : s[i];
+        char c1 = (s[i+1] >= 'a' && s[i+1] <= 'z') ? (char)(s[i+1] - 32) : s[i+1];
+        char c2 = (s[i+2] >= 'a' && s[i+2] <= 'z') ? (char)(s[i+2] - 32) : s[i+2];
+        char c3 = (s[i+3] >= 'a' && s[i+3] <= 'z') ? (char)(s[i+3] - 32) : s[i+3];
+        if (c0 == 'D' && c1 == 'I' && c2 == 'M' && c3 == 'M') return 1;
+    }
+    return 0;
+}
+
 static int sdr_iterate_cb(
 static int sdr_iterate_cb(
     ipmi_sdr_ctx_t sdr,
     ipmi_sdr_ctx_t sdr,
     uint8_t        record_type,
     uint8_t        record_type,
@@ -1777,25 +1790,41 @@ static int sdr_iterate_cb(
     }
     }
 
 
     uint8_t pct = 0, mod = 0, rate = 0, base_u = 0, mod_u = 0;
     uint8_t pct = 0, mod = 0, rate = 0, base_u = 0, mod_u = 0;
-    if (ipmi_sdr_parse_sensor_units(
-            sdr, sdr_record, sdr_record_len,
-            &pct, &mod, &rate, &base_u, &mod_u) < 0) {
-        return 0;
-    }
+    int units_ok = (ipmi_sdr_parse_sensor_units(
+                        sdr, sdr_record, sdr_record_len,
+                        &pct, &mod, &rate, &base_u, &mod_u) == 0);
 
 
     uint8_t raw = 0;
     uint8_t raw = 0;
     double *reading = NULL;
     double *reading = NULL;
     uint16_t bitmask = 0;
     uint16_t bitmask = 0;
     int src = ipmi_sensor_read(ic->sr, sdr_record, sdr_record_len, 0, &raw, &reading, &bitmask);
     int src = ipmi_sensor_read(ic->sr, sdr_record, sdr_record_len, 0, &raw, &reading, &bitmask);
     char line[256];
     char line[256];
-    if (src == 1 && reading != NULL) {
+    if (src == 1 && reading != NULL && units_ok) {
         if (base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
         if (base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
             snprintf(line, sizeof(line), "%s | %.2f degrees C | ok\n", name, *reading);
             snprintf(line, sizeof(line), "%s | %.2f degrees C | ok\n", name, *reading);
         } else {
         } else {
             snprintf(line, sizeof(line), "%s | %.2f | ok\n", name, *reading);
             snprintf(line, sizeof(line), "%s | %.2f | ok\n", name, *reading);
         }
         }
-    } else if (base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
+    } else if (units_ok && base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
         snprintf(line, sizeof(line), "%s | no reading | ns\n", name);
         snprintf(line, sizeof(line), "%s | no reading | ns\n", name);
+    } else if (src == 1 && contains_ci_dimm(name)) {
+        uint8_t stype = 0, ert = 0;
+        if (ipmi_sdr_parse_sensor_type(sdr, sdr_record, sdr_record_len, &stype) == 0 &&
+            ipmi_sdr_parse_event_reading_type_code(sdr, sdr_record, sdr_record_len, &ert) == 0) {
+            if (stype == IPMI_SENSOR_TYPE_MEMORY && ert == 0x6F) {
+                snprintf(line, sizeof(line), "%s | discrete_mem=0x%04X | ok\n", name, (unsigned)bitmask);
+            } else if (stype == IPMI_SENSOR_TYPE_ENTITY_PRESENCE && ert == 0x6F) {
+                snprintf(line, sizeof(line), "%s | discrete_presence=0x%04X | ok\n", name, (unsigned)bitmask);
+            } else if (ert == 0x08) {
+                snprintf(line, sizeof(line), "%s | discrete_devpres=0x%04X | ok\n", name, (unsigned)bitmask);
+            } else {
+                if (reading) free(reading);
+                return 0;
+            }
+        } else {
+            if (reading) free(reading);
+            return 0;
+        }
     } else {
     } else {
         if (reading) free(reading);
         if (reading) free(reading);
         return 0;
         return 0;
@@ -1824,6 +1853,16 @@ static int ensure_sdr_cache_open(ipmi_sdr_ctx_t sdr, ipmi_ctx_t ctx, const char
     return ipmi_sdr_cache_open(sdr, ctx, path);
     return ipmi_sdr_cache_open(sdr, ctx, path);
 }
 }
 
 
+void c_ipmi_invalidate_sdr_cache(int handle) {
+    StlIpmiSlot *slot = get_ipmi_slot(handle);
+    if (!slot) return;
+    pthread_mutex_lock(&slot->mu);
+    if (slot->in_use && slot->sdr_cache_path[0] != '\0') {
+        unlink(slot->sdr_cache_path);
+    }
+    pthread_mutex_unlock(&slot->mu);
+}
+
 int c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len) {
 int c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len) {
     if (out_len) *out_len = 0;
     if (out_len) *out_len = 0;
     if (out_buf && out_cap > 0) out_buf[0] = '\0';
     if (out_buf && out_cap > 0) out_buf[0] = '\0';
@@ -1844,6 +1883,7 @@ int c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_
         pthread_mutex_unlock(&slot->mu);
         pthread_mutex_unlock(&slot->mu);
         return -1;
         return -1;
     }
     }
+    (void)ipmi_sensor_read_ctx_set_flags(sr, IPMI_SENSOR_READ_FLAGS_DISCRETE_READING);
 
 
     if (ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
     if (ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
         slot->alive = 0;
         slot->alive = 0;

+ 153 - 67
native/stl_accel/parser_re2c.re

@@ -193,11 +193,12 @@ static int match_ci_word(const uint8_t *buf_start, const uint8_t *p, const uint8
  */
  */
 static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
 static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
     extract_leading_bracket_cpu(s, end, ev);
     extract_leading_bracket_cpu(s, end, ev);
-    extract_ncd_token(s, end, ev);
+    int has_ncd = extract_ncd_token(s, end, ev);
+    int has_explicit_dimm_coord = has_ncd;
 
 
-    /* Check MemTest86 "CPU<0|1>_DIMM_<A..L>", "(P0,C3,S0,R0)", "Channel/Slot: N0-3-0", or "(Chan,Slot,Rank,Bank,Row,Col): (3,0,0,12,...)" */
+    /* Check MemTest86 "CPU<0|1>_DIMM_<A..L>", "P<0|1>_DIMM_<A..L>[0|1]", "(P0,C3,S0,R0)", "Channel/Slot: N0-3-0", or "(Chan,Slot,Rank,Bank,Row,Col): (3,0,0,12,...)" */
     for (const uint8_t *p = s; p + 6 <= end; p++) {
     for (const uint8_t *p = s; p + 6 <= end; p++) {
-        if (p + 11 <= end &&
+        if (!has_ncd && p + 11 <= end &&
             (p == s || (!((p[-1] >= 'a' && p[-1] <= 'z') || (p[-1] >= 'A' && p[-1] <= 'Z') ||
             (p == s || (!((p[-1] >= 'a' && p[-1] <= 'z') || (p[-1] >= 'A' && p[-1] <= 'Z') ||
                           (p[-1] >= '0' && p[-1] <= '9') || p[-1] == '_'))) &&
                           (p[-1] >= '0' && p[-1] <= '9') || p[-1] == '_'))) &&
             ascii_lower(p[0]) == 'c' && ascii_lower(p[1]) == 'p' && ascii_lower(p[2]) == 'u' &&
             ascii_lower(p[0]) == 'c' && ascii_lower(p[1]) == 'p' && ascii_lower(p[2]) == 'u' &&
@@ -213,9 +214,35 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                 ev->cpu = (int8_t)(p[3] - '0');
                 ev->cpu = (int8_t)(p[3] - '0');
                 ev->channel = (int8_t)(ul - 'A');
                 ev->channel = (int8_t)(ul - 'A');
                 if (ev->dimm < 0) ev->dimm = 0;
                 if (ev->dimm < 0) ev->dimm = 0;
+                has_explicit_dimm_coord = 1;
             }
             }
         }
         }
-        if ((p[0] == 'N' || p[0] == 'n') && (p[1] == '0' || p[1] == '1') &&
+        if (!has_ncd && p + 9 <= end &&
+            (p == s || (!((p[-1] >= 'a' && p[-1] <= 'z') || (p[-1] >= 'A' && p[-1] <= 'Z') ||
+                          (p[-1] >= '0' && p[-1] <= '9') || p[-1] == '_'))) &&
+            (p[0] == 'P' || p[0] == 'p') && (p[1] == '0' || p[1] == '1') && p[2] == '_' &&
+            ascii_lower(p[3]) == 'd' && ascii_lower(p[4]) == 'i' && ascii_lower(p[5]) == 'm' && ascii_lower(p[6]) == 'm' &&
+            p[7] == '_') {
+            uint8_t ltr = p[8];
+            uint8_t ul = (ltr >= 'a' && ltr <= 'z') ? (uint8_t)(ltr - 32) : ltr;
+            if (ul >= 'A' && ul <= 'L') {
+                int ok_after = (p + 9 == end) ||
+                    (p[9] == '0' || p[9] == '1') ||
+                    (!((p[9] >= 'a' && p[9] <= 'z') || (p[9] >= 'A' && p[9] <= 'Z') ||
+                       (p[9] >= '0' && p[9] <= '9') || p[9] == '_'));
+                if (ok_after) {
+                    ev->cpu = (int8_t)(p[1] - '0');
+                    ev->channel = (int8_t)(ul - 'A');
+                    if (p + 9 < end && (p[9] == '0' || p[9] == '1')) {
+                        ev->dimm = (int8_t)(p[9] - '0');
+                    } else if (ev->dimm < 0) {
+                        ev->dimm = 0;
+                    }
+                    has_explicit_dimm_coord = 1;
+                }
+            }
+        }
+        if (!has_ncd && (p[0] == 'N' || p[0] == 'n') && (p[1] == '0' || p[1] == '1') &&
             p[2] == '-' && p[3] >= '0' && p[3] <= '9') {
             p[2] == '-' && p[3] >= '0' && p[3] <= '9') {
             int32_t ch = -1, sl = -1;
             int32_t ch = -1, sl = -1;
             const uint8_t *nx = p + 3;
             const uint8_t *nx = p + 3;
@@ -227,10 +254,11 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                         ev->dimm = (int8_t)sl;
                         ev->dimm = (int8_t)sl;
                     }
                     }
                 }
                 }
+                has_explicit_dimm_coord = 1;
             }
             }
         }
         }
         if (p + 8 > end) continue;
         if (p + 8 > end) continue;
-        if (p[0] == '(' && (p[1] == 'P' || p[1] == 'p') && (p[2] == '0' || p[2] == '1') &&
+        if (!has_ncd && p[0] == '(' && (p[1] == 'P' || p[1] == 'p') && (p[2] == '0' || p[2] == '1') &&
             p[3] == ',' && (p[4] == 'C' || p[4] == 'c')) {
             p[3] == ',' && (p[4] == 'C' || p[4] == 'c')) {
             int32_t ch = -1, sl = -1;
             int32_t ch = -1, sl = -1;
             const uint8_t *nx = p + 5;
             const uint8_t *nx = p + 5;
@@ -242,6 +270,7 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                         ev->dimm = (int8_t)sl;
                         ev->dimm = (int8_t)sl;
                     }
                     }
                 }
                 }
+                has_explicit_dimm_coord = 1;
             }
             }
         }
         }
         size_t tup_skip = 0;
         size_t tup_skip = 0;
@@ -263,33 +292,63 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                 parse_i32_at(nx + 1, end, &c_sl, &nx) && nx < end && *nx == ',' &&
                 parse_i32_at(nx + 1, end, &c_sl, &nx) && nx < end && *nx == ',' &&
                 parse_i32_at(nx + 1, end, &c_rk, &nx) && nx < end && *nx == ',' &&
                 parse_i32_at(nx + 1, end, &c_rk, &nx) && nx < end && *nx == ',' &&
                 parse_i32_at(nx + 1, end, &c_bk, &nx)) {
                 parse_i32_at(nx + 1, end, &c_bk, &nx)) {
-                if (c_ch >= 12 && c_ch <= 23 && ev->cpu < 0) {
-                    ev->cpu = 1;
-                    ev->channel = (int8_t)(c_ch - 12);
-                } else if (c_ch >= 0 && c_ch <= 11) {
-                    ev->channel = (int8_t)c_ch;
-                }
-                if (c_sl >= 0 && c_sl <= 1) ev->dimm = (int8_t)c_sl;
-                if (c_rk >= 0 && c_rk <= 3) ev->rank = (int8_t)c_rk;
-                if (c_bk >= 0 && c_bk < 32) ev->bank = (int8_t)c_bk;
-            }
-        }
-        if ((p + 6 <= end && (p[0] == 'C' || p[0] == 'c') && (p[1] == 'h' || p[1] == 'H') &&
-             p[2] == '/' && (p[3] == 'S' || p[3] == 's') && (p[4] == 'l' || p[4] == 'L') && p[5] == ':')) {
-            const uint8_t *nx = p + 6;
-            while (nx < end && (*nx == ' ' || *nx == '\t')) nx++;
-            if (nx < end && *nx >= '0' && *nx <= '9') {
-                int32_t c_ch = -1, c_sl = -1;
-                if (parse_i32_at(nx, end, &c_ch, &nx) && c_ch >= 0 && c_ch <= 23) {
-                    if (c_ch >= 12 && ev->cpu < 0) {
+                if (!has_explicit_dimm_coord) {
+                    if (c_ch >= 12 && c_ch <= 23 && ev->cpu < 0) {
                         ev->cpu = 1;
                         ev->cpu = 1;
                         ev->channel = (int8_t)(c_ch - 12);
                         ev->channel = (int8_t)(c_ch - 12);
-                    } else if (c_ch <= 11) {
+                    } else if (c_ch >= 0 && c_ch <= 11) {
                         ev->channel = (int8_t)c_ch;
                         ev->channel = (int8_t)c_ch;
                     }
                     }
-                    if (nx < end && (*nx == '/' || *nx == '-' || *nx == ',') &&
-                        parse_i32_at(nx + 1, end, &c_sl, &nx) && c_sl >= 0 && c_sl <= 1) {
-                        ev->dimm = (int8_t)c_sl;
+                    if (c_sl >= 0 && c_sl <= 1) ev->dimm = (int8_t)c_sl;
+                }
+                if (c_rk >= 0 && c_rk <= 3 && ev->rank < 0) ev->rank = (int8_t)c_rk;
+                if (c_bk >= 0 && c_bk < 32 && ev->bank < 0) ev->bank = (int8_t)c_bk;
+            }
+        }
+        if (!has_explicit_dimm_coord &&
+            (p == s || (!((p[-1] >= 'a' && p[-1] <= 'z') || (p[-1] >= 'A' && p[-1] <= 'Z') ||
+                          (p[-1] >= '0' && p[-1] <= '9') || p[-1] == '_')))) {
+            static const char *const cs_prefixes[] = {
+                "channel/slot:",
+                "channel-slot:",
+                "chan/slot:",
+                "chan-slot:",
+                "ch/sl:",
+                "ch-sl:"
+            };
+            const uint8_t *cs_nx = NULL;
+            for (size_t k = 0; k < sizeof(cs_prefixes) / sizeof(cs_prefixes[0]); k++) {
+                size_t plen = strlen(cs_prefixes[k]);
+                if (p + plen <= end) {
+                    int eq = 1;
+                    for (size_t j = 0; j < plen; j++) {
+                        if (ascii_lower(p[j]) != (uint8_t)cs_prefixes[k][j]) {
+                            eq = 0;
+                            break;
+                        }
+                    }
+                    if (eq) {
+                        cs_nx = p + plen;
+                        break;
+                    }
+                }
+            }
+            if (cs_nx) {
+                while (cs_nx < end && (*cs_nx == ' ' || *cs_nx == '\t')) cs_nx++;
+                if (cs_nx < end && *cs_nx >= '0' && *cs_nx <= '9') {
+                    int32_t c_ch = -1, c_sl = -1;
+                    if (parse_i32_at(cs_nx, end, &c_ch, &cs_nx) && c_ch >= 0 && c_ch <= 23) {
+                        if (c_ch >= 12 && ev->cpu < 0) {
+                            ev->cpu = 1;
+                            ev->channel = (int8_t)(c_ch - 12);
+                        } else if (c_ch <= 11) {
+                            ev->channel = (int8_t)c_ch;
+                        }
+                        if (cs_nx < end && (*cs_nx == '/' || *cs_nx == '-' || *cs_nx == ',') &&
+                            parse_i32_at(cs_nx + 1, end, &c_sl, &cs_nx) && c_sl >= 0 && c_sl <= 1) {
+                            ev->dimm = (int8_t)c_sl;
+                        }
+                        has_explicit_dimm_coord = 1;
                     }
                     }
                 }
                 }
             }
             }
@@ -299,7 +358,7 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
     int bg = -1;
     int bg = -1;
     int ba = -1;
     int ba = -1;
     int direct_bank = -1;
     int direct_bank = -1;
-    int explicit_socket = (ev->cpu >= 0) ? (int)ev->cpu : -1;
+    int explicit_socket = -1;
     int fallback_cpu = -1;
     int fallback_cpu = -1;
     int ctrl_mc = -1;
     int ctrl_mc = -1;
     int raw_chid = -1;
     int raw_chid = -1;
@@ -321,18 +380,18 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
             }
             }
             const uint8_t *after = NULL;
             const uint8_t *after = NULL;
             uint64_t hv = 0;
             uint64_t hv = 0;
-            if (match_ci_kw(p, end, "socket", &after)) {
+            if (!has_explicit_dimm_coord && match_ci_kw(p, end, "socket", &after)) {
                 if (parse_hex64_at(after, end, &hv) && hv <= 1) explicit_socket = (int)hv;
                 if (parse_hex64_at(after, end, &hv) && hv <= 1) explicit_socket = (int)hv;
-            } else if (match_ci_kw(p, end, "mc", &after)) {
+            } else if (!has_explicit_dimm_coord && match_ci_kw(p, end, "mc", &after)) {
                 if (parse_hex64_at(after, end, &hv) && hv <= 11) gnr_mc = (int)hv;
                 if (parse_hex64_at(after, end, &hv) && hv <= 11) gnr_mc = (int)hv;
-            } else if (match_ci_kw(p, end, "nmmc", &after)) {
+            } else if (!has_explicit_dimm_coord && match_ci_kw(p, end, "nmmc", &after)) {
                 if (parse_hex64_at(after, end, &hv) && hv <= 11) gnr_nmmc = (int)hv;
                 if (parse_hex64_at(after, end, &hv) && hv <= 11) gnr_nmmc = (int)hv;
-            } else if (match_ci_kw(p, end, "channel", &after)) {
+            } else if (!has_explicit_dimm_coord && match_ci_kw(p, end, "channel", &after)) {
                 if (parse_hex64_at(after, end, &hv) && hv <= 23) gnr_ch = (int)hv;
                 if (parse_hex64_at(after, end, &hv) && hv <= 23) gnr_ch = (int)hv;
-            } else if (match_ci_kw(p, end, "nmchannel", &after)) {
+            } else if (!has_explicit_dimm_coord && match_ci_kw(p, end, "nmchannel", &after)) {
                 if (parse_hex64_at(after, end, &hv) && hv <= 23) gnr_nmch = (int)hv;
                 if (parse_hex64_at(after, end, &hv) && hv <= 23) gnr_nmch = (int)hv;
             } else if (match_ci_kw(p, end, "dimm", &after) || match_ci_kw(p, end, "nmdimm", &after)) {
             } else if (match_ci_kw(p, end, "dimm", &after) || match_ci_kw(p, end, "nmdimm", &after)) {
-                if (parse_hex64_at(after, end, &hv) && hv <= 1) ev->dimm = (int8_t)hv;
+                if (ev->dimm < 0 && parse_hex64_at(after, end, &hv) && hv <= 1) ev->dimm = (int8_t)hv;
             } else if (match_ci_kw(p, end, "rank", &after) || match_ci_kw(p, end, "cs", &after)) {
             } else if (match_ci_kw(p, end, "rank", &after) || match_ci_kw(p, end, "cs", &after)) {
                 if (ev->rank < 0 && parse_hex64_at(after, end, &hv) && hv <= 3) ev->rank = (int8_t)hv;
                 if (ev->rank < 0 && parse_hex64_at(after, end, &hv) && hv <= 3) ev->rank = (int8_t)hv;
             } else if (match_ci_kw(p, end, "bg", &after)) {
             } else if (match_ci_kw(p, end, "bg", &after)) {
@@ -344,17 +403,19 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                 }
                 }
             }
             }
         }
         }
-        int eff_mc = (gnr_mc >= 0) ? gnr_mc : gnr_nmmc;
-        int eff_ch = (gnr_ch >= 0) ? gnr_ch : gnr_nmch;
-        /* Granite Rapids-AP has 12 M2M/MCs (MC 0..11) x 1 sub-MC channel (Channel 0) */
-        if (eff_mc >= 0 && eff_mc <= 11 && eff_ch <= 0) {
-            ev->channel = (int8_t)eff_mc;
-        } else if (eff_mc == 0 && eff_ch >= 0 && eff_ch <= 11) {
-            ev->channel = (int8_t)eff_ch;
-        } else if (eff_mc > 0 && eff_ch > 0 && (eff_mc * 2 + eff_ch) <= 11) {
-            ev->channel = (int8_t)(eff_mc * 2 + eff_ch);
-        } else if (eff_ch >= 0 && eff_ch <= 11) {
-            ev->channel = (int8_t)eff_ch;
+        if (!has_explicit_dimm_coord) {
+            int eff_mc = (gnr_mc >= 0) ? gnr_mc : gnr_nmmc;
+            int eff_ch = (gnr_ch >= 0) ? gnr_ch : gnr_nmch;
+            /* Granite Rapids-AP has 12 M2M/MCs (MC 0..11) x 1 sub-MC channel (Channel 0) */
+            if (eff_mc >= 0 && eff_mc <= 11 && eff_ch <= 0) {
+                ev->channel = (int8_t)eff_mc;
+            } else if (eff_mc == 0 && eff_ch >= 0 && eff_ch <= 11) {
+                ev->channel = (int8_t)eff_ch;
+            } else if (eff_mc > 0 && eff_ch > 0 && (eff_mc * 2 + eff_ch) <= 11) {
+                ev->channel = (int8_t)(eff_mc * 2 + eff_ch);
+            } else if (eff_ch >= 0 && eff_ch <= 11) {
+                ev->channel = (int8_t)eff_ch;
+            }
         }
         }
     }
     }
 
 
@@ -369,22 +430,25 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
         }
         }
         const uint8_t *after = NULL;
         const uint8_t *after = NULL;
         int32_t v = 0;
         int32_t v = 0;
-        if (match_ci_kw(p, kw_scan_end, "socket", &after) || match_ci_kw(p, kw_scan_end, "sock", &after) ||
-            match_ci_kw(p, kw_scan_end, "scktid", &after) || match_ci_kw(p, kw_scan_end, "node", &after)) {
+        if (!has_explicit_dimm_coord &&
+            (match_ci_kw(p, kw_scan_end, "socket", &after) || match_ci_kw(p, kw_scan_end, "sock", &after) ||
+             match_ci_kw(p, kw_scan_end, "scktid", &after) || match_ci_kw(p, kw_scan_end, "node", &after))) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 1) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 1) {
                 explicit_socket = (int)v;
                 explicit_socket = (int)v;
             }
             }
-        } else if (match_ci_kw(p, kw_scan_end, "cpu", &after)) {
+        } else if (!has_explicit_dimm_coord && match_ci_kw(p, kw_scan_end, "cpu", &after)) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 1 && fallback_cpu < 0) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 1 && fallback_cpu < 0) {
                 fallback_cpu = (int)v;
                 fallback_cpu = (int)v;
             }
             }
-        } else if (match_ci_kw(p, kw_scan_end, "ctrl", &after) || match_ci_kw(p, kw_scan_end, "mc", &after)) {
+        } else if (!has_explicit_dimm_coord &&
+                   (match_ci_kw(p, kw_scan_end, "ctrl", &after) || match_ci_kw(p, kw_scan_end, "mc", &after))) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 11) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 11) {
                 ctrl_mc = (int)v;
                 ctrl_mc = (int)v;
             }
             }
-        } else if (match_ci_kw(p, kw_scan_end, "channel", &after) || match_ci_kw(p, kw_scan_end, "ch", &after) ||
-                   match_ci_kw(p, kw_scan_end, "chan", &after) ||
-                   (ev->channel < 0 && match_ci_kw(p, kw_scan_end, "chid", &after))) {
+        } else if (!has_explicit_dimm_coord &&
+                   (match_ci_kw(p, kw_scan_end, "channel", &after) || match_ci_kw(p, kw_scan_end, "ch", &after) ||
+                    match_ci_kw(p, kw_scan_end, "chan", &after) ||
+                    (ev->channel < 0 && match_ci_kw(p, kw_scan_end, "chid", &after)))) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 23) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 23) {
                 raw_chid = (int)v;
                 raw_chid = (int)v;
                 if (v >= 12 && explicit_socket < 0) {
                 if (v >= 12 && explicit_socket < 0) {
@@ -399,8 +463,8 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
                    match_ci_kw(p, kw_scan_end, "slot", &after) || match_ci_kw(p, kw_scan_end, "sl", &after)) {
                    match_ci_kw(p, kw_scan_end, "slot", &after) || match_ci_kw(p, kw_scan_end, "sl", &after)) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 23) {
             if (parse_i32_at(after, kw_scan_end, &v, NULL) && v >= 0 && v <= 23) {
                 if (v <= 1) {
                 if (v <= 1) {
-                    ev->dimm = (int8_t)v;
-                } else if (ev->channel < 0) {
+                    if (ev->dimm < 0) ev->dimm = (int8_t)v;
+                } else if (!has_explicit_dimm_coord && ev->channel < 0) {
                     explicit_socket = (int)(v / 12);
                     explicit_socket = (int)(v / 12);
                     ev->channel = (int8_t)(v % 12);
                     ev->channel = (int8_t)(v % 12);
                     ev->dimm = 0;
                     ev->dimm = 0;
@@ -432,13 +496,15 @@ static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2
         }
         }
     }
     }
 
 
-    if (!gnr_pos && ctrl_mc > 0 && ctrl_mc <= 11 && raw_chid == 0) {
-        ev->channel = (int8_t)ctrl_mc;
-    }
-    if (explicit_socket >= 0 && explicit_socket <= 1) {
-        ev->cpu = (int8_t)explicit_socket;
-    } else if (!gnr_pos && fallback_cpu >= 0 && fallback_cpu <= 1 && ev->cpu < 0) {
-        ev->cpu = (int8_t)fallback_cpu;
+    if (!has_explicit_dimm_coord) {
+        if (!gnr_pos && ctrl_mc > 0 && ctrl_mc <= 11 && raw_chid == 0) {
+            ev->channel = (int8_t)ctrl_mc;
+        }
+        if (explicit_socket >= 0 && explicit_socket <= 1) {
+            ev->cpu = (int8_t)explicit_socket;
+        } else if (!gnr_pos && fallback_cpu >= 0 && fallback_cpu <= 1 && ev->cpu < 0) {
+            ev->cpu = (int8_t)fallback_cpu;
+        }
     }
     }
 
 
     if (bg >= 0 && ba >= 0) {
     if (bg >= 0 && ba >= 0) {
@@ -700,18 +766,36 @@ scan_anywhere:
                 }
                 }
                 return STL_LK_INLINE_TEMP;
                 return STL_LK_INLINE_TEMP;
             }
             }
+            "[" ("HS" | "HD") "_NODIMM]" {
+                if (tok[2] == 'S') ev->fw_family = 1;
+                extract_coords_and_addr(s, end, ev);
+                ev->subkind = 0; /* explicitly absent */
+                ev->val1 = 1;    /* PEI DRAM inventory marker */
+                return STL_LK_DIMM_INVENTORY;
+            }
             "[" ("HS" | "HD") "_DRAM]" {
             "[" ("HS" | "HD") "_DRAM]" {
                 if (tok[2] == 'S') ev->fw_family = 1;
                 if (tok[2] == 'S') ev->fw_family = 1;
                 extract_coords_and_addr(s, end, ev);
                 extract_coords_and_addr(s, end, ev);
-                /* Check Size:0 -> absent, else present */
+                /* Check Size:0 or absent/empty/not-installed -> absent, else present */
                 ev->subkind = 4;
                 ev->subkind = 4;
-                for (const uint8_t *p = YYCURSOR; p + 5 <= lim; p++) {
-                    if (memcmp(p, "Size:", 5) == 0) {
+                ev->val1 = 1;    /* PEI DRAM inventory marker */
+                for (const uint8_t *p = YYCURSOR; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_word(YYCURSOR, p, lim, "size", &af)) {
                         int32_t sz = 0;
                         int32_t sz = 0;
-                        if (parse_i32_at(p + 5, lim, &sz, NULL)) {
+                        if (parse_i32_at(af, lim, &sz, NULL)) {
                             ev->subkind = (sz > 0) ? 4 : 0;
                             ev->subkind = (sz > 0) ? 4 : 0;
                             ev->val0 = sz;
                             ev->val0 = sz;
+                            break;
                         }
                         }
+                    }
+                    if (match_ci_word(YYCURSOR, p, lim, "not installed", &af) ||
+                        match_ci_word(YYCURSOR, p, lim, "not present", &af) ||
+                        match_ci_word(YYCURSOR, p, lim, "no dimm", &af) ||
+                        match_ci_word(YYCURSOR, p, lim, "absent", &af) ||
+                        match_ci_word(YYCURSOR, p, lim, "empty", &af) ||
+                        match_ci_word(YYCURSOR, p, lim, "unpopulated", &af)) {
+                        ev->subkind = 0;
                         break;
                         break;
                     }
                     }
                 }
                 }
@@ -1072,7 +1156,9 @@ scan_anywhere:
                     const uint8_t *af = NULL;
                     const uint8_t *af = NULL;
                     if (match_ci_word(tok, p, lim, "not", &af) ||
                     if (match_ci_word(tok, p, lim, "not", &af) ||
                         match_ci_word(tok, p, lim, "empty", &af) ||
                         match_ci_word(tok, p, lim, "empty", &af) ||
-                        match_ci_word(tok, p, lim, "absent", &af)) {
+                        match_ci_word(tok, p, lim, "absent", &af) ||
+                        match_ci_word(tok, p, lim, "unpopulated", &af) ||
+                        match_ci_word(tok, p, lim, "nodimm", &af)) {
                         ev->subkind = 0;
                         ev->subkind = 0;
                         return STL_LK_DIMM_INVENTORY;
                         return STL_LK_DIMM_INVENTORY;
                     }
                     }

+ 108 - 29
native/stl_accel/src/actors.rs

@@ -187,6 +187,7 @@ pub enum IpmiJob {
         host: String,
         host: String,
         user: String,
         user: String,
         pass: String,
         pass: String,
+        refresh_sdr: bool,
     },
     },
     ExplicitCmd {
     ExplicitCmd {
         host: String,
         host: String,
@@ -805,12 +806,6 @@ pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     s.set("console_online", JsonVal::Bool(st.console_online));
     s.set("console_online", JsonVal::Bool(st.console_online));
     let power_str = if st.server_power == "off" {
     let power_str = if st.server_power == "off" {
         "off"
         "off"
-    } else if st.bmc_enabled
-        && !st.bmc_host.is_empty()
-        && st.bmc_state == "online"
-        && st.server_power == "unknown"
-    {
-        "on"
     } else {
     } else {
         st.server_power.as_str()
         st.server_power.as_str()
     };
     };
@@ -830,11 +825,16 @@ pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
         bp_state.as_str(),
         bp_state.as_str(),
         "completed" | "failed" | "stopped" | "interrupted"
         "completed" | "failed" | "stopped" | "interrupted"
     );
     );
+    let mt_post_complete = st.mt_report_sync_pending
+        || (st.plan_mt_started
+            && (st.hot.mt_pass_complete
+                || st.hot.mt_fail_complete
+                || st.mt_result.get_bool("complete").unwrap_or(false)));
     let run_state = if st.awaiting_dimm_replacement || bp_state == "blocked" {
     let run_state = if st.awaiting_dimm_replacement || bp_state == "blocked" {
         "blocked".to_string()
         "blocked".to_string()
     } else if is_terminal {
     } else if is_terminal {
         bp_state.clone()
         bp_state.clone()
-    } else if st.prompt_ready {
+    } else if st.prompt_ready && !mt_post_complete {
         "waiting_input".to_string()
         "waiting_input".to_string()
     } else {
     } else {
         bp_state.clone()
         bp_state.clone()
@@ -926,8 +926,11 @@ pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
         .get(&cpu_idx)
         .get(&cpu_idx)
         .map(|r| r.status == "pass" && r.algorithm_count > 0)
         .map(|r| r.status == "pass" && r.algorithm_count > 0)
         .unwrap_or(false);
         .unwrap_or(false);
-    let input_ready =
-        st.prompt_ready && !st.awaiting_dimm_replacement && bp_state != "blocked" && !is_terminal;
+    let input_ready = st.prompt_ready
+        && !st.awaiting_dimm_replacement
+        && bp_state != "blocked"
+        && !is_terminal
+        && !mt_post_complete;
     let mut input_obj = JsonVal::obj();
     let mut input_obj = JsonVal::obj();
     input_obj.set(
     input_obj.set(
         "id",
         "id",
@@ -991,15 +994,37 @@ pub(crate) fn build_qt_clean_station_entry(st: &StationState) -> JsonVal {
     }
     }
     s.set("channels", JsonVal::Arr(ch_arr));
     s.set("channels", JsonVal::Arr(ch_arr));
     s.set("task_batch", strip_private_keys_recursive(&st.task_batch));
     s.set("task_batch", strip_private_keys_recursive(&st.task_batch));
-    s.set(
-        "task_history",
-        JsonVal::Arr(
-            st.task_history
-                .iter()
-                .map(strip_private_keys_recursive)
-                .collect(),
-        ),
-    );
+    let recent_history_start = st.task_history.len().saturating_sub(10);
+    let compact_history: Vec<JsonVal> = st.task_history[recent_history_start..]
+        .iter()
+        .map(|entry| {
+            let mut slim = JsonVal::obj();
+            for k in [
+                "run_id",
+                "batch_id",
+                "station_id",
+                "boot_id",
+                "firmware_family",
+                "profile_index",
+                "profile_name",
+                "repeat_index",
+                "repeat_total",
+                "verdict",
+                "started_unix_ms",
+                "ended_unix_ms",
+                "summary_path",
+            ] {
+                if let Some(v) = entry.get(k) {
+                    slim.set(k, v.clone());
+                }
+            }
+            if let Some(sc) = entry.get("stage_completions") {
+                slim.set("stage_completions", sc.clone());
+            }
+            strip_private_keys_recursive(&slim)
+        })
+        .collect();
+    s.set("task_history", JsonVal::Arr(compact_history));
     s.set("task_status", JsonVal::Str(st.task_status.clone()));
     s.set("task_status", JsonVal::Str(st.task_status.clone()));
     s.set(
     s.set(
         "awaiting_dimm_replacement",
         "awaiting_dimm_replacement",
@@ -1125,7 +1150,7 @@ pub fn spawn_station_actor(
                             }
                             }
                         }
                         }
                     }
                     }
-                    IpmiJob::PollTelemetry { host, user, pass } => {
+                    IpmiJob::PollTelemetry { host, user, pass, refresh_sdr } => {
                         let host_reachable = !host.is_empty()
                         let host_reachable = !host.is_empty()
                             && (probe_tcp_port(&host, 22, 180) || probe_tcp_port(&host, 2200, 150));
                             && (probe_tcp_port(&host, 22, 180) || probe_tcp_port(&host, 2200, 150));
                         if !host_reachable {
                         if !host_reachable {
@@ -1170,6 +1195,9 @@ pub fn spawn_station_actor(
                                 power_opt = Some("off".to_string());
                                 power_opt = Some("off".to_string());
                             }
                             }
                         }
                         }
+                        if bmc_online && refresh_sdr {
+                            session.invalidate_sdr_cache();
+                        }
                         let sdr_opt = if bmc_online && power_opt.as_deref() != Some("off") {
                         let sdr_opt = if bmc_online && power_opt.as_deref() != Some("off") {
                             run_ipmi_with_session(
                             run_ipmi_with_session(
                                 Some(&mut session),
                                 Some(&mut session),
@@ -1382,6 +1410,7 @@ pub fn spawn_station_actor(
             host: st.bmc_host.clone(),
             host: st.bmc_host.clone(),
             user: st.bmc_user.clone(),
             user: st.bmc_user.clone(),
             pass: st.bmc_password.clone(),
             pass: st.bmc_password.clone(),
+            refresh_sdr: true,
         });
         });
     }
     }
 
 
@@ -1408,7 +1437,10 @@ pub fn spawn_station_actor(
 
 
             let mut registered_pty_fd: i32 = -1;
             let mut registered_pty_fd: i32 = -1;
             let mut cached_pxe_state = crate::storage::load_pxe_state(&data_dir);
             let mut cached_pxe_state = crate::storage::load_pxe_state(&data_dir);
-            let mut next_ipmi_poll_ms = now_ms() + 6000;
+            let mut next_ipmi_poll_ms = now_ms() + 3000;
+            let mut last_sdr_refresh_ms = now_ms();
+            let mut pending_sdr_refresh = false;
+            let mut last_seen_boot_id = st.boot_id.clone();
             let mut offline_since_ms: Option<i64> = None;
             let mut offline_since_ms: Option<i64> = None;
             let mut ev_tokens = [0u64; 8];
             let mut ev_tokens = [0u64; 8];
             let mut ev_masks = [0u32; 8];
             let mut ev_masks = [0u32; 8];
@@ -1667,10 +1699,11 @@ pub fn spawn_station_actor(
                                 }
                                 }
                             }
                             }
                             if let Some(pwr) = power {
                             if let Some(pwr) = power {
+                                let prev_power = st.server_power.clone();
                                 if pwr == "off" {
                                 if pwr == "off" {
                                     st.clear_all_dimm_temps();
                                     st.clear_all_dimm_temps();
                                     if !st.is_run_active() && !st.awaiting_dimm_replacement {
                                     if !st.is_run_active() && !st.awaiting_dimm_replacement {
-                                        st.reset_all_dimm_stages();
+                                        st.reset_dimms_for_new_boot();
                                     }
                                     }
                                     state_dirty = true;
                                     state_dirty = true;
                                 } else if pwr == "unknown" {
                                 } else if pwr == "unknown" {
@@ -1689,15 +1722,39 @@ pub fn spawn_station_actor(
                                     st.prompt_ready = false;
                                     st.prompt_ready = false;
                                     st.hot.prompt_ready = false;
                                     st.hot.prompt_ready = false;
                                     state_dirty = true;
                                     state_dirty = true;
-                                } else if pwr == "on" && st.observed_phase == "powered_off" {
-                                    st.observed_phase = "boot".to_string();
-                                    st.observed_detail = "power_on".to_string();
+                                } else if pwr == "on"
+                                    && (prev_power == "off" || st.observed_phase == "powered_off")
+                                {
+                                    let bp_state_now = st.boot_execution.get_str_or("state", "idle");
+                                    let was_blocked_or_terminal = st.awaiting_dimm_replacement
+                                        || st.has_any_failure_state()
+                                        || matches!(
+                                            bp_state_now.as_str(),
+                                            "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+                                        )
+                                        || matches!(
+                                            st.task_status.as_str(),
+                                            "failed" | "completed" | "interrupted"
+                                        );
+                                    // Never abort an already active test run (e.g. during Training/AMT/MT)
+                                    // just because a BMC IPMI power poll recovered/delivered late `off->on` past 20s.
+                                    if !st.is_run_active() || was_blocked_or_terminal {
+                                        st.clear_for_external_restart(now_ms(), "power_on", true);
+                                        st.cleaner.clear_halfline();
+                                    } else if st.observed_phase == "powered_off" {
+                                        st.observed_phase = "boot".to_string();
+                                        st.observed_detail = "power_on".to_string();
+                                    }
+                                    pending_sdr_refresh = true;
+                                    next_ipmi_poll_ms = now_ms() + 500;
                                     state_dirty = true;
                                     state_dirty = true;
                                 }
                                 }
                             }
                             }
                             if let Some(sdr) = sdr_output {
                             if let Some(sdr) = sdr_output {
-                                update_dimms_from_bmc_sdr(&mut st, &sdr);
-                                state_dirty = true;
+                                if st.server_power != "off" {
+                                    update_dimms_from_bmc_sdr(&mut st, &sdr);
+                                    state_dirty = true;
+                                }
                             }
                             }
                         }
                         }
                         StationMsg::TestInjectSerial {
                         StationMsg::TestInjectSerial {
@@ -1744,6 +1801,11 @@ pub fn spawn_station_actor(
                             pxe_snapshot,
                             pxe_snapshot,
                             reply_tx,
                             reply_tx,
                         } => {
                         } => {
+                            if let Some(ip) = pxe_snapshot.get_str("pxe_server_ip") {
+                                if !ip.trim().is_empty() {
+                                    st.pxe_server_ip = ip.trim().to_string();
+                                }
+                            }
                             cached_pxe_state = pxe_snapshot;
                             cached_pxe_state = pxe_snapshot;
                             step_boot_plan(&mut st, &contract);
                             step_boot_plan(&mut st, &contract);
                             step_task_batch(
                             step_task_batch(
@@ -1826,7 +1888,13 @@ pub fn spawn_station_actor(
                     && !st.mt_report_sync_pending
                     && !st.mt_report_sync_pending
                 {
                 {
                     let pxe_host = cached_pxe_state.get_str_or("pxe_host", "");
                     let pxe_host = cached_pxe_state.get_str_or("pxe_host", "");
-                    let min_ms = st.mt_started_unix_ms.max(st.run_started_unix_ms);
+                    let min_ms = if st.mt_started_unix_ms > 0 {
+                        st.mt_started_unix_ms
+                    } else if st.run_started_unix_ms > 0 {
+                        st.run_started_unix_ms
+                    } else {
+                        st.hot.observed_unix_ms.max(1)
+                    };
                     if crate::pxe::is_local_pxe_host(&pxe_host) {
                     if crate::pxe::is_local_pxe_host(&pxe_host) {
                         if let Some((report, full_path)) = crate::pxe::try_ingest_local_pxe_report(
                         if let Some((report, full_path)) = crate::pxe::try_ingest_local_pxe_report(
                             &pxe_tftp_dir,
                             &pxe_tftp_dir,
@@ -1921,22 +1989,33 @@ pub fn spawn_station_actor(
                     }
                     }
                 }
                 }
 
 
-                // 6. Periodic non-blocking BMC power + 24-ch SDR temperature poll
+                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;
+                }
+
+                // 6. Periodic non-blocking BMC power + 24-ch SDR temperature & DIMM presence poll
                 if enable_hw_bg_probes
                 if enable_hw_bg_probes
                     && st.bmc_enabled
                     && st.bmc_enabled
                     && !st.bmc_host.is_empty()
                     && !st.bmc_host.is_empty()
                     && now >= next_ipmi_poll_ms
                     && now >= next_ipmi_poll_ms
                 {
                 {
-                    next_ipmi_poll_ms = now + 8000;
+                    next_ipmi_poll_ms = now + if st.bmc_state == "online" { 3000 } else { 6000 };
+                    let do_refresh = pending_sdr_refresh || now.saturating_sub(last_sdr_refresh_ms) >= 20_000;
                     if ipmi_poll_inflight
                     if ipmi_poll_inflight
                         .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
                         .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
                         .is_ok()
                         .is_ok()
                     {
                     {
+                        if do_refresh {
+                            pending_sdr_refresh = false;
+                            last_sdr_refresh_ms = now;
+                        }
                         if ipmi_tx_for_actor
                         if ipmi_tx_for_actor
                             .send(IpmiJob::PollTelemetry {
                             .send(IpmiJob::PollTelemetry {
                                 host: st.bmc_host.clone(),
                                 host: st.bmc_host.clone(),
                                 user: st.bmc_user.clone(),
                                 user: st.bmc_user.clone(),
                                 pass: st.bmc_password.clone(),
                                 pass: st.bmc_password.clone(),
+                                refresh_sdr: do_refresh,
                             })
                             })
                             .is_err()
                             .is_err()
                         {
                         {

+ 216 - 4
native/stl_accel/src/api.rs

@@ -60,6 +60,7 @@ pub struct AppHub {
     pub audit_book: Mutex<AuditEventBook>,
     pub audit_book: Mutex<AuditEventBook>,
     pub pxe_state: RwLock<JsonVal>,
     pub pxe_state: RwLock<JsonVal>,
     pub auto_cmd_seq: AtomicU64,
     pub auto_cmd_seq: AtomicU64,
+    pub thermal_hub: Arc<crate::thermal_mcu::ThermalMcuHub>,
 }
 }
 
 
 pub type ServerContext = AppHub;
 pub type ServerContext = AppHub;
@@ -204,6 +205,9 @@ impl AppHub {
             stations.insert(sid, handle);
             stations.insert(sid, handle);
         }
         }
 
 
+        let thermal_hub =
+            crate::thermal_mcu::ThermalMcuHub::spawn(args.data_dir.clone(), stations.clone());
+
         let hub = Arc::new(Self {
         let hub = Arc::new(Self {
             version: args.version.clone(),
             version: args.version.clone(),
             commit: args.commit.clone(),
             commit: args.commit.clone(),
@@ -230,6 +234,7 @@ impl AppHub {
             }),
             }),
             pxe_state: RwLock::new(pxe_state),
             pxe_state: RwLock::new(pxe_state),
             auto_cmd_seq: AtomicU64::new(1),
             auto_cmd_seq: AtomicU64::new(1),
+            thermal_hub,
         });
         });
 
 
         // Prime initial zero-copy QtClean state snapshot immediately
         // Prime initial zero-copy QtClean state snapshot immediately
@@ -546,6 +551,105 @@ impl AppHub {
         format!("{}-{}-{}", prefix, now_ms(), seq)
         format!("{}-{}-{}", prefix, now_ms(), seq)
     }
     }
 
 
+    fn execute_thermal_action(
+        &self,
+        sid_override: Option<&str>,
+        params: &JsonVal,
+        default_operator: &str,
+    ) -> Result<JsonVal, String> {
+        let action = params.get_str_or("action", "");
+        if action.is_empty() {
+            return Err("缺少 action 字段".to_string());
+        }
+        let operator = params.get_str_or("operator", default_operator);
+        let sid = sid_override
+            .filter(|s| !s.is_empty())
+            .map(|s| s.to_string())
+            .unwrap_or_else(|| params.get_str_or("station_id", "S1"));
+        let res = self.thermal_hub.execute_action(&sid, &action, params)?;
+        let should_audit = matches!(
+            action.as_str(),
+            "save_mappings"
+                | "connect"
+                | "disconnect"
+                | "set_temp"
+                | "stop_preheat"
+                | "skip_preheat"
+                | "start_pid"
+                | "finish_control"
+                | "stop_heaters"
+                | "stop_fans"
+                | "emergency_stop"
+                | "pid_calibrate"
+                | "manual_duty"
+                | "start_record"
+                | "stop_record"
+                | "configure_safety"
+        );
+        if should_audit {
+            let summary = match action.as_str() {
+                "save_mappings" => format!(
+                    "保存 BMC 机位 ↔ 高温罩串口映射 ({} 项)",
+                    res.get_i64("count").unwrap_or(1)
+                ),
+                "connect" => format!(
+                    "连接工位 {} 高温罩 ({})",
+                    sid,
+                    params.get_str_or("mode", "serial")
+                ),
+                "disconnect" => format!("断开工位 {} 高温罩连接", sid),
+                "set_temp" => format!(
+                    "高温罩开启设温控温: {}℃",
+                    params
+                        .get_i64("target_c")
+                        .or_else(|| params.get_i64("temp_c"))
+                        .unwrap_or(0)
+                ),
+                "stop_preheat" => "高温罩停止预加热/退出控温 (0x05)".to_string(),
+                "skip_preheat" => "高温罩跳过预热直接进入 PID (0x06)".to_string(),
+                "start_pid" => "高温罩直接启动 PID 闭环控温 (0x07)".to_string(),
+                "finish_control" => {
+                    let purge = params.get_bool("cooling_purge").unwrap_or(true);
+                    if purge {
+                        "高温罩控温结束并开启风扇吹扫散热 (0x08 00)".to_string()
+                    } else {
+                        "高温罩控温结束不吹扫 (0x08 01)".to_string()
+                    }
+                }
+                "stop_heaters" => "高温罩停止并锁存全部加热块 (0x0A)".to_string(),
+                "stop_fans" => "高温罩停止并锁存全部风扇 (0x0B)".to_string(),
+                "emergency_stop" => "高温罩一键紧急全停(35路归零 + 0x05 + 0x0A)".to_string(),
+                "pid_calibrate" => format!(
+                    "高温罩 PID 参数标定: {}",
+                    params.get_str_or("expr", "(回读)")
+                ),
+                "manual_duty" => "高温罩 35 路手动占空比调试 (0x46)".to_string(),
+                "start_record" => format!(
+                    "开始高温罩数据记录 (模板格式): {}",
+                    res.get_str_or("csv_filename", "")
+                ),
+                "stop_record" => "停止高温罩本地 CSV 记录".to_string(),
+                "configure_safety" => format!(
+                    "更新高温罩安全护栏 (看门狗={}s, 超温熔断={}℃)",
+                    res.get_i64("lease_sec").unwrap_or(0),
+                    res.get_i64("overtemp_cutoff_c").unwrap_or(95)
+                ),
+                _ => format!("执行高温罩温控动作: {}", action),
+            };
+            self.commit_audit(
+                &sid,
+                &operator,
+                AuditRecordDraft {
+                    category: "thermal_mcu".to_string(),
+                    action: action.clone(),
+                    summary,
+                    details: res.clone(),
+                },
+            );
+        }
+        Ok(res)
+    }
+
     fn execute_actor_command(
     fn execute_actor_command(
         &self,
         &self,
         sid: &str,
         sid: &str,
@@ -1290,8 +1394,11 @@ impl AppHub {
                     return Ok(pending_item);
                     return Ok(pending_item);
                 }
                 }
 
 
-                let exec_res =
-                    self.execute_actor_command(&sid, &sub_method, &sub_args, &operator);
+                let exec_res = if sub_method == "ThermalAction" {
+                    self.execute_thermal_action(Some(&sid), &sub_args, &operator)
+                } else {
+                    self.execute_actor_command(&sid, &sub_method, &sub_args, &operator)
+                };
                 let completed_item = match exec_res {
                 let completed_item = match exec_res {
                     Ok(res_val) => self.finalize_command(&cmd_id, |item| {
                     Ok(res_val) => self.finalize_command(&cmd_id, |item| {
                         item.set("state", JsonVal::Str("succeeded".to_string()));
                         item.set("state", JsonVal::Str("succeeded".to_string()));
@@ -1450,6 +1557,11 @@ impl AppHub {
                     Err(_) => Err(("INTERNAL".to_string(), "配置 N540 超时".to_string())),
                     Err(_) => Err(("INTERNAL".to_string(), "配置 N540 超时".to_string())),
                 }
                 }
             }
             }
+            "GetThermalConsole" => self.thermal_hub.get_snapshot(params),
+            "ThermalAction" => match self.execute_thermal_action(None, params, "web") {
+                Ok(res) => Ok(res),
+                Err(msg) => Err(("FAILED_PRECONDITION".to_string(), msg)),
+            },
             other => Err((
             other => Err((
                 "UNIMPLEMENTED".to_string(),
                 "UNIMPLEMENTED".to_string(),
                 format!("不支持的 RPC 方法: {}", other),
                 format!("不支持的 RPC 方法: {}", other),
@@ -1534,13 +1646,13 @@ fn write_ws_frame(stream: &Mutex<TcpStream>, opcode: u8, payload: &[u8]) -> bool
     written == (hdr_len + len) as i64
     written == (hdr_len + len) as i64
 }
 }
 
 
-fn parse_query_view(raw_target: &str) -> String {
+fn parse_query_param(raw_target: &str, key: &str) -> String {
     let Some((_, qs)) = raw_target.split_once('?') else {
     let Some((_, qs)) = raw_target.split_once('?') else {
         return String::new();
         return String::new();
     };
     };
     for pair in qs.split('&') {
     for pair in qs.split('&') {
         if let Some((k, v)) = pair.split_once('=') {
         if let Some((k, v)) = pair.split_once('=') {
-            if k == "view" {
+            if k == key {
                 return v.to_string();
                 return v.to_string();
             }
             }
         }
         }
@@ -1548,6 +1660,10 @@ fn parse_query_view(raw_target: &str) -> String {
     String::new()
     String::new()
 }
 }
 
 
+fn parse_query_view(raw_target: &str) -> String {
+    parse_query_param(raw_target, "view")
+}
+
 fn handle_ws_loop(
 fn handle_ws_loop(
     mut read_stream: TcpStream,
     mut read_stream: TcpStream,
     write_stream: Arc<Mutex<TcpStream>>,
     write_stream: Arc<Mutex<TcpStream>>,
@@ -1824,6 +1940,102 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
         return;
         return;
     }
     }
 
 
+    if path_only == "/api/thermal/export.csv" {
+        let req_sid = parse_query_param(raw_target, "station_id");
+        let sid = if req_sid.is_empty() {
+            "S1".to_string()
+        } else {
+            req_sid
+                .chars()
+                .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
+                .take(16)
+                .collect()
+        };
+        match hub.thermal_hub.export_session_csv(&sid) {
+            Ok((fname, csv_text)) => {
+                let body = csv_text.into_bytes();
+                let hdr = format!(
+                    "HTTP/1.1 200 OK\r\nContent-Type: text/csv; charset=utf-8\r\nContent-Length: {}\r\nContent-Disposition: attachment; filename=\"{}\"\r\nCache-Control: no-cache\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n",
+                    body.len(),
+                    fname
+                );
+                let _ = stream.write_all(hdr.as_bytes());
+                if method == "GET" {
+                    let _ = stream.write_all(&body);
+                }
+                let _ = stream.flush();
+            }
+            Err(msg) => {
+                let body = msg.into_bytes();
+                let hdr = format!(
+                    "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+                    body.len()
+                );
+                let _ = stream.write_all(hdr.as_bytes());
+                if method == "GET" {
+                    let _ = stream.write_all(&body);
+                }
+                let _ = stream.flush();
+            }
+        }
+        return;
+    }
+
+    if let Some(fname) = path_only.strip_prefix("/api/thermal/logs/") {
+        let safe = !fname.is_empty()
+            && !fname.contains("..")
+            && !fname.contains('/')
+            && !fname.contains('\\')
+            && fname
+                .bytes()
+                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'));
+        if !safe {
+            let resp = "HTTP/1.1 400 Bad Request\r\nContent-Length: 11\r\nConnection: close\r\n\r\nBad Request";
+            let _ = stream.write_all(resp.as_bytes());
+            return;
+        }
+        let log_path = hub.thermal_hub.logs_dir.join(fname);
+        let Ok(mut f) = fs::File::open(&log_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());
+            return;
+        };
+        let Ok(meta) = f.metadata() else {
+            let resp = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 21\r\nConnection: close\r\n\r\nInternal Server Error";
+            let _ = stream.write_all(resp.as_bytes());
+            return;
+        };
+        let ctype = if fname.ends_with(".csv") {
+            "text/csv; charset=utf-8"
+        } else if fname.ends_with(".jsonl") {
+            "application/x-ndjson; charset=utf-8"
+        } else {
+            "application/octet-stream"
+        };
+        let hdr = format!(
+            "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\nContent-Disposition: attachment; filename=\"{}\"\r\nCache-Control: no-cache\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n",
+            ctype,
+            meta.len(),
+            fname
+        );
+        if stream.write_all(hdr.as_bytes()).is_ok() && method == "GET" {
+            let mut chunk = vec![0u8; 65536];
+            loop {
+                match f.read(&mut chunk) {
+                    Ok(0) => break,
+                    Ok(n) => {
+                        if stream.write_all(&chunk[..n]).is_err() {
+                            break;
+                        }
+                    }
+                    Err(_) => break,
+                }
+            }
+        }
+        let _ = stream.flush();
+        return;
+    }
+
     let rel_path = path_only.trim_start_matches('/');
     let rel_path = path_only.trim_start_matches('/');
     let rel_clean = if rel_path.is_empty() {
     let rel_clean = if rel_path.is_empty() {
         "index.html"
         "index.html"

+ 33 - 13
native/stl_accel/src/commands.rs

@@ -149,7 +149,13 @@ pub fn handle_station_command_nonblocking(
             StationCmdExec::Immediate(Ok(res), None)
             StationCmdExec::Immediate(Ok(res), None)
         }
         }
         "ConfirmDimmReplacement" => {
         "ConfirmDimmReplacement" => {
+            let had_prev_boot = !st.boot_id.is_empty();
             st.confirm_dimm_replacement();
             st.confirm_dimm_replacement();
+            if had_prev_boot {
+                st.boot_seq += 1;
+                st.hot.boot_seq = st.boot_seq;
+                st.boot_id = format!("B-{}-{}", st.station_id, st.boot_seq);
+            }
             save_station_settings(data_dir, st);
             save_station_settings(data_dir, st);
             let mut res = JsonVal::obj();
             let mut res = JsonVal::obj();
             res.set("station_id", JsonVal::Str(sid));
             res.set("station_id", JsonVal::Str(sid));
@@ -185,8 +191,10 @@ pub fn handle_station_command_nonblocking(
                         st.uip_overrides = ovs.clone();
                         st.uip_overrides = ovs.clone();
                     } else if args.get("memory_params").is_some() {
                     } else if args.get("memory_params").is_some() {
                         // Full Qt memory_params snapshot replaces previous ICT parameter overrides
                         // Full Qt memory_params snapshot replaces previous ICT parameter overrides
-                        // while preserving any prior explicit RMT/PXE directives unless overwritten below.
-                        st.uip_overrides.retain(|x| x.get_str_or("id", "") == "rmt");
+                        // while preserving any prior explicit RMT/maskmain/PXE directives unless overwritten below.
+                        st.uip_overrides.retain(|x| {
+                            matches!(x.get_str_or("id", "").as_str(), "rmt" | "rmt.userdef" | "maskmain")
+                        });
                         if args.get_arr("uip_raw_commands").is_none() {
                         if args.get_arr("uip_raw_commands").is_none() {
                             st.uip_raw_commands
                             st.uip_raw_commands
                                 .retain(|c| c.trim().to_ascii_lowercase().starts_with("pxe "));
                                 .retain(|c| c.trim().to_ascii_lowercase().starts_with("pxe "));
@@ -198,9 +206,13 @@ pub fn handle_station_command_nonblocking(
                             .filter_map(|x| x.as_str().map(|s| s.to_string()))
                             .filter_map(|x| x.as_str().map(|s| s.to_string()))
                             .collect();
                             .collect();
                     }
                     }
-                    let want_rmt = args
-                        .get_bool("run_rmt")
-                        .or_else(|| args.get("rmt").and_then(|r| r.get_bool("enabled")));
+                    let rmt_disable_only = FirmwareContract::rmt_selected_is_disable_only(args.get("rmt"));
+                    let want_rmt = if rmt_disable_only {
+                        Some(false)
+                    } else {
+                        args.get_bool("run_rmt")
+                            .or_else(|| args.get("rmt").and_then(|r| r.get_bool("enabled")))
+                    };
                     if let Some(en) = want_rmt {
                     if let Some(en) = want_rmt {
                         st.boot_plan.set("run_rmt", JsonVal::Bool(en));
                         st.boot_plan.set("run_rmt", JsonVal::Bool(en));
                     }
                     }
@@ -226,6 +238,13 @@ pub fn handle_station_command_nonblocking(
                                 st.uip_overrides.push(ov);
                                 st.uip_overrides.push(ov);
                             }
                             }
                         }
                         }
+                        if let Some(en) = want_rmt {
+                            FirmwareContract::apply_rmt_policy_to_uip_overrides(
+                                &mut st.uip_overrides,
+                                en,
+                                fw_fam,
+                            );
+                        }
                         for r in built_raws {
                         for r in built_raws {
                             if !st.uip_raw_commands.contains(&r) {
                             if !st.uip_raw_commands.contains(&r) {
                                 st.uip_raw_commands.push(r);
                                 st.uip_raw_commands.push(r);
@@ -236,15 +255,11 @@ pub fn handle_station_command_nonblocking(
                 "rmt" => {
                 "rmt" => {
                     let en = !matches!(action.as_str(), "disable" | "skip" | "skip_rmt" | "off" | "false");
                     let en = !matches!(action.as_str(), "disable" | "skip" | "skip_rmt" | "off" | "false");
                     st.boot_plan.set("run_rmt", JsonVal::Bool(en));
                     st.boot_plan.set("run_rmt", JsonVal::Bool(en));
-                    st.uip_overrides.retain(|x| x.get_str_or("id", "") != "rmt");
-                    let mut o = JsonVal::obj();
-                    o.set("id", JsonVal::Str("rmt".to_string()));
-                    o.set("mode", JsonVal::Str("override".to_string()));
-                    o.set(
-                        "value",
-                        JsonVal::Str(if en { "enable" } else { "disable" }.to_string()),
+                    FirmwareContract::apply_rmt_policy_to_uip_overrides(
+                        &mut st.uip_overrides,
+                        en,
+                        fw_fam,
                     );
                     );
-                    st.uip_overrides.push(o);
                 }
                 }
                 "amt" => {
                 "amt" => {
                     let en = !matches!(
                     let en = !matches!(
@@ -313,6 +328,9 @@ pub fn handle_station_command_nonblocking(
                             "ADDRLIMHI",
                             "ADDRLIMHI",
                             "addr_lo",
                             "addr_lo",
                             "addr_hi",
                             "addr_hi",
+                            "ecc",
+                            "eccpoll",
+                            "debuglog",
                         ] {
                         ] {
                             st.mt_selection.remove(stale);
                             st.mt_selection.remove(stale);
                         }
                         }
@@ -1001,6 +1019,7 @@ pub fn handle_station_command_nonblocking(
                 .cloned()
                 .cloned()
                 .unwrap_or_else(|| st.mt_selection.clone());
                 .unwrap_or_else(|| st.mt_selection.clone());
             let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
             let pxe_server_ip = pxe_state.get_str_or("pxe_server_ip", "192.168.0.10");
+            st.pxe_server_ip = pxe_server_ip.clone();
             let cfg_text = render_mt86_cfg_text(&sel, &pxe_server_ip);
             let cfg_text = render_mt86_cfg_text(&sel, &pxe_server_ip);
             let pxe_host = pxe_state.get_str_or("pxe_host", "");
             let pxe_host = pxe_state.get_str_or("pxe_host", "");
             sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text);
             sync_mt86_cfg_all_candidates(&pxe_host, pxe_tftp_dir, &cfg_text);
@@ -1575,6 +1594,7 @@ pub fn handle_station_command_nonblocking(
         }
         }
         "ConfigurePxe" => match apply_pxe_configuration(pxe_state, args, data_dir, pxe_tftp_dir) {
         "ConfigurePxe" => match apply_pxe_configuration(pxe_state, args, data_dir, pxe_tftp_dir) {
             Ok(pxe_snap) => {
             Ok(pxe_snap) => {
+                st.pxe_server_ip = pxe_snap.get_str_or("pxe_server_ip", "192.168.0.10");
                 if args.get_bool("apply_to_uip").unwrap_or(false) {
                 if args.get_bool("apply_to_uip").unwrap_or(false) {
                     st.uip_raw_commands
                     st.uip_raw_commands
                         .retain(|c| !c.trim().to_ascii_lowercase().starts_with("pxe "));
                         .retain(|c| !c.trim().to_ascii_lowercase().starts_with("pxe "));

+ 150 - 9
native/stl_accel/src/devices.rs

@@ -445,6 +445,14 @@ impl PersistentIpmiSession {
         self.handle = -1;
         self.handle = -1;
     }
     }
 
 
+    pub fn invalidate_sdr_cache(&mut self) {
+        if self.handle > 0 {
+            unsafe {
+                lib::c_ipmi_invalidate_sdr_cache(self.handle);
+            }
+        }
+    }
+
     pub fn ensure_connected(&mut self, host: &str, user: &str, pass: &str) -> bool {
     pub fn ensure_connected(&mut self, host: &str, user: &str, pass: &str) -> bool {
         if self.handle > 0
         if self.handle > 0
             && self.host == host
             && self.host == host
@@ -715,15 +723,91 @@ pub fn run_ipmi_cmd(host: &str, user: &str, pass: &str, args: &[&str]) -> Result
 pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
 pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
     let now = now_ms();
     let now = now_ms();
     let mut seen_valid = [false; 24];
     let mut seen_valid = [false; 24];
+    let mut seen_temp_sensor = [false; 24];
+    let mut seen_discrete_present = [false; 24];
+    let mut seen_discrete_absent = [false; 24];
+    let mut seen_discrete_disabled = [false; 24];
+
     for line in sdr_output.lines() {
     for line in sdr_output.lines() {
         let parts: Vec<&str> = line.split('|').map(|s| s.trim()).collect();
         let parts: Vec<&str> = line.split('|').map(|s| s.trim()).collect();
         if parts.len() < 2 {
         if parts.len() < 2 {
             continue;
             continue;
         }
         }
         let sensor_name = parts[0].to_ascii_uppercase();
         let sensor_name = parts[0].to_ascii_uppercase();
+        let mut parsed_discrete_mem: Option<u16> = None;
+        let mut parsed_discrete_pres: Option<u16> = None;
+        let mut parsed_discrete_devpres: Option<u16> = None;
+        for col in &parts[1..] {
+            let lower = col.to_ascii_lowercase();
+            if let Some(pos) = lower.find("discrete_mem=0x") {
+                let hex = &lower[pos + "discrete_mem=0x".len()..];
+                let tok: String = hex.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
+                if let Ok(v) = u16::from_str_radix(&tok, 16) {
+                    parsed_discrete_mem = Some(v);
+                }
+            } else if let Some(pos) = lower.find("discrete_presence=0x") {
+                let hex = &lower[pos + "discrete_presence=0x".len()..];
+                let tok: String = hex.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
+                if let Ok(v) = u16::from_str_radix(&tok, 16) {
+                    parsed_discrete_pres = Some(v);
+                }
+            } else if let Some(pos) = lower.find("discrete_devpres=0x") {
+                let hex = &lower[pos + "discrete_devpres=0x".len()..];
+                let tok: String = hex.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
+                if let Ok(v) = u16::from_str_radix(&tok, 16) {
+                    parsed_discrete_devpres = Some(v);
+                }
+            }
+        }
+
+        if parsed_discrete_mem.is_some()
+            || parsed_discrete_pres.is_some()
+            || parsed_discrete_devpres.is_some()
+        {
+            let Some(slot_idx) = map_sdr_dimm_slot_inner(&sensor_name, true) else {
+                continue;
+            };
+            if slot_idx < 24 {
+                if let Some(v) = parsed_discrete_mem {
+                    // Sensor Type 0x0C (Memory): bit 6 (0x0040) = Presence detected, bit 4 (0x0010) = Disabled.
+                    // Note: many BMCs (e.g. .165/.166/.167 DIMM_CPU*_Stat) report 0x0000 when healthy even for plugged DIMMs,
+                    // so v == 0 must NOT be treated as Absent.
+                    if (v & 0x0040) != 0 {
+                        seen_discrete_present[slot_idx] = true;
+                    }
+                    if (v & 0x0010) != 0 {
+                        seen_discrete_disabled[slot_idx] = true;
+                    }
+                }
+                if let Some(v) = parsed_discrete_pres {
+                    // Sensor Type 0x25 (Entity Presence), ERT 0x6F: bit 0 = Present, bit 1 = Absent, bit 2 = Disabled
+                    if (v & 0x0001) != 0 {
+                        seen_discrete_present[slot_idx] = true;
+                    } else if (v & 0x0002) != 0 || v == 0 {
+                        seen_discrete_absent[slot_idx] = true;
+                    }
+                    if (v & 0x0004) != 0 {
+                        seen_discrete_disabled[slot_idx] = true;
+                    }
+                }
+                if let Some(v) = parsed_discrete_devpres {
+                    // IPMI Spec ERT 0x08 (Device Present): bit 0 = Removed/Absent, bit 1 = Inserted/Present
+                    if (v & 0x0002) != 0 {
+                        seen_discrete_present[slot_idx] = true;
+                    } else if (v & 0x0001) != 0 || v == 0 {
+                        seen_discrete_absent[slot_idx] = true;
+                    }
+                }
+            }
+            continue;
+        }
+
         let Some(slot_idx) = map_sdr_sensor_to_slot(&sensor_name) else {
         let Some(slot_idx) = map_sdr_sensor_to_slot(&sensor_name) else {
             continue;
             continue;
         };
         };
+        if slot_idx < 24 {
+            seen_temp_sensor[slot_idx] = true;
+        }
         let mut parsed_temp: Option<f64> = None;
         let mut parsed_temp: Option<f64> = None;
         for col in &parts[1..] {
         for col in &parts[1..] {
             let lower = col.to_ascii_lowercase();
             let lower = col.to_ascii_lowercase();
@@ -739,6 +823,8 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
         if let Some(temp_c) = parsed_temp {
         if let Some(temp_c) = parsed_temp {
             if slot_idx < 24 {
             if slot_idx < 24 {
                 seen_valid[slot_idx] = true;
                 seen_valid[slot_idx] = true;
+                st.had_bmc_sdr[slot_idx] = true;
+                st.sdr_absent_streak[slot_idx] = 0;
             }
             }
             if let Some(slot) = st.dimms.get_mut(slot_idx) {
             if let Some(slot) = st.dimms.get_mut(slot_idx) {
                 slot.value_c = Some(temp_c);
                 slot.value_c = Some(temp_c);
@@ -754,18 +840,73 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
             st.sync_dimm_to_soa(slot_idx);
             st.sync_dimm_to_soa(slot_idx);
         }
         }
     }
     }
+
+    let any_valid_temp = seen_valid.iter().any(|&v| v);
+    let any_discrete_present = seen_discrete_present.iter().any(|&v| v);
+
     for idx in 0..24 {
     for idx in 0..24 {
-        if !seen_valid[idx] && st.dimms[idx].source == "bmc_sdr" {
-            st.dimms[idx].value_c = None;
-            st.dimms[idx].quality = "unavailable".to_string();
-            st.dimms[idx].source.clear();
-            st.dimms[idx].received_ms = 0;
+        if seen_discrete_present[idx] && !seen_valid[idx] {
+            st.sdr_absent_streak[idx] = 0;
+            st.dimms[idx].presence = "present".to_string();
+            if st.dimms[idx].enabled == "unknown" {
+                st.dimms[idx].enabled = if seen_discrete_disabled[idx] {
+                    "disabled"
+                } else {
+                    "enabled"
+                }
+                .to_string();
+            }
+            st.backfill_completed_stages_for_slot(idx);
+            st.sync_dimm_to_soa(idx);
+        }
+        if !seen_valid[idx] {
+            if st.dimms[idx].source == "bmc_sdr" {
+                st.dimms[idx].value_c = None;
+                st.dimms[idx].quality = "unavailable".to_string();
+                st.dimms[idx].source.clear();
+                st.dimms[idx].received_ms = 0;
+            }
+            let protected_by_current_fail = st.dimm_seen_in_boot[idx]
+                && (st.dimms[idx].enabled == "disabled"
+                    || !st.dimms[idx].failed_stage.is_empty());
+            if !protected_by_current_fail {
+                let server_idle_post_training = st.server_power == "on"
+                    && !st.is_run_active()
+                    && !matches!(st.observed_phase.as_str(), "boot" | "uip" | "training");
+                let discrete_says_absent = (any_discrete_present || server_idle_post_training)
+                    && seen_discrete_absent[idx]
+                    && !seen_discrete_present[idx];
+                let temp_says_absent = any_valid_temp
+                    && !seen_discrete_present[idx]
+                    && (seen_temp_sensor[idx] || !st.dimm_seen_in_boot[idx] || st.had_bmc_sdr[idx]);
+                let last_dimm_unplugged = !any_valid_temp
+                    && (seen_temp_sensor[idx] || seen_discrete_absent[idx])
+                    && st.had_bmc_sdr[idx]
+                    && server_idle_post_training;
+                if discrete_says_absent || temp_says_absent || last_dimm_unplugged {
+                    st.sdr_absent_streak[idx] = st.sdr_absent_streak[idx].saturating_add(1);
+                    let threshold = if !st.dimm_seen_in_boot[idx] { 1 } else { 2 };
+                    if st.sdr_absent_streak[idx] >= threshold
+                        || st.dimms[idx].presence == "unknown"
+                    {
+                        st.dimms[idx] = crate::results::DimmSlot::empty();
+                        st.dimms[idx].presence = "absent".to_string();
+                        st.dimms[idx].quality = "unavailable".to_string();
+                        st.dimm_seen_in_boot[idx] = false;
+                        st.had_bmc_sdr[idx] = false;
+                    }
+                }
+            }
             st.sync_dimm_to_soa(idx);
             st.sync_dimm_to_soa(idx);
         }
         }
     }
     }
 }
 }
 
 
 pub fn map_sdr_sensor_to_slot(sensor: &str) -> Option<usize> {
 pub fn map_sdr_sensor_to_slot(sensor: &str) -> Option<usize> {
+    map_sdr_dimm_slot_inner(sensor, false)
+}
+
+fn map_sdr_dimm_slot_inner(sensor: &str, allow_stat: bool) -> Option<usize> {
     let s = sensor.trim().to_ascii_uppercase();
     let s = sensor.trim().to_ascii_uppercase();
     if !s.contains("DIMM") {
     if !s.contains("DIMM") {
         return None;
         return None;
@@ -775,10 +916,10 @@ pub fn map_sdr_sensor_to_slot(sensor: &str) -> Option<usize> {
         .filter(|t| !t.is_empty())
         .filter(|t| !t.is_empty())
         .collect();
         .collect();
     // Ignore non-temperature DIMM power / status sensors (e.g. DIMMG0_Power, DIMM_CPU0_A_Stat)
     // Ignore non-temperature DIMM power / status sensors (e.g. DIMMG0_Power, DIMM_CPU0_A_Stat)
-    if tokens
-        .iter()
-        .any(|&t| matches!(t, "POWER" | "PWR" | "STAT" | "STATUS" | "WATTS"))
-    {
+    if tokens.iter().any(|&t| {
+        matches!(t, "POWER" | "PWR" | "WATTS")
+            || (!allow_stat && matches!(t, "STAT" | "STATUS"))
+    }) {
         return None;
         return None;
     }
     }
 
 

+ 157 - 26
native/stl_accel/src/firmware.rs

@@ -155,6 +155,108 @@ impl FirmwareContract {
         root
         root
     }
     }
 
 
+    pub fn rmt_selected_is_disable_only(rmt_cfg: Option<&JsonVal>) -> bool {
+        let Some(r_obj) = rmt_cfg else {
+            return false;
+        };
+        let Some(sel) = r_obj.get_arr("selected") else {
+            return false;
+        };
+        let mut bare_enable = false;
+        let mut bare_disable = false;
+        let mut bare_backside = false;
+        for item in sel {
+            let Some(s) = item.as_str() else { continue };
+            let cmd_part = s.split('(').next().unwrap_or(s).trim().to_ascii_lowercase();
+            if cmd_part == "rmt enable" || cmd_part == "rmt" || s.contains("Rank Margin Tool") || cmd_part == "enable" {
+                bare_enable = true;
+            } else if cmd_part == "rmt disable" || cmd_part == "disable" {
+                bare_disable = true;
+            } else if cmd_part == "rmt backside" || cmd_part == "backside" {
+                bare_backside = true;
+            }
+        }
+        bare_disable && !bare_enable && !bare_backside
+    }
+
+    pub fn upsert_maskmain_steps(ovs: &mut Vec<JsonVal>, add_steps: &[u32], remove_steps: &[u32]) {
+        let mut steps: BTreeSet<u32> = BTreeSet::new();
+        if let Some(existing) = ovs.iter().find(|x| x.get_str_or("id", "") == "maskmain") {
+            let mode = existing.get_str_or("mode", "override");
+            if mode == "override" {
+                let raw = existing.get_str_or("value", "");
+                if let Ok(parsed) = Self::parse_multi_steps("maskmain", &raw, 101) {
+                    steps.extend(parsed);
+                }
+            }
+        }
+        for s in remove_steps {
+            steps.remove(s);
+        }
+        for s in add_steps {
+            if *s <= 101 {
+                steps.insert(*s);
+            }
+        }
+        ovs.retain(|x| x.get_str_or("id", "") != "maskmain");
+        if !steps.is_empty() {
+            let joined = steps
+                .iter()
+                .map(|v| v.to_string())
+                .collect::<Vec<_>>()
+                .join(",");
+            let mut o = JsonVal::obj();
+            o.set("id", JsonVal::Str("maskmain".to_string()));
+            o.set("mode", JsonVal::Str("override".to_string()));
+            o.set("value", JsonVal::Str(joined));
+            ovs.push(o);
+        }
+    }
+
+    /// Dual-firmware RMT policy normalization:
+    /// - `cxmt`: skip RMT via `rmt disable`, run RMT via `rmt enable` / `backside`.
+    /// - `hovsee` (`108_VD012` / `107_VD012` / `101_VD013`): NEVER emit unsupported `rmt disable`;
+    ///   skip RMT + Draw Eye Test via `maskmain 48` + `maskmain 49` while keeping step `41` (`DDR Training`) unmasked.
+    pub fn apply_rmt_policy_to_uip_overrides(
+        ovs: &mut Vec<JsonVal>,
+        want_rmt: bool,
+        fw_family_name: &str,
+    ) {
+        if !want_rmt {
+            ovs.retain(|x| {
+                let id = x.get_str_or("id", "");
+                id != "rmt" && id != "rmt.userdef"
+            });
+            if fw_family_name == "cxmt" {
+                Self::upsert_maskmain_steps(ovs, &[], &[48, 49]);
+                let mut o = JsonVal::obj();
+                o.set("id", JsonVal::Str("rmt".to_string()));
+                o.set("mode", JsonVal::Str("override".to_string()));
+                o.set("value", JsonVal::Str("disable".to_string()));
+                ovs.push(o);
+            } else {
+                // Keep step 41 (DDR Training) unmasked; mask 48 (Rank Margin Tool) + 49 (Draw Eye Test)
+                Self::upsert_maskmain_steps(ovs, &[48, 49], &[41]);
+            }
+            return;
+        }
+
+        Self::upsert_maskmain_steps(ovs, &[], &[48, 49]);
+        let has_active_rmt = ovs.iter().any(|x| {
+            x.get_str_or("id", "") == "rmt"
+                && x.get_str_or("mode", "override") == "override"
+                && x.get_str_or("value", "").trim().to_ascii_lowercase() != "disable"
+        });
+        if !has_active_rmt {
+            ovs.retain(|x| x.get_str_or("id", "") != "rmt");
+            let mut o = JsonVal::obj();
+            o.set("id", JsonVal::Str("rmt".to_string()));
+            o.set("mode", JsonVal::Str("override".to_string()));
+            o.set("value", JsonVal::Str("enable".to_string()));
+            ovs.push(o);
+        }
+    }
+
     pub fn memory_params_to_uip_overrides_for_family(
     pub fn memory_params_to_uip_overrides_for_family(
         mem_params: &JsonVal,
         mem_params: &JsonVal,
         run_rmt: Option<bool>,
         run_rmt: Option<bool>,
@@ -162,10 +264,10 @@ impl FirmwareContract {
         fw_family_name: &str,
         fw_family_name: &str,
     ) -> (Vec<JsonVal>, Vec<String>) {
     ) -> (Vec<JsonVal>, Vec<String>) {
         let (ovs, raws) = Self::memory_params_to_uip_overrides(mem_params, run_rmt, rmt_cfg);
         let (ovs, raws) = Self::memory_params_to_uip_overrides(mem_params, run_rmt, rmt_cfg);
+        let mut mapped = Vec::with_capacity(ovs.len());
         if fw_family_name == "cxmt" {
         if fw_family_name == "cxmt" {
             let has_trfcsb = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfcsb");
             let has_trfcsb = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfcsb");
             let has_trefsbrd = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trefsbrd");
             let has_trefsbrd = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trefsbrd");
-            let mut mapped = Vec::with_capacity(ovs.len());
             for mut o in ovs {
             for mut o in ovs {
                 match o.get_str_or("id", "").as_str() {
                 match o.get_str_or("id", "").as_str() {
                     "actm.trfcfgrcsb" => {
                     "actm.trfcfgrcsb" => {
@@ -185,19 +287,28 @@ impl FirmwareContract {
                 }
                 }
                 mapped.push(o);
                 mapped.push(o);
             }
             }
-            return (mapped, raws);
-        }
-        // Hovsee 107_VD012 (.166): translate canonical `actm.trfcsb` -> `actm.trfcfgrcsb`
-        let has_trfcfgrcsb = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfcfgrcsb");
-        let mut mapped = Vec::with_capacity(ovs.len());
-        for mut o in ovs {
-            if o.get_str_or("id", "") == "actm.trfcsb" {
-                if has_trfcfgrcsb {
-                    continue;
+        } else {
+            // Hovsee 107_VD012 / 108_VD012 (.166): translate canonical `actm.trfcsb` -> `actm.trfcfgrcsb`
+            let has_trfcfgrcsb = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfcfgrcsb");
+            for mut o in ovs {
+                if o.get_str_or("id", "") == "actm.trfcsb" {
+                    if has_trfcfgrcsb {
+                        continue;
+                    }
+                    o.set("id", JsonVal::Str("actm.trfcfgrcsb".to_string()));
                 }
                 }
-                o.set("id", JsonVal::Str("actm.trfcfgrcsb".to_string()));
+                mapped.push(o);
             }
             }
-            mapped.push(o);
+        }
+        let rmt_dis_only = Self::rmt_selected_is_disable_only(rmt_cfg);
+        let has_rmt_dis_ov = mapped.iter().any(|o| {
+            o.get_str_or("id", "") == "rmt"
+                && o.get_str_or("value", "").trim().eq_ignore_ascii_case("disable")
+        });
+        if rmt_dis_only || run_rmt == Some(false) || rmt_cfg.and_then(|r| r.get_bool("enabled")) == Some(false) || has_rmt_dis_ov {
+            Self::apply_rmt_policy_to_uip_overrides(&mut mapped, false, fw_family_name);
+        } else if run_rmt == Some(true) || rmt_cfg.and_then(|r| r.get_bool("enabled")) == Some(true) {
+            Self::apply_rmt_policy_to_uip_overrides(&mut mapped, true, fw_family_name);
         }
         }
         (mapped, raws)
         (mapped, raws)
     }
     }
@@ -345,23 +456,43 @@ impl FirmwareContract {
                 }
                 }
             }
             }
         }
         }
-        for (k, id) in [("ap", "ap"), ("ecc", "ecc")] {
-            if !ovs.iter().any(|x| x.get_str_or("id", "") == id) {
-                if let Some(b) = mem_params.get_bool(k) {
+        if !ovs.iter().any(|x| x.get_str_or("id", "") == "ap") {
+            if let Some(b) = mem_params.get_bool("ap") {
+                // `108_VD012` rejects `ap disable` (`Invalid or not support command`);
+                // only emit `ap enable` when Qt checkbox is checked (`ap: true`).
+                if b {
                     let mut o = JsonVal::obj();
                     let mut o = JsonVal::obj();
-                    o.set("id", JsonVal::Str(id.to_string()));
+                    o.set("id", JsonVal::Str("ap".to_string()));
                     o.set("mode", JsonVal::Str("override".to_string()));
                     o.set("mode", JsonVal::Str("override".to_string()));
-                    o.set("value", JsonVal::Str(if b { "enable" } else { "disable" }.to_string()));
+                    o.set("value", JsonVal::Str("enable".to_string()));
+                    ovs.push(o);
+                }
+            } else if let Some(s) = mem_params.get_str("ap") {
+                let st = s.trim().to_ascii_lowercase();
+                if st == "enable" || st == "disable" {
+                    let mut o = JsonVal::obj();
+                    o.set("id", JsonVal::Str("ap".to_string()));
+                    o.set("mode", JsonVal::Str("override".to_string()));
+                    o.set("value", JsonVal::Str(st));
+                    ovs.push(o);
+                }
+            }
+        }
+        if !ovs.iter().any(|x| x.get_str_or("id", "") == "ecc") {
+            if let Some(b) = mem_params.get_bool("ecc") {
+                let mut o = JsonVal::obj();
+                o.set("id", JsonVal::Str("ecc".to_string()));
+                o.set("mode", JsonVal::Str("override".to_string()));
+                o.set("value", JsonVal::Str(if b { "enable" } else { "disable" }.to_string()));
+                ovs.push(o);
+            } else if let Some(s) = mem_params.get_str("ecc") {
+                let st = s.trim().to_ascii_lowercase();
+                if st == "enable" || st == "disable" {
+                    let mut o = JsonVal::obj();
+                    o.set("id", JsonVal::Str("ecc".to_string()));
+                    o.set("mode", JsonVal::Str("override".to_string()));
+                    o.set("value", JsonVal::Str(st));
                     ovs.push(o);
                     ovs.push(o);
-                } else if let Some(s) = mem_params.get_str(k) {
-                    let st = s.trim().to_ascii_lowercase();
-                    if st == "enable" || st == "disable" {
-                        let mut o = JsonVal::obj();
-                        o.set("id", JsonVal::Str(id.to_string()));
-                        o.set("mode", JsonVal::Str("override".to_string()));
-                        o.set("value", JsonVal::Str(st));
-                        ovs.push(o);
-                    }
                 }
                 }
             }
             }
         }
         }

+ 1 - 0
native/stl_accel/src/lib.rs

@@ -333,6 +333,7 @@ extern "C" {
         out_cap: usize,
         out_cap: usize,
         out_len: *mut usize,
         out_len: *mut usize,
     ) -> i32;
     ) -> i32;
+    pub fn c_ipmi_invalidate_sdr_cache(handle: i32);
     pub fn c_ipmi_device_info(
     pub fn c_ipmi_device_info(
         handle: i32,
         handle: i32,
         kind: *const u8,
         kind: *const u8,

Diferenças do arquivo suprimidas por serem muito extensas
+ 1245 - 1
native/stl_accel/src/main.rs


+ 170 - 34
native/stl_accel/src/pxe.rs

@@ -31,12 +31,13 @@ pub const STAGE1_PXE_COMMANDS: [&str; 6] = [
 ];
 ];
 
 
 /// Local candidate filenames written alongside `mt86.cfg`
 /// Local candidate filenames written alongside `mt86.cfg`
-pub const LOCAL_CFG_CANDIDATES: [&str; 6] = [
+pub const LOCAL_CFG_CANDIDATES: [&str; 7] = [
     "mt86.cfg",
     "mt86.cfg",
     "Default string-mt86.cfg",
     "Default string-mt86.cfg",
     "118.cfg",
     "118.cfg",
     "memtest86.cfg",
     "memtest86.cfg",
     "18-66-96-8a-f7-77-mt86.cfg",
     "18-66-96-8a-f7-77-mt86.cfg",
+    "18-66-96-8a-f7-7f-mt86.cfg",
     "18-66-96-8a-f7-87-mt86.cfg",
     "18-66-96-8a-f7-87-mt86.cfg",
 ];
 ];
 
 
@@ -150,14 +151,33 @@ fn mt_test_name_to_idx(name: &str) -> Option<i64> {
         "hammer test" => Some(13),
         "hammer test" => Some(13),
         "dma test (experimental)" | "dma test" => Some(14),
         "dma test (experimental)" | "dma test" => Some(14),
         "march c algorithm" | "march c" => Some(15),
         "march c algorithm" | "march c" => Some(15),
-        "galloping pattern (galpat)" | "galpat" => Some(16),
-        "galloping pattern (linear)" | "galpat linear" => Some(17),
-        "galloping pattern (randomaddress)" | "galpat randaddr" => Some(18),
-        "galloping pattern (bankjump)" | "galpat bankjump" => Some(19),
-        "galloping pattern (victim)" | "galpat victim" => Some(20),
-        "galloping pattern (marchic)" | "galpat marchic" => Some(21),
-        "galloping pattern (marchsse)" | "galpat marchsse" => Some(22),
-        "galloping pattern (butterfly)" | "galpat butterfly" => Some(23),
+        "galloping pattern (galpat)"
+        | "galloping pattern - galpat"
+        | "galpat" => Some(16),
+        "galloping pattern (linear)"
+        | "galloping pattern - linear"
+        | "galpat linear" => Some(17),
+        "galloping pattern (randomaddress)"
+        | "galloping pattern (randaddr)"
+        | "galloping pattern - randomaddress"
+        | "galloping pattern - randaddr"
+        | "galpat randaddr"
+        | "galpat randomaddress" => Some(18),
+        "galloping pattern (bankjump)"
+        | "galloping pattern - bankjump"
+        | "galpat bankjump" => Some(19),
+        "galloping pattern (victim)"
+        | "galloping pattern - victim"
+        | "galpat victim" => Some(20),
+        "galloping pattern (marchic)"
+        | "galloping pattern - marchic"
+        | "galpat marchic" => Some(21),
+        "galloping pattern (marchsse)"
+        | "galloping pattern - marchsse"
+        | "galpat marchsse" => Some(22),
+        "galloping pattern (butterfly)"
+        | "galloping pattern - butterfly"
+        | "galpat butterfly" => Some(23),
         "march ss+ algorithm" | "march ss+" => Some(24),
         "march ss+ algorithm" | "march ss+" => Some(24),
         "stressapp memory stress test" | "stressapp" => Some(25),
         "stressapp memory stress test" | "stressapp" => Some(25),
         _ => {
         _ => {
@@ -216,29 +236,41 @@ fn parse_test_id_list(arr: &[JsonVal]) -> Vec<i64> {
 
 
 pub fn render_mt86_cfg_text(cfg: &JsonVal, tftp_server_ip: &str) -> String {
 pub fn render_mt86_cfg_text(cfg: &JsonVal, tftp_server_ip: &str) -> String {
     let fallback_tst = cfg.get_str_or("tstlist", DEFAULT_FORMAL_TSTLIST);
     let fallback_tst = cfg.get_str_or("tstlist", DEFAULT_FORMAL_TSTLIST);
-    let tstlist = if let Some(only) = cfg.get_arr("only_tests") {
-        let nums = parse_test_id_list(only);
-        if nums.is_empty() {
-            fallback_tst
-        } else {
-            nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",")
-        }
-    } else if let Some(sel) = cfg.get_arr("selected") {
-        let nums = parse_test_id_list(sel);
-        if nums.is_empty() {
-            fallback_tst
-        } else {
-            nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",")
-        }
-    } else if let Some(algs) = cfg.get_arr("algorithms") {
-        let nums = parse_test_id_list(algs);
-        if nums.is_empty() {
-            fallback_tst
-        } else {
-            nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",")
-        }
-    } else if let Some(skip) = cfg.get_arr("skip_tests") {
-        let skip_set = parse_test_id_list(skip);
+    let only_nums = cfg
+        .get_arr("only_tests")
+        .map(|a| parse_test_id_list(a))
+        .unwrap_or_default();
+    let sel_nums = cfg
+        .get_arr("selected")
+        .map(|a| parse_test_id_list(a))
+        .unwrap_or_default();
+    let alg_nums = cfg
+        .get_arr("algorithms")
+        .map(|a| parse_test_id_list(a))
+        .unwrap_or_default();
+    let skip_set = cfg
+        .get_arr("skip_tests")
+        .map(|a| parse_test_id_list(a))
+        .unwrap_or_default();
+    let tstlist = if !only_nums.is_empty() {
+        only_nums
+            .iter()
+            .map(|n| n.to_string())
+            .collect::<Vec<_>>()
+            .join(",")
+    } else if !sel_nums.is_empty() {
+        sel_nums
+            .iter()
+            .map(|n| n.to_string())
+            .collect::<Vec<_>>()
+            .join(",")
+    } else if !alg_nums.is_empty() {
+        alg_nums
+            .iter()
+            .map(|n| n.to_string())
+            .collect::<Vec<_>>()
+            .join(",")
+    } else if !skip_set.is_empty() {
         let nums: Vec<String> = (0..=25)
         let nums: Vec<String> = (0..=25)
             .filter(|n| !skip_set.contains(n))
             .filter(|n| !skip_set.contains(n))
             .map(|n| n.to_string())
             .map(|n| n.to_string())
@@ -1058,6 +1090,32 @@ fn parse_n_ch_slot_coords(line: &str) -> (Option<i64>, Option<i64>, Option<i64>)
 
 
     let bytes = line.as_bytes();
     let bytes = line.as_bytes();
     for i in 0..bytes.len() {
     for i in 0..bytes.len() {
+        if (bytes[i] == b'N' || bytes[i] == b'n')
+            && i + 4 < bytes.len()
+            && (bytes[i + 1] == b'0' || bytes[i + 1] == b'1')
+            && bytes[i + 2] == b'.'
+            && (bytes[i + 3] == b'C' || bytes[i + 3] == b'c')
+            && bytes[i + 4].is_ascii_digit()
+        {
+            let cpu = (bytes[i + 1] - b'0') as i64;
+            let rest = &line[i + 4..];
+            let ch_digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
+            if let Ok(ch) = ch_digits.parse::<i64>() {
+                if (0..=11).contains(&ch) {
+                    let after_ch = &rest[ch_digits.len()..];
+                    let dimm = if after_ch.len() >= 3
+                        && after_ch.as_bytes()[0] == b'.'
+                        && (after_ch.as_bytes()[1] == b'D' || after_ch.as_bytes()[1] == b'd')
+                        && (after_ch.as_bytes()[2] == b'0' || after_ch.as_bytes()[2] == b'1')
+                    {
+                        Some((after_ch.as_bytes()[2] - b'0') as i64)
+                    } else {
+                        None
+                    };
+                    return (Some(cpu), Some(ch), dimm);
+                }
+            }
+        }
         if (bytes[i] == b'N' || bytes[i] == b'n')
         if (bytes[i] == b'N' || bytes[i] == b'n')
             && i + 4 < bytes.len()
             && i + 4 < bytes.len()
             && (bytes[i + 1] == b'0' || bytes[i + 1] == b'1')
             && (bytes[i + 1] == b'0' || bytes[i + 1] == b'1')
@@ -1434,6 +1492,34 @@ fn parse_tftp_request(pkt: &[u8]) -> Option<(u16, String, String, Vec<(String, S
     Some((op, filename, mode, opts))
     Some((op, filename, mode, opts))
 }
 }
 
 
+pub const PXE_SYNC_MAGIC: &[u8; 16] = b"XJKJ_PXESYNC_V1\0";
+pub const PXE_SYNC_MAX_PAYLOAD: usize = 2 * 1024 * 1024;
+
+pub fn inject_pxe_sync_payload(
+    template: &[u8],
+    efi_bytes: &[u8],
+    target_rel_path: &str,
+) -> Option<Vec<u8>> {
+    if efi_bytes.is_empty() || efi_bytes.len() > PXE_SYNC_MAX_PAYLOAD {
+        return None;
+    }
+    let slot_off = template
+        .windows(PXE_SYNC_MAGIC.len())
+        .position(|w| w == PXE_SYNC_MAGIC)?;
+    let data_off = slot_off + 16 + 8 + 64;
+    if data_off + PXE_SYNC_MAX_PAYLOAD > template.len() {
+        return None;
+    }
+    let mut out = template.to_vec();
+    out[slot_off + 16..slot_off + 24].copy_from_slice(&(efi_bytes.len() as u64).to_le_bytes());
+    out[slot_off + 24..slot_off + 88].fill(0);
+    let path_bytes = target_rel_path.as_bytes();
+    let copy_len = path_bytes.len().min(63);
+    out[slot_off + 24..slot_off + 24 + copy_len].copy_from_slice(&path_bytes[..copy_len]);
+    out[data_off..data_off + efi_bytes.len()].copy_from_slice(efi_bytes);
+    Some(out)
+}
+
 fn is_mt86_cfg_name(base_lower: &str) -> bool {
 fn is_mt86_cfg_name(base_lower: &str) -> bool {
     matches!(
     matches!(
         base_lower,
         base_lower,
@@ -1446,6 +1532,41 @@ fn resolve_tftp_rrq_bytes(hub: &crate::api::AppHub, raw_name: &str) -> Option<Ve
     let fname = rel.file_name()?.to_string_lossy().to_string();
     let fname = rel.file_name()?.to_string_lossy().to_string();
     let base_lower = fname.to_ascii_lowercase();
     let base_lower = fname.to_ascii_lowercase();
 
 
+    if base_lower == "pxe_sync.efi" {
+        let tpl_path = hub.pxe_tftp_dir.join("pxe_sync.efi");
+        if tpl_path.is_file() {
+            if let Ok(tpl) = fs::read(&tpl_path) {
+                let active_name = hub
+                    .pxe_state
+                    .read()
+                    .ok()
+                    .and_then(|st| st.get_str("active_efi").map(|s| s.to_string()))
+                    .and_then(|s| {
+                        Path::new(s.trim())
+                            .file_name()
+                            .and_then(|f| f.to_str())
+                            .map(|f| f.to_string())
+                    })
+                    .filter(|s| !s.is_empty())
+                    .unwrap_or_else(|| PXE_EFI_FILENAME.to_string());
+                let efi_path = if hub.pxe_tftp_dir.join(&active_name).is_file() {
+                    hub.pxe_tftp_dir.join(&active_name)
+                } else {
+                    hub.pxe_tftp_dir.join(PXE_EFI_FILENAME)
+                };
+                if efi_path.is_file() {
+                    if let Ok(efi_bytes) = fs::read(&efi_path) {
+                        let target_rel = format!("\\EFI\\{}", active_name);
+                        if let Some(patched) = inject_pxe_sync_payload(&tpl, &efi_bytes, &target_rel) {
+                            return Some(patched);
+                        }
+                    }
+                }
+                return Some(tpl);
+            }
+        }
+    }
+
     if is_mt86_cfg_name(&base_lower) {
     if is_mt86_cfg_name(&base_lower) {
         for cand in [hub.pxe_tftp_dir.join(&fname), hub.pxe_tftp_dir.join("mt86.cfg")] {
         for cand in [hub.pxe_tftp_dir.join(&fname), hub.pxe_tftp_dir.join("mt86.cfg")] {
             if cand.is_file() {
             if cand.is_file() {
@@ -1870,8 +1991,23 @@ pub fn try_ingest_local_pxe_report(
         if let Some(ref exp) = clean_expected {
         if let Some(ref exp) = clean_expected {
             let exact = sub.join(exp);
             let exact = sub.join(exp);
             if exact.is_file() {
             if exact.is_file() {
-                best = Some((std::time::SystemTime::now(), exact));
-                break;
+                let fresh = if min_unix_ms <= 0 {
+                    true
+                } else if let Ok(md) = fs::metadata(&exact) {
+                    md.len() > 0
+                        && md
+                            .modified()
+                            .ok()
+                            .and_then(|mt| mt.duration_since(std::time::UNIX_EPOCH).ok())
+                            .map(|d| d.as_secs() >= min_secs)
+                            .unwrap_or(false)
+                } else {
+                    false
+                };
+                if fresh {
+                    best = Some((std::time::SystemTime::now(), exact));
+                    break;
+                }
             }
             }
         }
         }
         let Ok(entries) = fs::read_dir(&sub) else {
         let Ok(entries) = fs::read_dir(&sub) else {

+ 420 - 33
native/stl_accel/src/results.rs

@@ -486,6 +486,8 @@ pub struct StationState {
     pub latest_mt_report_path: String,
     pub latest_mt_report_path: String,
     pub uefi_fs_candidates: Vec<String>,
     pub uefi_fs_candidates: Vec<String>,
     pub resolved_mt_efi_path: Option<String>,
     pub resolved_mt_efi_path: Option<String>,
+    pub resolved_grub_tftp_loader: Option<String>,
+    pub pxe_server_ip: String,
     pub efi_probe_done: bool,
     pub efi_probe_done: bool,
     pub run_started_unix_ms: i64,
     pub run_started_unix_ms: i64,
     pub run_ended_unix_ms: i64,
     pub run_ended_unix_ms: i64,
@@ -500,6 +502,9 @@ pub struct StationState {
     pub in_internal_warm_reset: bool,
     pub in_internal_warm_reset: bool,
     pub amt_prefers_short_cmd: bool,
     pub amt_prefers_short_cmd: bool,
     pub amt_fallback_attempted: bool,
     pub amt_fallback_attempted: bool,
+    pub dimm_seen_in_boot: [bool; 24],
+    pub had_bmc_sdr: [bool; 24],
+    pub sdr_absent_streak: [u8; 24],
 }
 }
 
 
 impl StationState {
 impl StationState {
@@ -675,6 +680,8 @@ impl StationState {
             latest_mt_report_path: String::new(),
             latest_mt_report_path: String::new(),
             uefi_fs_candidates: Vec::new(),
             uefi_fs_candidates: Vec::new(),
             resolved_mt_efi_path: None,
             resolved_mt_efi_path: None,
+            resolved_grub_tftp_loader: None,
+            pxe_server_ip: "192.168.0.10".to_string(),
             efi_probe_done: false,
             efi_probe_done: false,
             run_started_unix_ms: 0,
             run_started_unix_ms: 0,
             run_ended_unix_ms: 0,
             run_ended_unix_ms: 0,
@@ -689,6 +696,9 @@ impl StationState {
             in_internal_warm_reset: false,
             in_internal_warm_reset: false,
             amt_prefers_short_cmd: false,
             amt_prefers_short_cmd: false,
             amt_fallback_attempted: false,
             amt_fallback_attempted: false,
+            dimm_seen_in_boot: [false; 24],
+            had_bmc_sdr: [false; 24],
+            sdr_absent_streak: [0; 24],
         }
         }
     }
     }
 
 
@@ -773,6 +783,122 @@ impl StationState {
         self.dimm_soa.reset_stages();
         self.dimm_soa.reset_stages();
     }
     }
 
 
+    pub fn reset_dimms_for_new_boot(&mut self) {
+        for idx in 0..24 {
+            self.dimms[idx] = DimmSlot::empty();
+            self.sync_dimm_to_soa(idx);
+        }
+        self.dimm_seen_in_boot = [false; 24];
+        self.had_bmc_sdr = [false; 24];
+        self.sdr_absent_streak = [0; 24];
+    }
+
+    pub fn clear_for_external_restart(
+        &mut self,
+        now: i64,
+        reason_detail: &str,
+        force_new_boot_id: bool,
+    ) {
+        let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+        let had_active_or_finished_run = self.run_ended_unix_ms > 0
+            || self.single_run_started_ms > 0
+            || self.single_run_active
+            || self.is_run_active()
+            || !self.boot_execution.get_str_or("id", "").is_empty();
+        self.awaiting_dimm_replacement = false;
+        self.hot.awaiting_dimm_replacement = false;
+        self.plan_paused = false;
+        self.in_internal_warm_reset = false;
+        self.last_err_stage.clear();
+        for v in self.stage_errors.values_mut() {
+            v.clear();
+        }
+        self.unsupported_commands.clear();
+        if force_new_boot_id || self.boot_id.is_empty() {
+            self.boot_seq += 1;
+            self.hot.boot_seq = self.boot_seq;
+            self.boot_id = format!("B-{}-{}", self.station_id, self.boot_seq);
+        }
+        self.hot.reset_for_new_boot(now);
+        self.reset_dimms_for_new_boot();
+        self.rmt_results.clear();
+        self.amt_results.clear();
+        self.active_amt_cpus.clear();
+        self.amt_fallback_attempted = false;
+        self.mt_result = JsonVal::obj();
+        self.mt_per_test_errs.clear();
+        self.plan_configured.clear();
+        self.plan_done.clear();
+        self.plan_amt_started.clear();
+        self.plan_mt_started = false;
+        self.single_run_active = false;
+        self.single_run_id.clear();
+        self.single_run_started_ms = 0;
+        if had_active_or_finished_run {
+            self.run_started_unix_ms = 0;
+            self.run_ended_unix_ms = 0;
+        }
+        self.mt_started_unix_ms = 0;
+        self.mt_report_sync_pending = false;
+        self.mt_report_fetched_for_boot = false;
+        self.mt_waiting_report_until_ms = 0;
+        self.expected_mt_report_name.clear();
+        self.latest_mt_report_path.clear();
+        self.uefi_fs_candidates.clear();
+        self.resolved_mt_efi_path = None;
+        self.resolved_grub_tftp_loader = None;
+        self.efi_probe_done = false;
+        self.observed_stages.clear();
+        self.stage_step_counts.clear();
+        self.observed_phase = "boot".to_string();
+        self.observed_detail = reason_detail.to_string();
+        self.observed_cpu = None;
+        self.observed_uip_stage = None;
+        self.observed_unix_ms = now;
+        self.prompt_ready = false;
+        self.prompt_kind.clear();
+        self.prompt_cpu = None;
+        self.prompt_uip_stage = None;
+        self.prompt_evidence.clear();
+        self.async_script.clear();
+        self.tx_pacer.clear();
+        self.pending_complete_signal = None;
+        self.task_status = "not_started".to_string();
+        self.stage_intents.clear();
+        self.last_uip_apply = None;
+        self.last_amt_apply = None;
+        self.last_amt_start = None;
+        self.last_phase_action = None;
+        self.command = JsonVal::Null;
+        if bp_state_now != "idle"
+            || !self.boot_execution.get_str_or("id", "").is_empty()
+            || !self.boot_execution.get_str_or("boot_id", "").is_empty()
+            || !self.boot_execution.get_str_or("error", "").is_empty()
+            || !self.boot_execution.get_str_or("current_stage", "").is_empty()
+            || !self.boot_execution.get_str_or("waiting_reason", "").is_empty()
+            || self
+                .boot_execution
+                .get_arr("handled_inputs")
+                .map(|a| !a.is_empty())
+                .unwrap_or(false)
+            || self
+                .boot_execution
+                .get_f64("started_unix_ms")
+                .unwrap_or(0.0)
+                > 0.0
+        {
+            self.boot_execution.set("id", JsonVal::Str(String::new()));
+            self.boot_execution.set("boot_id", JsonVal::Str(String::new()));
+            self.boot_execution.set("state", JsonVal::Str("idle".to_string()));
+            self.boot_execution.set("current_stage", JsonVal::Str(String::new()));
+            self.boot_execution.set("error", JsonVal::Str(String::new()));
+            self.boot_execution.set("waiting_reason", JsonVal::Str(String::new()));
+            self.boot_execution.set("handled_inputs", JsonVal::Arr(Vec::new()));
+            self.boot_execution.set("started_unix_ms", JsonVal::Num(0.0));
+            self.boot_execution.set("updated_unix_ms", JsonVal::Num(now as f64));
+        }
+    }
+
     pub fn clear_bmc_sdr_temps(&mut self) {
     pub fn clear_bmc_sdr_temps(&mut self) {
         for idx in 0..24 {
         for idx in 0..24 {
             if self.dimms[idx].source == "bmc_sdr" {
             if self.dimms[idx].source == "bmc_sdr" {
@@ -863,10 +989,17 @@ impl StationState {
         self.latest_mt_report_path.clear();
         self.latest_mt_report_path.clear();
         self.uefi_fs_candidates.clear();
         self.uefi_fs_candidates.clear();
         self.resolved_mt_efi_path = None;
         self.resolved_mt_efi_path = None;
+        self.resolved_grub_tftp_loader = None;
         self.efi_probe_done = false;
         self.efi_probe_done = false;
         self.awaiting_dimm_replacement = false;
         self.awaiting_dimm_replacement = false;
         self.hot.awaiting_dimm_replacement = false;
         self.hot.awaiting_dimm_replacement = false;
         self.task_status = "not_started".to_string();
         self.task_status = "not_started".to_string();
+        self.stage_intents.clear();
+        self.last_uip_apply = None;
+        self.last_amt_apply = None;
+        self.last_amt_start = None;
+        self.last_phase_action = None;
+        self.command = JsonVal::Null;
         self.rmt_results.clear();
         self.rmt_results.clear();
         self.amt_results.clear();
         self.amt_results.clear();
         self.active_amt_cpus.clear();
         self.active_amt_cpus.clear();
@@ -877,10 +1010,9 @@ impl StationState {
         for v in self.stage_errors.values_mut() {
         for v in self.stage_errors.values_mut() {
             v.clear();
             v.clear();
         }
         }
-        for idx in 0..24 {
-            self.dimms[idx] = DimmSlot::empty();
-            self.sync_dimm_to_soa(idx);
-        }
+        self.reset_dimms_for_new_boot();
+        self.boot_execution.set("id", JsonVal::Str(String::new()));
+        self.boot_execution.set("boot_id", JsonVal::Str(String::new()));
         self.boot_execution.set("state", JsonVal::Str("idle".to_string()));
         self.boot_execution.set("state", JsonVal::Str("idle".to_string()));
         self.boot_execution.set("current_stage", JsonVal::Str(String::new()));
         self.boot_execution.set("current_stage", JsonVal::Str(String::new()));
         self.boot_execution.set("error", JsonVal::Str(String::new()));
         self.boot_execution.set("error", JsonVal::Str(String::new()));
@@ -888,6 +1020,8 @@ impl StationState {
             "waiting_reason",
             "waiting_reason",
             JsonVal::Str("测试机未连接或已失联,通道与运行状态已清空".to_string()),
             JsonVal::Str("测试机未连接或已失联,通道与运行状态已清空".to_string()),
         );
         );
+        self.boot_execution.set("handled_inputs", JsonVal::Arr(Vec::new()));
+        self.boot_execution.set("started_unix_ms", JsonVal::Num(0.0));
         self.boot_execution.set("updated_unix_ms", JsonVal::Num(now as f64));
         self.boot_execution.set("updated_unix_ms", JsonVal::Num(now as f64));
         if self.task_batch.get_str_or("state", "idle") == "running" {
         if self.task_batch.get_str_or("state", "idle") == "running" {
             self.task_batch.set("state", JsonVal::Str("stopped".to_string()));
             self.task_batch.set("state", JsonVal::Str("stopped".to_string()));
@@ -933,6 +1067,28 @@ impl StationState {
             || self.task_status == "running"
             || self.task_status == "running"
     }
     }
 
 
+    #[inline]
+    pub fn has_any_failure_state(&self) -> bool {
+        self.awaiting_dimm_replacement
+            || self.hot.mt_fail_complete
+            || self.mt_result.get_str_or("status", "") == "fail"
+            || self
+                .amt_results
+                .values()
+                .any(|r| r.status == "fail" || r.status == "block")
+            || self.stage_errors.values().any(|v| !v.is_empty())
+    }
+
+    #[inline]
+    pub fn has_entered_ddr_training(&self) -> bool {
+        self.observed_stages.contains("uip")
+            || self.hot.ict_stage1_complete
+            || self.observed_stages.contains("rmt")
+            || self.observed_stages.contains("amt")
+            || self.observed_stages.contains("uefi")
+            || self.observed_stages.contains("mt")
+    }
+
     #[inline]
     #[inline]
     pub fn freeze_run_timing(&mut self, now: i64) {
     pub fn freeze_run_timing(&mut self, now: i64) {
         if self.run_started_unix_ms > 0 && self.run_ended_unix_ms == 0 {
         if self.run_started_unix_ms > 0 && self.run_ended_unix_ms == 0 {
@@ -1063,6 +1219,8 @@ impl StationState {
                         slot.failed_stage = stage.to_string();
                         slot.failed_stage = stage.to_string();
                     }
                     }
                 }
                 }
+                self.dimm_seen_in_boot[idx] = true;
+                self.sdr_absent_streak[idx] = 0;
                 self.sync_dimm_to_soa(idx);
                 self.sync_dimm_to_soa(idx);
             }
             }
         }
         }
@@ -1133,8 +1291,35 @@ impl StationState {
             return;
             return;
         }
         }
 
 
-        let cpu = if ev.cpu >= 0 { Some(ev.cpu as i64) } else { None };
-        let ch = if ev.channel >= 0 { Some(ev.channel as i64) } else { None };
+        let mut cpu = if ev.cpu >= 0 { Some(ev.cpu as i64) } else { None };
+        let mut ch = if ev.channel >= 0 { Some(ev.channel as i64) } else { None };
+        let mut dimm = if ev.dimm >= 0 { Some(ev.dimm as i64) } else { None };
+        self.resolve_coords_from_sn(line, &mut cpu, &mut ch, &mut dimm);
+        let (prev_msg_snap, prev_cpu_snap) = self
+            .stage_errors
+            .get(stage)
+            .and_then(|v| v.last())
+            .map(|last| (last.get_str_or("message", ""), last.get_i64("cpu")))
+            .unwrap_or_default();
+        if (cpu.is_none() || ch.is_none()) && !prev_msg_snap.is_empty() {
+            self.resolve_coords_from_sn(&prev_msg_snap, &mut cpu, &mut ch, &mut dimm);
+        }
+        if cpu.is_none() {
+            if let Some(c) = ch {
+                if (0..12).contains(&c) {
+                    let s0 = self.dimms[c as usize].presence == "present";
+                    let s1 = self.dimms[12 + (c as usize)].presence == "present";
+                    if s0 && !s1 {
+                        cpu = Some(0);
+                    } else if s1 && !s0 {
+                        cpu = Some(1);
+                    }
+                }
+            }
+        }
+        if cpu.is_none() {
+            cpu = prev_cpu_snap;
+        }
         let valid_bank = if (0..32).contains(&ev.bank) {
         let valid_bank = if (0..32).contains(&ev.bank) {
             Some(ev.bank as i64)
             Some(ev.bank as i64)
         } else {
         } else {
@@ -1156,6 +1341,8 @@ impl StationState {
                         slot.failed_stage = stage.to_string();
                         slot.failed_stage = stage.to_string();
                     }
                     }
                 }
                 }
+                self.dimm_seen_in_boot[idx] = true;
+                self.sdr_absent_streak[idx] = 0;
                 self.sync_dimm_to_soa(idx);
                 self.sync_dimm_to_soa(idx);
             }
             }
         }
         }
@@ -1612,8 +1799,9 @@ impl StationState {
             };
             };
             self.observed_detail = "confirmed_dimm_replacement".to_string();
             self.observed_detail = "confirmed_dimm_replacement".to_string();
             self.stage_errors.values_mut().for_each(|v| v.clear());
             self.stage_errors.values_mut().for_each(|v| v.clear());
+            self.last_err_stage.clear();
             self.unsupported_commands.clear();
             self.unsupported_commands.clear();
-            self.reset_all_dimm_stages();
+            self.reset_dimms_for_new_boot();
             self.task_status = "not_started".to_string();
             self.task_status = "not_started".to_string();
             if matches!(
             if matches!(
                 self.boot_execution.get_str_or("state", "").as_str(),
                 self.boot_execution.get_str_or("state", "").as_str(),
@@ -1793,6 +1981,14 @@ impl StationState {
             let low_wr = trimmed.to_ascii_lowercase();
             let low_wr = trimmed.to_ascii_lowercase();
             if low_wr.contains("warm reset")
             if low_wr.contains("warm reset")
                 || low_wr.contains("warmreset")
                 || low_wr.contains("warmreset")
+                || low_wr.contains("power good reset")
+                || low_wr.contains("post_reset_powergood")
+                || low_wr.contains("reset requested: 2")
+                || low_wr.contains("reset requested: 6")
+                || low_wr.contains("resetrequired: 02")
+                || low_wr.contains("resetrequired: 06")
+                || low_wr.contains("resetrequired: 0x02")
+                || low_wr.contains("resetrequired: 0x06")
                 || low_wr.contains("mrc_status_reset_required")
                 || low_wr.contains("mrc_status_reset_required")
             {
             {
                 self.in_internal_warm_reset = true;
                 self.in_internal_warm_reset = true;
@@ -1812,7 +2008,17 @@ impl StationState {
                 } else {
                 } else {
                     self.amt_prefers_short_cmd = false;
                     self.amt_prefers_short_cmd = false;
                 }
                 }
-                if self.in_internal_warm_reset {
+                let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+                let was_blocked_or_terminal = self.has_any_failure_state()
+                    || matches!(
+                        bp_state_now.as_str(),
+                        "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+                    )
+                    || matches!(
+                        self.task_status.as_str(),
+                        "failed" | "completed" | "interrupted"
+                    );
+                if self.in_internal_warm_reset && !was_blocked_or_terminal {
                     self.in_internal_warm_reset = false;
                     self.in_internal_warm_reset = false;
                     self.hot.awaiting_reset_banner = false;
                     self.hot.awaiting_reset_banner = false;
                     self.hot.stage_rank = 0;
                     self.hot.stage_rank = 0;
@@ -1826,14 +2032,30 @@ impl StationState {
                     self.plan_done.retain(|k| !k.contains(":uip1"));
                     self.plan_done.retain(|k| !k.contains(":uip1"));
                     self.observed_phase = "boot".to_string();
                     self.observed_phase = "boot".to_string();
                     self.observed_detail = "internal_warm_reset".to_string();
                     self.observed_detail = "internal_warm_reset".to_string();
-                    self.cleaner.clear_halfline();
                     self.observed_unix_ms = now;
                     self.observed_unix_ms = now;
                     self.hot.observed_unix_ms = now;
                     self.hot.observed_unix_ms = now;
                     return;
                     return;
                 }
                 }
                 self.in_internal_warm_reset = false;
                 self.in_internal_warm_reset = false;
-                // Only "[SYS_BIOS]Version:" increments boot_id (never ICT Stage 2 banner!)
-                if (!self.hot.awaiting_reset_banner && self.observed_detail != "host_reset")
+                if was_blocked_or_terminal || (!self.is_run_active() && !self.hot.awaiting_reset_banner) {
+                    self.clear_for_external_restart(now, "bios_banner", true);
+                    self.observed_stages.insert("boot".to_string());
+                    *self.stage_step_counts.entry("boot".to_string()).or_insert(0) += 1;
+                    return;
+                }
+                // Only "[SYS_BIOS]Version:" increments boot_id (never ICT Stage 2 banner or pre-ICT1 MRC warm resets!)
+                let pre_uip_active_reset = !was_blocked_or_terminal
+                    && self.is_run_active()
+                    && self.observed_stages.contains("boot")
+                    && !self.observed_stages.contains("uip")
+                    && !self.observed_stages.contains("rmt")
+                    && !self.observed_stages.contains("amt")
+                    && !self.observed_stages.contains("uefi")
+                    && !self.observed_stages.contains("mt")
+                    && !self.hot.training_complete;
+                if (!self.hot.awaiting_reset_banner
+                    && self.observed_detail != "host_reset"
+                    && !pre_uip_active_reset)
                     || self.boot_id.is_empty()
                     || self.boot_id.is_empty()
                 {
                 {
                     self.boot_seq += 1;
                     self.boot_seq += 1;
@@ -1841,6 +2063,10 @@ impl StationState {
                     self.boot_id = format!("B-{}-{}", self.station_id, self.boot_seq);
                     self.boot_id = format!("B-{}-{}", self.station_id, self.boot_seq);
                 }
                 }
                 self.hot.reset_for_new_boot(now);
                 self.hot.reset_for_new_boot(now);
+                self.awaiting_dimm_replacement = false;
+                self.hot.awaiting_dimm_replacement = false;
+                self.plan_paused = false;
+                self.last_err_stage.clear();
                 if self.run_started_unix_ms == 0 && self.is_run_active() {
                 if self.run_started_unix_ms == 0 && self.is_run_active() {
                     self.run_started_unix_ms = now;
                     self.run_started_unix_ms = now;
                     self.run_ended_unix_ms = 0;
                     self.run_ended_unix_ms = 0;
@@ -1853,6 +2079,7 @@ impl StationState {
                 self.latest_mt_report_path.clear();
                 self.latest_mt_report_path.clear();
                 self.uefi_fs_candidates.clear();
                 self.uefi_fs_candidates.clear();
                 self.resolved_mt_efi_path = None;
                 self.resolved_mt_efi_path = None;
+                self.resolved_grub_tftp_loader = None;
                 self.efi_probe_done = false;
                 self.efi_probe_done = false;
                 self.observed_phase = "boot".to_string();
                 self.observed_phase = "boot".to_string();
                 self.observed_detail = "bios_banner".to_string();
                 self.observed_detail = "bios_banner".to_string();
@@ -1877,13 +2104,61 @@ impl StationState {
                     v.clear();
                     v.clear();
                 }
                 }
                 self.unsupported_commands.clear();
                 self.unsupported_commands.clear();
-                self.reset_all_dimm_stages();
+                self.reset_dimms_for_new_boot();
                 self.observed_unix_ms = now;
                 self.observed_unix_ms = now;
             }
             }
+            lib::STL_LK_ICT_BANNER_HOVSEE | lib::STL_LK_ICT_BANNER_CXMT => {
+                let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+                let is_terminal = matches!(
+                    bp_state_now.as_str(),
+                    "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+                ) || matches!(
+                    self.task_status.as_str(),
+                    "failed" | "completed" | "interrupted"
+                );
+                // Stage 2 (`Current stage is 2`) emits `STL_LK_ICT_BANNER_HOVSEE / CXMT`
+                // inside the same boot right after Training/RMT/AMT (`started_unix_ms` must stay).
+                // Only clear for external restart after entering Stage 2+ or when already terminal/blocked.
+                if is_terminal
+                    || self.awaiting_dimm_replacement
+                    || self.hot.ict_stage2_complete
+                    || self.hot.uefi_complete
+                    || self.hot.mt_banner_seen
+                    || self.hot.mt_pass_complete
+                    || self.hot.mt_fail_complete
+                    || self.observed_stages.contains("uefi")
+                    || self.observed_stages.contains("mt")
+                    || self.observed_stages.contains("post")
+                {
+                    self.clear_for_external_restart(now, "ict_banner_reboot", true);
+                }
+                self.hot.awaiting_reset_banner = false;
+                self.in_internal_warm_reset = false;
+                self.advance_phase("uip", "uip_banner", now);
+            }
             lib::STL_LK_ICT_START_STAGE1 | lib::STL_LK_ICT_START_STAGE2 => {
             lib::STL_LK_ICT_START_STAGE1 | lib::STL_LK_ICT_START_STAGE2 => {
                 let stg = if ev.kind == lib::STL_LK_ICT_START_STAGE2 { 2i64 } else { 1i64 };
                 let stg = if ev.kind == lib::STL_LK_ICT_START_STAGE2 { 2i64 } else { 1i64 };
                 let cpu = if ev.cpu >= 0 { ev.cpu as i64 } else { 0 };
                 let cpu = if ev.cpu >= 0 { ev.cpu as i64 } else { 0 };
                 if stg == 1 {
                 if stg == 1 {
+                    let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+                    if self.has_any_failure_state()
+                        || self.hot.training_complete
+                        || self.hot.rmt_complete
+                        || self.hot.amt_complete
+                        || self.hot.ict_stage2_complete
+                        || self.hot.uefi_complete
+                        || self.hot.mt_pass_complete
+                        || matches!(
+                            bp_state_now.as_str(),
+                            "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+                        )
+                        || matches!(
+                            self.task_status.as_str(),
+                            "failed" | "completed" | "interrupted"
+                        )
+                    {
+                        self.clear_for_external_restart(now, "uip_stage1_reboot", true);
+                    }
                     self.hot.awaiting_reset_banner = false;
                     self.hot.awaiting_reset_banner = false;
                     self.in_internal_warm_reset = false;
                     self.in_internal_warm_reset = false;
                 }
                 }
@@ -1915,6 +2190,7 @@ impl StationState {
                     self.hot.ict_stage2_complete = true;
                     self.hot.ict_stage2_complete = true;
                 } else if self.observed_cpu == Some((self.cpu_count.saturating_sub(1)) as i64)
                 } else if self.observed_cpu == Some((self.cpu_count.saturating_sub(1)) as i64)
                     || trimmed.contains("go on training")
                     || trimmed.contains("go on training")
+                    || self.observed_stages.contains("uip")
                 {
                 {
                     self.hot.ict_stage1_complete = true;
                     self.hot.ict_stage1_complete = true;
                 }
                 }
@@ -1925,6 +2201,28 @@ impl StationState {
                 self.apply_prompt_event(&ev, trimmed_bytes, now);
                 self.apply_prompt_event(&ev, trimmed_bytes, now);
             }
             }
             lib::STL_LK_DIMM_INVENTORY => {
             lib::STL_LK_DIMM_INVENTORY => {
+                if ev.val1 == 1 {
+                    let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+                    let is_terminal = matches!(
+                        bp_state_now.as_str(),
+                        "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+                    ) || matches!(
+                        self.task_status.as_str(),
+                        "failed" | "completed" | "interrupted"
+                    );
+                    if self.has_any_failure_state()
+                        || is_terminal
+                        || self.hot.amt_complete
+                        || self.hot.ict_stage2_complete
+                        || self.hot.uefi_complete
+                        || self.hot.mt_banner_seen
+                        || self.observed_stages.contains("amt")
+                        || self.observed_stages.contains("uefi")
+                        || self.observed_stages.contains("mt")
+                    {
+                        self.clear_for_external_restart(now, "dram_inventory_reboot", true);
+                    }
+                }
                 if ev.cpu >= 0 && ev.channel >= 0 {
                 if ev.cpu >= 0 && ev.channel >= 0 {
                     let slot_idx = (ev.cpu as usize) * 12 + (ev.channel as usize);
                     let slot_idx = (ev.cpu as usize) * 12 + (ev.channel as usize);
                     if slot_idx < 24 {
                     if slot_idx < 24 {
@@ -1936,8 +2234,11 @@ impl StationState {
                                 || (trimmed.contains("Error:") && trimmed.contains("disable channel"))
                                 || (trimmed.contains("Error:") && trimmed.contains("disable channel"))
                                 || self.observed_phase == "training"
                                 || self.observed_phase == "training"
                                 || self.observed_phase == "rmt";
                                 || self.observed_phase == "rmt";
+                            let stg = if self.observed_phase == "rmt" { "rmt" } else { "training" };
                             self.dimms[slot_idx].presence = "present".to_string();
                             self.dimms[slot_idx].presence = "present".to_string();
                             self.dimms[slot_idx].enabled = "disabled".to_string();
                             self.dimms[slot_idx].enabled = "disabled".to_string();
+                            self.dimm_seen_in_boot[slot_idx] = true;
+                            self.sdr_absent_streak[slot_idx] = 0;
                             if let Some(sn) = extract_sn_after_colon(trimmed) {
                             if let Some(sn) = extract_sn_after_colon(trimmed) {
                                 let cur = &self.dimms[slot_idx].sn;
                                 let cur = &self.dimms[slot_idx].sn;
                                 let cur_is_hex = cur.len() >= 2 && cur[..2].eq_ignore_ascii_case("0x");
                                 let cur_is_hex = cur.len() >= 2 && cur[..2].eq_ignore_ascii_case("0x");
@@ -1947,14 +2248,17 @@ impl StationState {
                                 }
                                 }
                             }
                             }
                             if is_explicit_train_fail {
                             if is_explicit_train_fail {
-                                self.dimms[slot_idx].stage_training = "fail".to_string();
+                                if stg == "rmt" {
+                                    self.dimms[slot_idx].stage_rmt = "fail".to_string();
+                                } else {
+                                    self.dimms[slot_idx].stage_training = "fail".to_string();
+                                }
                                 if self.dimms[slot_idx].failed_stage.is_empty() {
                                 if self.dimms[slot_idx].failed_stage.is_empty() {
-                                    self.dimms[slot_idx].failed_stage = "training".to_string();
+                                    self.dimms[slot_idx].failed_stage = stg.to_string();
                                 }
                                 }
                             }
                             }
                             self.sync_dimm_to_soa(slot_idx);
                             self.sync_dimm_to_soa(slot_idx);
                             if is_explicit_train_fail {
                             if is_explicit_train_fail {
-                                let stg = if self.observed_phase == "rmt" { "rmt" } else { "training" };
                                 self.record_stage_error(
                                 self.record_stage_error(
                                     stg,
                                     stg,
                                     Some(ev.cpu as i64),
                                     Some(ev.cpu as i64),
@@ -1964,23 +2268,39 @@ impl StationState {
                                 );
                                 );
                             }
                             }
                         } else if ev.subkind == 4 {
                         } else if ev.subkind == 4 {
-                            self.dimms[slot_idx].presence = "present".to_string();
-                            if self.dimms[slot_idx].enabled == "unknown" {
-                                self.dimms[slot_idx].enabled = "enabled".to_string();
-                            }
-                            if let Some(sn) = extract_sn_after_colon(trimmed) {
-                                let cur = &self.dimms[slot_idx].sn;
-                                let cur_is_hex = cur.len() >= 2 && cur[..2].eq_ignore_ascii_case("0x");
-                                let new_is_hex = sn.len() >= 2 && sn[..2].eq_ignore_ascii_case("0x");
-                                if cur.is_empty() || cur_is_hex || !new_is_hex {
-                                    self.dimms[slot_idx].sn = sn;
+                            let low_line = trimmed.to_ascii_lowercase();
+                            let sn_opt = extract_sn_after_colon(trimmed);
+                            let is_test_no_without_sn = (low_line.contains("test: n")
+                                || low_line.contains("test:n"))
+                                && sn_opt.is_none();
+                            if !is_test_no_without_sn {
+                                self.dimms[slot_idx].presence = "present".to_string();
+                                self.dimm_seen_in_boot[slot_idx] = true;
+                                self.sdr_absent_streak[slot_idx] = 0;
+                                if self.dimms[slot_idx].enabled == "unknown" {
+                                    self.dimms[slot_idx].enabled = "enabled".to_string();
                                 }
                                 }
+                                if let Some(sn) = sn_opt {
+                                    let cur = &self.dimms[slot_idx].sn;
+                                    let cur_is_hex = cur.len() >= 2 && cur[..2].eq_ignore_ascii_case("0x");
+                                    let new_is_hex = sn.len() >= 2 && sn[..2].eq_ignore_ascii_case("0x");
+                                    if cur.is_empty() || cur_is_hex || !new_is_hex {
+                                        self.dimms[slot_idx].sn = sn;
+                                    }
+                                }
+                                self.backfill_completed_stages_for_slot(slot_idx);
+                                self.sync_dimm_to_soa(slot_idx);
                             }
                             }
-                            self.backfill_completed_stages_for_slot(slot_idx);
-                            self.sync_dimm_to_soa(slot_idx);
                         } else if ev.subkind == 0 {
                         } else if ev.subkind == 0 {
-                            if self.dimms[slot_idx].presence == "unknown" {
+                            let keep_current_fail = self.dimm_seen_in_boot[slot_idx]
+                                && !self.dimms[slot_idx].failed_stage.is_empty();
+                            if !keep_current_fail {
+                                self.dimms[slot_idx] = DimmSlot::empty();
                                 self.dimms[slot_idx].presence = "absent".to_string();
                                 self.dimms[slot_idx].presence = "absent".to_string();
+                                self.dimms[slot_idx].quality = "unavailable".to_string();
+                                self.dimm_seen_in_boot[slot_idx] = false;
+                                self.had_bmc_sdr[slot_idx] = false;
+                                self.sdr_absent_streak[slot_idx] = 0;
                                 self.sync_dimm_to_soa(slot_idx);
                                 self.sync_dimm_to_soa(slot_idx);
                             }
                             }
                         }
                         }
@@ -2001,6 +2321,8 @@ impl StationState {
                         self.dimms[slot_idx].source = "rmt_sensor".to_string();
                         self.dimms[slot_idx].source = "rmt_sensor".to_string();
                         self.dimms[slot_idx].received_ms = now;
                         self.dimms[slot_idx].received_ms = now;
                         self.dimms[slot_idx].presence = "present".to_string();
                         self.dimms[slot_idx].presence = "present".to_string();
+                        self.dimm_seen_in_boot[slot_idx] = true;
+                        self.sdr_absent_streak[slot_idx] = 0;
                         if self.dimms[slot_idx].enabled == "unknown" {
                         if self.dimms[slot_idx].enabled == "unknown" {
                             self.dimms[slot_idx].enabled = "enabled".to_string();
                             self.dimms[slot_idx].enabled = "enabled".to_string();
                         }
                         }
@@ -2010,10 +2332,15 @@ impl StationState {
                 }
                 }
             }
             }
             lib::STL_LK_MRC_START => {
             lib::STL_LK_MRC_START => {
-                self.hot.ict_stage1_complete = true;
                 self.prompt_ready = false;
                 self.prompt_ready = false;
                 self.hot.prompt_ready = false;
                 self.hot.prompt_ready = false;
+                let real_training = self.has_entered_ddr_training()
+                    || trimmed.contains("MemTest")
+                    || trimmed.contains("RcdQcaTraining")
+                    || trimmed.contains("DDR Training")
+                    || trimmed.contains("StartMemTrain");
                 if trimmed.contains("MemTest") {
                 if trimmed.contains("MemTest") {
+                    self.hot.ict_stage1_complete = true;
                     self.hot.training_complete = true;
                     self.hot.training_complete = true;
                     if self.observed_stages.contains("rmt")
                     if self.observed_stages.contains("rmt")
                         && self.rmt_results.values().any(|r| r.measurement_rows > 0)
                         && self.rmt_results.values().any(|r| r.measurement_rows > 0)
@@ -2028,15 +2355,31 @@ impl StationState {
                     }
                     }
                     self.advance_phase("amt", "amt_step", now);
                     self.advance_phase("amt", "amt_step", now);
                     *self.stage_step_counts.entry("amt".to_string()).or_insert(0) += 1;
                     *self.stage_step_counts.entry("amt".to_string()).or_insert(0) += 1;
-                } else {
+                } else if real_training {
+                    self.hot.ict_stage1_complete = true;
+                    self.hot.awaiting_reset_banner = false;
                     self.advance_phase("training", "training_step", now);
                     self.advance_phase("training", "training_step", now);
                     *self.stage_step_counts.entry("training".to_string()).or_insert(0) += 1;
                     *self.stage_step_counts.entry("training".to_string()).or_insert(0) += 1;
+                } else {
+                    self.observed_unix_ms = now;
+                    self.hot.observed_unix_ms = now;
                 }
                 }
-                if trimmed.contains("DDR Training -- SUCCEEDED") {
+                if real_training && trimmed.contains("DDR Training -- SUCCEEDED") {
                     self.hot.training_complete = true;
                     self.hot.training_complete = true;
                 }
                 }
             }
             }
             lib::STL_LK_MRC_DONE => {
             lib::STL_LK_MRC_DONE => {
+                self.prompt_ready = false;
+                self.hot.prompt_ready = false;
+                let real_training_done = ev.subkind == 4
+                    || self.has_entered_ddr_training()
+                    || trimmed.contains("EndMemTrain")
+                    || trimmed.contains("Memory Training Complete");
+                if !real_training_done {
+                    self.observed_unix_ms = now;
+                    self.hot.observed_unix_ms = now;
+                    return;
+                }
                 self.hot.ict_stage1_complete = true;
                 self.hot.ict_stage1_complete = true;
                 self.hot.training_complete = true;
                 self.hot.training_complete = true;
                 self.mark_present_channels_training_pass();
                 self.mark_present_channels_training_pass();
@@ -2051,8 +2394,6 @@ impl StationState {
                     }
                     }
                     self.hot.rmt_complete = true;
                     self.hot.rmt_complete = true;
                 }
                 }
-                self.prompt_ready = false;
-                self.hot.prompt_ready = false;
                 if ev.subkind == 4 {
                 if ev.subkind == 4 {
                     if self.observed_uip_stage.unwrap_or(1) > 1 {
                     if self.observed_uip_stage.unwrap_or(1) > 1 {
                         self.hot.ict_stage2_complete = true;
                         self.hot.ict_stage2_complete = true;
@@ -2165,6 +2506,8 @@ impl StationState {
                     self.dimm_soa.rmt_rx_vref_lo[slot_idx] = ev.val2 as i16;
                     self.dimm_soa.rmt_rx_vref_lo[slot_idx] = ev.val2 as i16;
                     self.dimm_soa.rmt_rx_vref_hi[slot_idx] = ev.val3 as i16;
                     self.dimm_soa.rmt_rx_vref_hi[slot_idx] = ev.val3 as i16;
                     self.dimms[slot_idx].presence = "present".to_string();
                     self.dimms[slot_idx].presence = "present".to_string();
+                    self.dimm_seen_in_boot[slot_idx] = true;
+                    self.sdr_absent_streak[slot_idx] = 0;
                     if self.dimms[slot_idx].enabled == "unknown" {
                     if self.dimms[slot_idx].enabled == "unknown" {
                         self.dimms[slot_idx].enabled = "enabled".to_string();
                         self.dimms[slot_idx].enabled = "enabled".to_string();
                     }
                     }
@@ -2495,6 +2838,19 @@ impl StationState {
                     let mut ch = if ev.channel >= 0 { Some(ev.channel as i64) } else { None };
                     let mut ch = if ev.channel >= 0 { Some(ev.channel as i64) } else { None };
                     let mut dimm = if ev.dimm >= 0 { Some(ev.dimm as i64) } else { None };
                     let mut dimm = if ev.dimm >= 0 { Some(ev.dimm as i64) } else { None };
                     self.resolve_coords_from_sn(trimmed, &mut cpu, &mut ch, &mut dimm);
                     self.resolve_coords_from_sn(trimmed, &mut cpu, &mut ch, &mut dimm);
+                    if cpu.is_none() {
+                        if let Some(c) = ch {
+                            if (0..12).contains(&c) {
+                                let s0 = self.dimms[c as usize].presence == "present";
+                                let s1 = self.dimms[12 + (c as usize)].presence == "present";
+                                if s0 && !s1 {
+                                    cpu = Some(0);
+                                } else if s1 && !s0 {
+                                    cpu = Some(1);
+                                }
+                            }
+                        }
+                    }
                     self.record_stage_error_coords(
                     self.record_stage_error_coords(
                         "mt",
                         "mt",
                         cpu,
                         cpu,
@@ -2593,6 +2949,37 @@ impl StationState {
     }
     }
 
 
     fn apply_prompt_event(&mut self, ev: &lib::StlRe2cEvent, raw_bytes: &[u8], now: i64) {
     fn apply_prompt_event(&mut self, ev: &lib::StlRe2cEvent, raw_bytes: &[u8], now: i64) {
+        let bp_state_now = self.boot_execution.get_str_or("state", "idle");
+        let is_terminal = matches!(
+            bp_state_now.as_str(),
+            "blocked" | "failed" | "completed" | "stopped" | "interrupted"
+        ) || matches!(
+            self.task_status.as_str(),
+            "failed" | "completed" | "interrupted"
+        );
+        if ev.kind == lib::STL_LK_ICT_ENTER_HINT
+            && (is_terminal
+                || self.awaiting_dimm_replacement
+                || self.hot.ict_stage2_complete
+                || self.hot.uefi_complete
+                || self.hot.mt_banner_seen
+                || self.hot.mt_pass_complete
+                || self.hot.mt_fail_complete
+                || self.observed_stages.contains("uefi")
+                || self.observed_stages.contains("mt")
+                || self.observed_stages.contains("post"))
+        {
+            self.clear_for_external_restart(now, "uip_enter_reboot", true);
+        } else if ev.kind == lib::STL_LK_ICT_PROMPT
+            && (self.hot.uefi_complete
+                || self.hot.mt_banner_seen
+                || self.hot.mt_pass_complete
+                || self.hot.mt_fail_complete
+                || self.observed_stages.contains("uefi")
+                || self.observed_stages.contains("mt"))
+        {
+            self.clear_for_external_restart(now, "uip_prompt_reboot", true);
+        }
         if self.hot.awaiting_reset_banner && self.bmc_enabled && !self.bmc_host.is_empty() {
         if self.hot.awaiting_reset_banner && self.bmc_enabled && !self.bmc_host.is_empty() {
             return;
             return;
         }
         }

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

@@ -173,9 +173,23 @@ pub fn load_station_settings(data_dir: &Path, stations: &mut BTreeMap<String, St
         }
         }
         if let Some(tb) = saved.get("task_batch") {
         if let Some(tb) = saved.get("task_batch") {
             let mut clean_tb = strip_private_keys_recursive(tb);
             let mut clean_tb = strip_private_keys_recursive(tb);
-            if clean_tb.get_str_or("state", "idle") == "running" {
-                clean_tb.set("state", JsonVal::Str("interrupted".to_string()));
-                clean_tb.set("updated_unix_ms", JsonVal::Str(crate::results::now_ms().to_string()));
+            let tb_state = clean_tb.get_str_or("state", "idle");
+            if matches!(
+                tb_state.as_str(),
+                "running" | "paused" | "failed" | "blocked" | "interrupted" | "completed"
+            ) {
+                clean_tb.set("batch_id", JsonVal::Str(String::new()));
+                clean_tb.set("state", JsonVal::Str("idle".to_string()));
+                clean_tb.set("current_profile_index", JsonVal::Num(0.0));
+                clean_tb.set("current_repeat", JsonVal::Num(0.0));
+                clean_tb.set("total_runs_completed", JsonVal::Num(0.0));
+                clean_tb.set("total_runs_planned", JsonVal::Num(0.0));
+                clean_tb.set("profiles", JsonVal::Arr(Vec::new()));
+                clean_tb.set("runs", JsonVal::Arr(Vec::new()));
+                clean_tb.set(
+                    "updated_unix_ms",
+                    JsonVal::Str(crate::results::now_ms().to_string()),
+                );
             }
             }
             st.task_batch = clean_tb;
             st.task_batch = clean_tb;
         }
         }

Diferenças do arquivo suprimidas por serem muito extensas
+ 4344 - 0
native/stl_accel/src/thermal_mcu.rs


+ 224 - 45
native/stl_accel/src/workflow.rs

@@ -99,7 +99,41 @@ pub fn tick_async_script(st: &mut StationState) {
 
 
     if !st.async_script.waiting_prompt_kind.is_empty() {
     if !st.async_script.waiting_prompt_kind.is_empty() {
         let want_kind = st.async_script.waiting_prompt_kind.as_str();
         let want_kind = st.async_script.waiting_prompt_kind.as_str();
-        let matched = st.prompt_ready && (want_kind == "*" || st.prompt_kind == want_kind);
+        let hl_str = String::from_utf8_lossy(st.cleaner.halfline_bytes()).to_string();
+        let clean_end_pre = st.clean_ring.write_offset();
+        let start_off_pre = st
+            .async_script
+            .step_start_clean_off
+            .max(st.clean_ring.base_offset())
+            .min(clean_end_pre);
+        let read_len_pre = (clean_end_pre.saturating_sub(start_off_pre) as usize).min(65536);
+        let (out_bytes_pre, _) = if want_kind == "grub_menu" || want_kind == "grub_cli" {
+            st.clean_ring.read_from(start_off_pre, read_len_pre)
+        } else {
+            (Vec::new(), 0)
+        };
+        let out_str_pre = if want_kind == "grub_menu" || want_kind == "grub_cli" {
+            String::from_utf8_lossy(&out_bytes_pre).to_string()
+        } else {
+            String::new()
+        };
+        let matched = if want_kind == "grub_menu" {
+            out_str_pre.contains("highlighted entry")
+                || out_str_pre.contains("GRUB version")
+                || out_str_pre.contains("Use the")
+                || hl_str.contains("highlighted entry")
+                || hl_str.trim_end().ends_with("grub>")
+                || out_str_pre
+                    .lines()
+                    .any(|l| l.trim_end().ends_with("grub>"))
+        } else if want_kind == "grub_cli" {
+            hl_str.trim_end().ends_with("grub>")
+                || out_str_pre
+                    .lines()
+                    .any(|l| l.trim_end().ends_with("grub>"))
+        } else {
+            st.prompt_ready && (want_kind == "*" || st.prompt_kind == want_kind)
+        };
         let timed_out = !matched && now >= st.async_script.step_deadline_ms;
         let timed_out = !matched && now >= st.async_script.step_deadline_ms;
         if !matched && !timed_out {
         if !matched && !timed_out {
             return;
             return;
@@ -122,13 +156,18 @@ pub fn tick_async_script(st: &mut StationState) {
                 || lower_out.contains("is not a directory");
                 || lower_out.contains("is not a directory");
             let has_dir_listing =
             let has_dir_listing =
                 lower_out.contains("directory of:") || lower_out.contains("file(s)");
                 lower_out.contains("directory of:") || lower_out.contains("file(s)");
-            let target_base = st
-                .async_script
-                .extra_meta
-                .get_str("probe_efi_basename")
-                .unwrap_or("118.efi")
-                .to_ascii_lowercase();
-            let found_efi = !not_found
+            let sent_lower = st.async_script.step_sent_line.trim().to_ascii_lowercase();
+            let probing_grub = sent_lower.contains("grubx64.efi");
+            let target_base = if probing_grub {
+                "grubx64.efi".to_string()
+            } else {
+                st.async_script
+                    .extra_meta
+                    .get_str("probe_efi_basename")
+                    .unwrap_or("118.efi")
+                    .to_ascii_lowercase()
+            };
+            let found_file = !not_found
                 && has_dir_listing
                 && has_dir_listing
                 && out_str.lines().any(|ln| {
                 && out_str.lines().any(|ln| {
                     let t = ln.trim().to_ascii_lowercase();
                     let t = ln.trim().to_ascii_lowercase();
@@ -138,14 +177,18 @@ pub fn tick_async_script(st: &mut StationState) {
                         && t.contains(&target_base)
                         && t.contains(&target_base)
                         && (t.ends_with(&target_base) || t.contains(&format!(" {}", target_base)))
                         && (t.ends_with(&target_base) || t.contains(&format!(" {}", target_base)))
                 });
                 });
-            if found_efi {
+            if found_file {
                 if let Some(cand) = st.async_script.step_sent_line.strip_prefix("ls ") {
                 if let Some(cand) = st.async_script.step_sent_line.strip_prefix("ls ") {
                     let mut resolved = cand.trim().to_string();
                     let mut resolved = cand.trim().to_string();
                     if let Some(colon) = resolved.find(':') {
                     if let Some(colon) = resolved.find(':') {
                         let (drv, rest) = resolved.split_at(colon + 1);
                         let (drv, rest) = resolved.split_at(colon + 1);
                         resolved = format!("{}{}", drv.to_ascii_uppercase(), rest);
                         resolved = format!("{}{}", drv.to_ascii_uppercase(), rest);
                     }
                     }
-                    st.resolved_mt_efi_path = Some(resolved);
+                    if probing_grub {
+                        st.resolved_grub_tftp_loader = Some(resolved);
+                    } else {
+                        st.resolved_mt_efi_path = Some(resolved);
+                    }
                 }
                 }
                 st.efi_probe_done = true;
                 st.efi_probe_done = true;
                 let maybe_sel = st.async_script.extra_meta.get("start_mt_sel").cloned();
                 let maybe_sel = st.async_script.extra_meta.get("start_mt_sel").cloned();
@@ -154,6 +197,8 @@ pub fn tick_async_script(st: &mut StationState) {
                     let mut meta = st.async_script.extra_meta.clone();
                     let mut meta = st.async_script.extra_meta.clone();
                     if let Some(ref resolved) = st.resolved_mt_efi_path {
                     if let Some(ref resolved) = st.resolved_mt_efi_path {
                         meta.set("command", JsonVal::Str(resolved.clone()));
                         meta.set("command", JsonVal::Str(resolved.clone()));
+                    } else if let Some(ref grub) = st.resolved_grub_tftp_loader {
+                        meta.set("command", JsonVal::Str(format!("{} -> (tftp)/{}", grub, st.async_script.extra_meta.get_str("probe_efi_basename").unwrap_or("118.efi"))));
                     }
                     }
                     let steps = build_uefi_mt_steps(st, &sel);
                     let steps = build_uefi_mt_steps(st, &sel);
                     st.plan_mt_started = true;
                     st.plan_mt_started = true;
@@ -276,14 +321,24 @@ pub fn tick_async_script(st: &mut StationState) {
             finish_async_script(st, now);
             finish_async_script(st, now);
             return;
             return;
         };
         };
+        if step.line == "__GRUB_C__" {
+            let hl_now = String::from_utf8_lossy(st.cleaner.halfline_bytes()).to_string();
+            if hl_now.trim_end().ends_with("grub>") {
+                continue;
+            }
+        }
         st.async_script.step_start_clean_off = st.clean_ring.write_offset();
         st.async_script.step_start_clean_off = st.clean_ring.write_offset();
         st.async_script.step_sent_line = step.line.clone();
         st.async_script.step_sent_line = step.line.clone();
         st.async_script.waiting_prompt_kind = step.expected_prompt_kind.clone();
         st.async_script.waiting_prompt_kind = step.expected_prompt_kind.clone();
         st.async_script.step_deadline_ms = now + step.timeout_ms.max(200);
         st.async_script.step_deadline_ms = now + step.timeout_ms.max(200);
         st.async_script.reject_on_fw_error = step.reject_on_fw_error;
         st.async_script.reject_on_fw_error = step.reject_on_fw_error;
 
 
-        let wire = format!("{}\r", step.line);
-        if let Err(e) = write_station_paced(st, wire.as_bytes()) {
+        let wire_bytes = if step.line == "__GRUB_C__" {
+            b"c".to_vec()
+        } else {
+            format!("{}\r", step.line).into_bytes()
+        };
+        if let Err(e) = write_station_paced(st, &wire_bytes) {
             if st.async_script.context_tag.starts_with("plan_") {
             if st.async_script.context_tag.starts_with("plan_") {
                 st.task_status = "failed".to_string();
                 st.task_status = "failed".to_string();
                 let batch_continuing = st.task_batch.get_str_or("state", "idle") == "running"
                 let batch_continuing = st.task_batch.get_str_or("state", "idle") == "running"
@@ -584,7 +639,8 @@ pub fn control_boot_plan_impl(
                 for v in st.stage_errors.values_mut() {
                 for v in st.stage_errors.values_mut() {
                     v.clear();
                     v.clear();
                 }
                 }
-                st.reset_all_dimm_stages();
+                st.last_err_stage.clear();
+                st.reset_dimms_for_new_boot();
             } else {
             } else {
                 if st.run_started_unix_ms <= 0
                 if st.run_started_unix_ms <= 0
                     || (!preserve_batch_timer && st.run_ended_unix_ms > 0)
                     || (!preserve_batch_timer && st.run_ended_unix_ms > 0)
@@ -699,7 +755,10 @@ pub fn extract_efi_basename(norm_path: &str) -> String {
 }
 }
 
 
 pub fn needs_uefi_efi_probe(st: &StationState, sel: &JsonVal) -> bool {
 pub fn needs_uefi_efi_probe(st: &StationState, sel: &JsonVal) -> bool {
-    if st.efi_probe_done || st.resolved_mt_efi_path.is_some() {
+    if st.efi_probe_done
+        || st.resolved_mt_efi_path.is_some()
+        || st.resolved_grub_tftp_loader.is_some()
+    {
         return false;
         return false;
     }
     }
     let raw_cfg = sel
     let raw_cfg = sel
@@ -710,15 +769,9 @@ pub fn needs_uefi_efi_probe(st: &StationState, sel: &JsonVal) -> bool {
     if !norm_path.to_ascii_uppercase().ends_with(".EFI") {
     if !norm_path.to_ascii_uppercase().ends_with(".EFI") {
         return false;
         return false;
     }
     }
-    let explicit_non_fs0 = norm_path.contains(':') && !norm_path.to_ascii_uppercase().starts_with("FS0:\\EFI\\");
-    if explicit_non_fs0 {
-        return false;
-    }
-    let cur_prompt = st.prompt_evidence.to_ascii_uppercase();
-    let already_in_efi = st.observed_detail == "uefi_shell_efi"
-        || cur_prompt.contains("\\EFI\\>")
-        || cur_prompt.contains("\\EFI>");
-    st.uefi_fs_candidates.len() > 1 || (!already_in_efi && !cur_prompt.contains("\\EFI"))
+    let explicit_non_fs0 =
+        norm_path.contains(':') && !norm_path.to_ascii_uppercase().starts_with("FS0:\\EFI\\");
+    !explicit_non_fs0
 }
 }
 
 
 pub fn build_uefi_efi_probe_steps_for(st: &StationState, sel: &JsonVal) -> (Vec<AsyncScriptStep>, String) {
 pub fn build_uefi_efi_probe_steps_for(st: &StationState, sel: &JsonVal) -> (Vec<AsyncScriptStep>, String) {
@@ -755,6 +808,22 @@ pub fn build_uefi_efi_probe_steps_for(st: &StationState, sel: &JsonVal) -> (Vec<
             reject_on_fw_error: false,
             reject_on_fw_error: false,
         });
         });
     }
     }
+    for fs in &cands {
+        steps.push(AsyncScriptStep {
+            line: format!("ls {}\\EFI\\redhat\\grubx64.efi", fs.to_ascii_lowercase()),
+            expected_prompt_kind: "uefi".to_string(),
+            timeout_ms: 2500,
+            reject_on_fw_error: false,
+        });
+    }
+    for fs in &cands {
+        steps.push(AsyncScriptStep {
+            line: format!("ls {}\\EFI\\BOOT\\grubx64.efi", fs.to_ascii_lowercase()),
+            expected_prompt_kind: "uefi".to_string(),
+            timeout_ms: 2500,
+            reject_on_fw_error: false,
+        });
+    }
     (steps, base_efi)
     (steps, base_efi)
 }
 }
 
 
@@ -823,8 +892,17 @@ pub fn build_uefi_mt_steps(st: &StationState, sel: &JsonVal) -> Vec<AsyncScriptS
                 reject_on_fw_error: false,
                 reject_on_fw_error: false,
             });
             });
         }
         }
-        let tftp_ip = sel.get_str_or("pxe_server_ip", "192.168.0.10");
-        let cfg_lines: Vec<String> = render_mt86_cfg_text(sel, &tftp_ip)
+        let tftp_ip = sel
+            .get_str("pxe_server_ip")
+            .filter(|s| !s.trim().is_empty())
+            .unwrap_or_else(|| {
+                if st.pxe_server_ip.trim().is_empty() {
+                    "192.168.0.10"
+                } else {
+                    st.pxe_server_ip.as_str()
+                }
+            });
+        let cfg_lines: Vec<String> = render_mt86_cfg_text(sel, tftp_ip)
             .lines()
             .lines()
             .map(|l| l.trim().to_string())
             .map(|l| l.trim().to_string())
             .filter(|l| !l.is_empty())
             .filter(|l| !l.is_empty())
@@ -852,6 +930,52 @@ pub fn build_uefi_mt_steps(st: &StationState, sel: &JsonVal) -> Vec<AsyncScriptS
                 reject_on_fw_error: false,
                 reject_on_fw_error: false,
             });
             });
         }
         }
+        if st.resolved_mt_efi_path.is_none() {
+            if let Some(ref grub_loader) = st.resolved_grub_tftp_loader {
+                steps.push(AsyncScriptStep {
+                    line: format!(r"cp -q mt86.cfg {}\EFI\BOOT\mt86.cfg", target_fs.to_ascii_lowercase()),
+                    expected_prompt_kind: "uefi".to_string(),
+                    timeout_ms: 2500,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: format!(r"cp -q mt86.cfg {}\EFI\BOOT\{}.cfg", target_fs.to_ascii_lowercase(), efi_stem),
+                    expected_prompt_kind: "uefi".to_string(),
+                    timeout_ms: 2500,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: grub_loader.clone(),
+                    expected_prompt_kind: "grub_menu".to_string(),
+                    timeout_ms: 5000,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: "__GRUB_C__".to_string(),
+                    expected_prompt_kind: "grub_cli".to_string(),
+                    timeout_ms: 4000,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: "net_bootp".to_string(),
+                    expected_prompt_kind: "grub_cli".to_string(),
+                    timeout_ms: 10000,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: format!("chainloader (tftp,{})/pxe_sync.efi", tftp_ip),
+                    expected_prompt_kind: "grub_cli".to_string(),
+                    timeout_ms: 15000,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: "boot ; exit".to_string(),
+                    expected_prompt_kind: "uefi".to_string(),
+                    timeout_ms: 8000,
+                    reject_on_fw_error: false,
+                });
+            }
+        }
         let args_tail = sel.get_str_or("arguments", "");
         let args_tail = sel.get_str_or("arguments", "");
         let launch_line = if args_tail.trim().is_empty() {
         let launch_line = if args_tail.trim().is_empty() {
             efi_basename
             efi_basename
@@ -1069,6 +1193,27 @@ pub fn step_boot_plan(st: &mut StationState, contract: &FirmwareContract) {
     match stage {
     match stage {
         "uip1" | "uip2" => {
         "uip1" | "uip2" => {
             let target_stg = if stage == "uip2" { 2u8 } else { 1u8 };
             let target_stg = if stage == "uip2" { 2u8 } else { 1u8 };
+            if target_stg == 1 {
+                let has_rmt_disable = st.uip_overrides.iter().any(|x| {
+                    x.get_str_or("id", "") == "rmt"
+                        && x.get_str_or("value", "").trim().eq_ignore_ascii_case("disable")
+                });
+                if let Some(want_rmt) = st.boot_plan.get_bool("run_rmt") {
+                    if !want_rmt || (fw_fam != "cxmt" && has_rmt_disable) {
+                        FirmwareContract::apply_rmt_policy_to_uip_overrides(
+                            &mut st.uip_overrides,
+                            if has_rmt_disable { false } else { want_rmt },
+                            fw_fam,
+                        );
+                    }
+                } else if fw_fam != "cxmt" && has_rmt_disable {
+                    FirmwareContract::apply_rmt_policy_to_uip_overrides(
+                        &mut st.uip_overrides,
+                        false,
+                        fw_fam,
+                    );
+                }
+            }
             match contract.build_uip_commands_for_family(
             match contract.build_uip_commands_for_family(
                 &st.uip_overrides,
                 &st.uip_overrides,
                 &st.uip_raw_commands,
                 &st.uip_raw_commands,
@@ -1261,19 +1406,17 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
     if stage_key == "uip1" {
     if stage_key == "uip1" {
         if let Some((_, rmt_act, rmt_params, _)) = st.take_stage_intent("rmt") {
         if let Some((_, rmt_act, rmt_params, _)) = st.take_stage_intent("rmt") {
             let want_rmt = match rmt_act.as_str() {
             let want_rmt = match rmt_act.as_str() {
-                "disable" | "skip_rmt" => false,
+                "disable" | "skip_rmt" | "skip" => false,
                 "enable" | "start_rmt" => true,
                 "enable" | "start_rmt" => true,
                 _ => rmt_params.get_bool("enabled").unwrap_or(true),
                 _ => rmt_params.get_bool("enabled").unwrap_or(true),
             };
             };
-            st.uip_overrides.retain(|x| x.get_str_or("id", "") != "rmt");
-            let mut rmt_ov = JsonVal::obj();
-            rmt_ov.set("id", JsonVal::Str("rmt".to_string()));
-            rmt_ov.set("mode", JsonVal::Str("override".to_string()));
-            rmt_ov.set(
-                "value",
-                JsonVal::Str(if want_rmt { "enable" } else { "disable" }.to_string()),
+            st.boot_plan.set("run_rmt", JsonVal::Bool(want_rmt));
+            let fam = st.fw_family_name().to_string();
+            FirmwareContract::apply_rmt_policy_to_uip_overrides(
+                &mut st.uip_overrides,
+                want_rmt,
+                &fam,
             );
             );
-            st.uip_overrides.push(rmt_ov);
         }
         }
     }
     }
     if stage_key == "mt" && !st.efi_probe_done && st.resolved_mt_efi_path.is_none() {
     if stage_key == "mt" && !st.efi_probe_done && st.resolved_mt_efi_path.is_none() {
@@ -1342,6 +1485,27 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
     match (stage_key, action.as_str()) {
     match (stage_key, action.as_str()) {
         ("uip1" | "uip2", "continue_uip" | "apply_uip" | "enable") => {
         ("uip1" | "uip2", "continue_uip" | "apply_uip" | "enable") => {
             let target_stg = if stage_key == "uip2" { 2u8 } else { 1u8 };
             let target_stg = if stage_key == "uip2" { 2u8 } else { 1u8 };
+            if target_stg == 1 {
+                let has_rmt_disable = st.uip_overrides.iter().any(|x| {
+                    x.get_str_or("id", "") == "rmt"
+                        && x.get_str_or("value", "").trim().eq_ignore_ascii_case("disable")
+                });
+                if let Some(want_rmt) = st.boot_plan.get_bool("run_rmt") {
+                    if !want_rmt || (fw_fam != "cxmt" && has_rmt_disable) {
+                        FirmwareContract::apply_rmt_policy_to_uip_overrides(
+                            &mut st.uip_overrides,
+                            if has_rmt_disable { false } else { want_rmt },
+                            fw_fam,
+                        );
+                    }
+                } else if fw_fam != "cxmt" && has_rmt_disable {
+                    FirmwareContract::apply_rmt_policy_to_uip_overrides(
+                        &mut st.uip_overrides,
+                        false,
+                        fw_fam,
+                    );
+                }
+            }
             let cmds = contract
             let cmds = contract
                 .build_uip_commands_for_family(
                 .build_uip_commands_for_family(
                     &st.uip_overrides,
                     &st.uip_overrides,
@@ -1497,6 +1661,13 @@ fn consume_pending_stage_intent(st: &mut StationState, contract: &FirmwareContra
                     "algorithms",
                     "algorithms",
                     "addr_lim_lo",
                     "addr_lim_lo",
                     "addr_lim_hi",
                     "addr_lim_hi",
+                    "ADDRLIMLO",
+                    "ADDRLIMHI",
+                    "addr_lo",
+                    "addr_hi",
+                    "ecc",
+                    "eccpoll",
+                    "debuglog",
                 ] {
                 ] {
                     st.mt_selection.remove(stale);
                     st.mt_selection.remove(stale);
                 }
                 }
@@ -1637,20 +1808,26 @@ pub fn apply_profile_to_station(
         }
         }
         built_ovs
         built_ovs
     };
     };
+    let eff_run_rmt = if FirmwareContract::rmt_selected_is_disable_only(profile.get("rmt")) {
+        false
+    } else {
+        run_rmt
+    };
     if profile.get_bool("run_rmt").is_some()
     if profile.get_bool("run_rmt").is_some()
         || profile.get("rmt").and_then(|r| r.get_bool("enabled")).is_some()
         || profile.get("rmt").and_then(|r| r.get_bool("enabled")).is_some()
+        || !eff_run_rmt
     {
     {
-        uip_ovs.retain(|x| x.get_str_or("id", "") != "rmt");
-    }
-    if !uip_ovs.iter().any(|x| x.get_str_or("id", "") == "rmt") {
-        let mut rmt_ov = JsonVal::obj();
-        rmt_ov.set("id", JsonVal::Str("rmt".to_string()));
-        rmt_ov.set("mode", JsonVal::Str("override".to_string()));
-        rmt_ov.set(
-            "value",
-            JsonVal::Str(if run_rmt { "enable" } else { "disable" }.to_string()),
+        FirmwareContract::apply_rmt_policy_to_uip_overrides(
+            &mut uip_ovs,
+            eff_run_rmt,
+            st.fw_family_name(),
+        );
+    } else if !uip_ovs.iter().any(|x| matches!(x.get_str_or("id", "").as_str(), "rmt" | "maskmain")) {
+        FirmwareContract::apply_rmt_policy_to_uip_overrides(
+            &mut uip_ovs,
+            eff_run_rmt,
+            st.fw_family_name(),
         );
         );
-        uip_ovs.push(rmt_ov);
     }
     }
     if run_mt
     if run_mt
         && pxe_state.get_bool("stage1_pxe_enabled").unwrap_or(false)
         && pxe_state.get_bool("stage1_pxe_enabled").unwrap_or(false)
@@ -1947,7 +2124,9 @@ pub fn step_task_batch(
                 .or_else(|| st.single_run_profile.get_str("task_name"))
                 .or_else(|| st.single_run_profile.get_str("task_name"))
                 .unwrap_or("Single-Run")
                 .unwrap_or("Single-Run")
                 .to_string();
                 .to_string();
-            let verdict = if bp_state == "completed" {
+            let has_any_err = st.awaiting_dimm_replacement
+                || st.stage_errors.values().any(|v| !v.is_empty());
+            let verdict = if bp_state == "completed" && !has_any_err {
                 st.task_status = "completed".to_string();
                 st.task_status = "completed".to_string();
                 "pass"
                 "pass"
             } else {
             } else {

+ 1 - 0
native/stl_accel/stl_accel.h

@@ -268,6 +268,7 @@ int     c_ipmi_raw(
     size_t         out_cap,
     size_t         out_cap,
     size_t        *out_len);
     size_t        *out_len);
 int     c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len);
 int     c_ipmi_sdr_temp_list(int handle, char *out_buf, size_t out_cap, size_t *out_len);
+void    c_ipmi_invalidate_sdr_cache(int handle);
 int     c_ipmi_device_info(
 int     c_ipmi_device_info(
     int         handle,
     int         handle,
     const char *kind,
     const char *kind,

+ 191 - 0
tools/pxe_sync.zig

@@ -0,0 +1,191 @@
+const std = @import("std");
+const uefi = std.os.uefi;
+const Status = uefi.Status;
+const Handle = uefi.Handle;
+const SimpleFileSystem = uefi.protocol.SimpleFileSystem;
+
+const MAX_PAYLOAD_BYTES: usize = 2 * 1024 * 1024;
+const MAGIC_STR: [16]u8 = "XJKJ_PXESYNC_V1\x00".*;
+
+pub const PxePayloadSlot = extern struct {
+    magic: [16]u8,
+    payload_len: u64,
+    target_path: [64]u8,
+    data: [MAX_PAYLOAD_BYTES]u8,
+};
+
+pub export var g_pxe_payload_slot: PxePayloadSlot align(16) = blk: {
+    var slot: PxePayloadSlot = undefined;
+    slot.magic = MAGIC_STR;
+    slot.payload_len = 0;
+    slot.target_path = @splat(0);
+    const def_path = "\\EFI\\118.efi";
+    @memcpy(slot.target_path[0..def_path.len], def_path);
+    slot.data = @splat(0x5A);
+    break :blk slot;
+};
+
+fn puts(con: *uefi.protocol.SimpleTextOutput, msg: []const u8) void {
+    var buf: [256:0]u16 = undefined;
+    var i: usize = 0;
+    for (msg) |ch| {
+        if (i + 2 >= buf.len) break;
+        if (ch == '\n') {
+            buf[i] = '\r';
+            i += 1;
+        }
+        buf[i] = ch;
+        i += 1;
+    }
+    buf[i] = 0;
+    _ = con.outputString(@ptrCast(&buf)) catch {};
+}
+
+fn putDec(con: *uefi.protocol.SimpleTextOutput, val: usize) void {
+    var digits: [24]u8 = undefined;
+    var v = val;
+    var idx: usize = digits.len;
+    if (v == 0) {
+        puts(con, "0");
+        return;
+    }
+    while (v > 0 and idx > 0) {
+        idx -= 1;
+        digits[idx] = @intCast('0' + (v % 10));
+        v /= 10;
+    }
+    puts(con, digits[idx..]);
+}
+
+fn readVolatileU64(ptr: *const volatile u64) u64 {
+    return ptr.*;
+}
+
+fn findTargetVolume(
+    bs: *uefi.tables.BootServices,
+    cfg_rel_w: [:0]const u16,
+    efi_dir_w: [:0]const u16,
+) ?*uefi.protocol.File {
+    const fs_len = bs.locateHandleLen(.{ .by_protocol = &SimpleFileSystem.guid }) catch return null;
+    if (fs_len == 0) return null;
+
+    var fs_handles_buf: [32]Handle = undefined;
+    const fs_slice = bs.locateHandle(.{ .by_protocol = &SimpleFileSystem.guid }, fs_handles_buf[0..@min(fs_len, 32)]) catch return null;
+
+    var efi_fallback: ?*uefi.protocol.File = null;
+    var first_fallback: ?*uefi.protocol.File = null;
+
+    for (fs_slice) |h| {
+        const sfs = (bs.handleProtocol(SimpleFileSystem, h) catch null) orelse continue;
+        const root = sfs.openVolume() catch continue;
+
+        if (root.open(cfg_rel_w, .read, .{}) catch null) |cfg_f| {
+            _ = cfg_f.close() catch {};
+            if (efi_fallback) |old_efi| _ = old_efi.close() catch {};
+            if (first_fallback) |old_first| _ = old_first.close() catch {};
+            return root;
+        }
+        if (efi_fallback == null) {
+            if (root.open(efi_dir_w, .read, .{}) catch null) |dir_f| {
+                _ = dir_f.close() catch {};
+                efi_fallback = root;
+                continue;
+            }
+        }
+        if (first_fallback == null) {
+            first_fallback = root;
+        } else {
+            _ = root.close() catch {};
+        }
+    }
+
+    if (efi_fallback) |efi_root| {
+        if (first_fallback) |f_root| _ = f_root.close() catch {};
+        return efi_root;
+    }
+    return first_fallback;
+}
+
+pub fn main() Status {
+    const st = uefi.system_table;
+    const bs = st.boot_services orelse return .unsupported;
+    const con = st.con_out orelse return .unsupported;
+
+    const slot_ptr: *const volatile PxePayloadSlot = &g_pxe_payload_slot;
+    var i: usize = 0;
+    while (i < MAGIC_STR.len) : (i += 1) {
+        if (slot_ptr.magic[i] != MAGIC_STR[i]) {
+            puts(con, "[pxe_sync] Invalid payload slot header\n");
+            return .load_error;
+        }
+    }
+
+    const payload_len_u64 = readVolatileU64(&slot_ptr.payload_len);
+    if (payload_len_u64 == 0 or payload_len_u64 > MAX_PAYLOAD_BYTES) {
+        puts(con, "[pxe_sync] Empty or oversized payload slot\n");
+        return .bad_buffer_size;
+    }
+    const payload_len: usize = @intCast(payload_len_u64);
+
+    var rel_w: [64:0]u16 = undefined;
+    var rel_len: usize = 0;
+    while (rel_len < 63) : (rel_len += 1) {
+        const ch = slot_ptr.target_path[rel_len];
+        if (ch == 0) break;
+        rel_w[rel_len] = if (ch == '/') '\\' else ch;
+    }
+    if (rel_len == 0) {
+        const def = "\\EFI\\118.efi";
+        for (def, 0..) |ch, idx| {
+            rel_w[idx] = ch;
+        }
+        rel_len = def.len;
+    }
+    rel_w[rel_len] = 0;
+
+    const cfg_rel_w = std.unicode.utf8ToUtf16LeStringLiteral("\\EFI\\mt86.cfg");
+    const efi_dir_w = std.unicode.utf8ToUtf16LeStringLiteral("\\EFI");
+    const root = findTargetVolume(bs, cfg_rel_w, efi_dir_w) orelse {
+        puts(con, "[pxe_sync] No writable SimpleFileSystem volume found\n");
+        return .not_found;
+    };
+    defer _ = root.close() catch {};
+
+    if (root.open(efi_dir_w, .read, .{}) catch null) |d| {
+        _ = d.close() catch {};
+    } else {
+        if (root.open(efi_dir_w, .read_write_create, .{ .directory = true }) catch null) |d| {
+            _ = d.close() catch {};
+        }
+    }
+
+    const target_w: [*:0]const u16 = @ptrCast(&rel_w);
+    if (root.open(target_w, .read_write, .{}) catch null) |old_f| {
+        _ = old_f.delete() catch {};
+    }
+    const out_f = root.open(target_w, .read_write_create, .{}) catch {
+        puts(con, "[pxe_sync] Failed to create target EFI file\n");
+        return .device_error;
+    };
+
+    const src_ptr: [*]const u8 = @ptrCast(@volatileCast(&slot_ptr.data));
+    const src_slice = src_ptr[0..payload_len];
+    var written: usize = 0;
+    while (written < payload_len) {
+        const chunk = @min(payload_len - written, 65536);
+        const n = out_f.write(src_slice[written .. written + chunk]) catch {
+            puts(con, "[pxe_sync] Write error\n");
+            _ = out_f.close() catch {};
+            return .device_error;
+        };
+        if (n == 0) break;
+        written += n;
+    }
+    _ = out_f.flush() catch {};
+    _ = out_f.close() catch {};
+
+    puts(con, "[pxe_sync] Synced local EFI bytes=");
+    putDec(con, written);
+    puts(con, "\n");
+    return .success;
+}

+ 1 - 0
web/app.js

@@ -381,6 +381,7 @@
       amt_dispatch:'AMT 固件下发',
       amt_dispatch:'AMT 固件下发',
       pxe_mt86:'PXE 与 mt86.cfg',
       pxe_mt86:'PXE 与 mt86.cfg',
       boot_plan:'启动计划',
       boot_plan:'启动计划',
+      thermal_mcu:'高温罩温控',
       connections:'连接设置',
       connections:'连接设置',
       dimm_replacement:'停机换条确认',
       dimm_replacement:'停机换条确认',
       stage_intent:'阶段预设覆盖',
       stage_intent:'阶段预设覆盖',

+ 1 - 1
web/firmware-controls.js

@@ -607,7 +607,7 @@
         api.status(`N540 已配置为纯净透传 (${mode}, 115200 8N1, bootinfo_en=OFF, sock_rto=0) 并触发重启生效`);
         api.status(`N540 已配置为纯净透传 (${mode}, 115200 8N1, bootinfo_en=OFF, sock_rto=0) 并触发重启生效`);
       });
       });
     }
     }
-    for (const [btnId, targetIp] of [['btn-bmc-preset-166','192.168.2.166'],['btn-bmc-preset-165','192.168.2.165'],['btn-bmc-preset-168','192.168.2.168']]) {
+    for (const [btnId, targetIp] of [['btn-bmc-preset-166','192.168.2.166'],['btn-bmc-preset-165','192.168.2.165'],['btn-bmc-preset-167','192.168.2.167']]) {
       if ($(btnId)) {
       if ($(btnId)) {
         api.bind(btnId, async () => {
         api.bind(btnId, async () => {
           $('connection-console-enabled').checked = true;
           $('connection-console-enabled').checked = true;

Diferenças do arquivo suprimidas por serem muito extensas
+ 309 - 8
web/index.html


+ 23 - 2
web/style.css

@@ -725,5 +725,26 @@ body:not([data-current-page="overview"]) .workspace-split { grid-template-column
 .th-manual-grid { display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px; }
 .th-manual-grid { display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px; }
 .th-manual-grid label { display:flex;flex-direction:column;gap:4px;font-size:11.5px;color:#57707d; }
 .th-manual-grid label { display:flex;flex-direction:column;gap:4px;font-size:11.5px;color:#57707d; }
 .th-log-pre { margin:0;height:190px;overflow:auto;padding:9px 10px;background:#1a242f;color:#d6e4f0;border-radius:6px;font:11px/1.55 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere; }
 .th-log-pre { margin:0;height:190px;overflow:auto;padding:9px 10px;background:#1a242f;color:#d6e4f0;border-radius:6px;font:11px/1.55 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere; }
-@media(max-width:1150px) { .th-two-col { grid-template-columns:1fr; }.th-cmd-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.th-bmc24-grid { grid-template-columns:repeat(4,minmax(0,1fr)); }.th-ct8-strip { grid-template-columns:repeat(4,minmax(0,1fr)); }.th-actuator-metrics { grid-template-columns:repeat(3,minmax(0,1fr)); } }
-@media(max-width:680px) { .th-bmc24-grid,.th-ct8-strip,.th-manual-grid,.th-actuator-metrics { grid-template-columns:repeat(2,minmax(0,1fr)); } }
+.th-station-matrix { display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px; }
+.th-station-card { background:#fff;border:1px solid var(--line);border-radius:10px;padding:12px 14px;cursor:pointer;display:flex;flex-direction:column;gap:6px;transition:border-color .15s,box-shadow .15s;min-width:0; }
+.th-station-card:hover { border-color:#8ec9c1;box-shadow:0 3px 10px rgba(13,139,128,.07); }
+.th-station-card.active { border-color:var(--primary);box-shadow:0 0 0 1px var(--primary);background:#fbfefe; }
+.th-station-card-top { display:flex;justify-content:space-between;align-items:center;gap:8px; }
+.th-station-card-name { font-weight:650;font-size:13px;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis; }
+.th-station-card-port { font:11px var(--mono);color:#5c7280;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; }
+.th-station-card-metrics { display:flex;justify-content:space-between;align-items:baseline;gap:8px;font:12px var(--mono);color:#234f5c;padding-top:4px;border-top:1px dashed #e5edf2; }
+.th-station-card-foot { display:flex;justify-content:space-between;align-items:center;gap:6px;font-size:11px;color:#6d808f; }
+.th-selected-badge { display:inline-flex;align-items:center;padding:6px 11px;border-radius:7px;background:#e9f6f3;border:1px solid #b8e0d9;color:#0a6d64;font-size:13px; }
+.th-local-status { padding:8px 12px;border-radius:8px;font-size:12.5px;background:#eef8f5;border:1px solid #bfe3da;color:#0d6a5f; }
+.th-local-status.error { background:#fff1f2;border-color:#f4c0c4;color:#b83740; }
+.th-export-bar { display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:8px 10px;background:#f3faf8;border:1px solid #cde7e1;border-radius:8px; }
+.th-safety-bar { display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:10px;padding-top:8px;border-top:1px dashed #d8e3ea;font-size:12px;color:#476270; }
+.th-safety-left { display:flex;flex-wrap:wrap;align-items:center;gap:10px; }
+.th-map-table-wrap { overflow:auto;border:1px solid var(--line);border-radius:8px;background:#fff; }
+.th-map-table th, .th-map-table td { padding:7px 8px;font-size:12px;vertical-align:middle; }
+.th-map-table input, .th-map-table select { padding:5px 7px;font-size:12px;width:100%; }
+.th-map-serial-cell { display:flex;flex-direction:column;gap:4px; }
+.th-map-tcp-row { display:flex;gap:4px; }
+.th-map-actions { display:flex;flex-wrap:wrap;align-items:center;gap:5px; }
+@media(max-width:1150px) { .th-station-matrix { grid-template-columns:repeat(2,minmax(0,1fr)); }.th-two-col { grid-template-columns:1fr; }.th-cmd-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }.th-bmc24-grid { grid-template-columns:repeat(4,minmax(0,1fr)); }.th-ct8-strip { grid-template-columns:repeat(4,minmax(0,1fr)); }.th-actuator-metrics { grid-template-columns:repeat(3,minmax(0,1fr)); } }
+@media(max-width:680px) { .th-station-matrix,.th-bmc24-grid,.th-ct8-strip,.th-manual-grid,.th-actuator-metrics { grid-template-columns:repeat(2,minmax(0,1fr)); } }

Diferenças do arquivo suprimidas por serem muito extensas
+ 1300 - 0
web/thermal-console.js