Sfoglia il codice sorgente

Release 0.9.1.0 (Phase 2): Full-detail frontend+backend local disk trace logging, SIMD state_diff, raw serial streaming, 2GiB disk guard & CLI replay

XJKJ STL 1 settimana fa
parent
commit
7a5be3b21d

+ 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.9.0.0
+ARG STL_VERSION=0.9.1.0
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
     STL_VERSION=${STL_VERSION}
     STL_VERSION=${STL_VERSION}
 
 

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.9.0.0
+0.9.1.0

+ 43 - 0
native/stl_accel/c_bridge.c

@@ -12,6 +12,7 @@
 
 
 #include <arpa/inet.h>
 #include <arpa/inet.h>
 #include <cpuid.h>
 #include <cpuid.h>
+#include <emmintrin.h>
 #include <errno.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <fcntl.h>
 #include <freeipmi/freeipmi.h>
 #include <freeipmi/freeipmi.h>
@@ -2276,3 +2277,45 @@ int stl_chmod_0600(const char *path) {
     if (!path || !path[0]) return -1;
     if (!path || !path[0]) return -1;
     return chmod(path, 0600);
     return chmod(path, 0600);
 }
 }
+
+uint64_t stl_mono_us(void) {
+    struct timespec ts;
+    if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0;
+    return (uint64_t)ts.tv_sec * 1000000ULL + (uint64_t)(ts.tv_nsec / 1000L);
+}
+
+/*
+ * Fast SIMD XOR 64-byte block diff (pure SSE2 baseline; extended to SSE4.2/AVX2/AVX-512 in Phase 3).
+ * Compares up to 4096 bytes (64 x 64B cache lines) and returns a u64 bitmask where bit i == 1
+ * indicates cache line i differs between `a` and `b`. Zero heap allocation; 0 means identical.
+ */
+uint64_t stl_mem_diff_64b_mask(const uint8_t *a, const uint8_t *b, size_t len) {
+    if (!a || !b || len == 0) return 0;
+    size_t blocks = (len + 63u) >> 6;
+    if (blocks > 64u) blocks = 64u;
+    uint64_t mask = 0;
+    for (size_t blk = 0; blk < blocks; blk++) {
+        size_t off = blk << 6;
+        size_t rem = len - off;
+        if (rem >= 64u) {
+            __m128i x0 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)(a + off + 0)),
+                                       _mm_loadu_si128((const __m128i *)(b + off + 0)));
+            __m128i x1 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)(a + off + 16)),
+                                       _mm_loadu_si128((const __m128i *)(b + off + 16)));
+            __m128i x2 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)(a + off + 32)),
+                                       _mm_loadu_si128((const __m128i *)(b + off + 32)));
+            __m128i x3 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)(a + off + 48)),
+                                       _mm_loadu_si128((const __m128i *)(b + off + 48)));
+            __m128i acc = _mm_or_si128(_mm_or_si128(x0, x1), _mm_or_si128(x2, x3));
+            __m128i eq0 = _mm_cmpeq_epi8(acc, _mm_setzero_si128());
+            if (_mm_movemask_epi8(eq0) != 0xFFFF) {
+                mask |= (1ULL << blk);
+            }
+        } else {
+            uint8_t diff = 0;
+            for (size_t i = 0; i < rem; i++) diff |= (uint8_t)(a[off + i] ^ b[off + i]);
+            if (diff != 0) mask |= (1ULL << blk);
+        }
+    }
+    return mask;
+}

+ 18 - 0
native/stl_accel/src/actors.rs

@@ -1103,8 +1103,10 @@ pub fn spawn_station_actor(
     pxe_tftp_dir: PathBuf,
     pxe_tftp_dir: PathBuf,
     dirty_set: Arc<DirtyStationSet>,
     dirty_set: Arc<DirtyStationSet>,
     push_hub: Arc<PushBroadcaster>,
     push_hub: Arc<PushBroadcaster>,
+    trace_hub: Arc<crate::trace::TraceHub>,
     enable_hw_bg_probes: bool,
     enable_hw_bg_probes: bool,
 ) -> StationHandle {
 ) -> StationHandle {
+    st.trace_hub = Some(Arc::clone(&trace_hub));
     if st.debug_log_path.is_none() {
     if st.debug_log_path.is_none() {
         let dbg_dir = data_dir.join("debug");
         let dbg_dir = data_dir.join("debug");
         let _ = std::fs::create_dir_all(&dbg_dir);
         let _ = std::fs::create_dir_all(&dbg_dir);
@@ -1113,6 +1115,7 @@ pub fn spawn_station_actor(
     if enable_hw_bg_probes && st.has_stale_station_state() {
     if enable_hw_bg_probes && st.has_stale_station_state() {
         st.reset_on_disconnect();
         st.reset_on_disconnect();
     }
     }
+    trace_hub.record_station_state(&st, "actor_init");
     let sid = st.station_id.clone();
     let sid = st.station_id.clone();
     let initial_view = build_published_view(&st);
     let initial_view = build_published_view(&st);
     let view = Arc::new(RwLock::new(initial_view));
     let view = Arc::new(RwLock::new(initial_view));
@@ -1823,6 +1826,7 @@ pub fn spawn_station_actor(
                             if let Ok(mut guard) = view_clone.write() {
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                                 *guard = build_published_view(&st);
                             }
                             }
+                            trace_hub.record_station_state(&st, &format!("cmd:{}", method));
                             dirty_set.mark(&st.station_id);
                             dirty_set.mark(&st.station_id);
                             if let Some(sig) = st.pending_complete_signal.take() {
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                                 push_hub.broadcast_task_complete(&sig);
@@ -2168,6 +2172,7 @@ pub fn spawn_station_actor(
                             if let Ok(mut guard) = view_clone.write() {
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                                 *guard = build_published_view(&st);
                             }
                             }
+                            trace_hub.record_station_state(&st, "test_inject_serial");
                             dirty_set.mark(&st.station_id);
                             dirty_set.mark(&st.station_id);
                             if let Some(sig) = st.pending_complete_signal.take() {
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                                 push_hub.broadcast_task_complete(&sig);
@@ -2198,6 +2203,7 @@ pub fn spawn_station_actor(
                             if let Ok(mut guard) = view_clone.write() {
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                                 *guard = build_published_view(&st);
                             }
                             }
+                            trace_hub.record_station_state(&st, "force_tick");
                             dirty_set.mark(&st.station_id);
                             dirty_set.mark(&st.station_id);
                             if let Some(sig) = st.pending_complete_signal.take() {
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                                 push_hub.broadcast_task_complete(&sig);
@@ -2233,6 +2239,7 @@ pub fn spawn_station_actor(
                             if let Ok(mut guard) = view_clone.write() {
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                                 *guard = build_published_view(&st);
                             }
                             }
+                            trace_hub.record_station_state(&st, "mt_report_uploaded");
                             dirty_set.mark(&st.station_id);
                             dirty_set.mark(&st.station_id);
                             if let Some(sig) = st.pending_complete_signal.take() {
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                                 push_hub.broadcast_task_complete(&sig);
@@ -2260,6 +2267,7 @@ pub fn spawn_station_actor(
                             if let Ok(mut guard) = view_clone.write() {
                             if let Ok(mut guard) = view_clone.write() {
                                 *guard = build_published_view(&st);
                                 *guard = build_published_view(&st);
                             }
                             }
+                            trace_hub.record_station_state(&st, "mt_report_sync_done");
                             dirty_set.mark(&st.station_id);
                             dirty_set.mark(&st.station_id);
                             if let Some(sig) = st.pending_complete_signal.take() {
                             if let Some(sig) = st.pending_complete_signal.take() {
                                 push_hub.broadcast_task_complete(&sig);
                                 push_hub.broadcast_task_complete(&sig);
@@ -2452,6 +2460,12 @@ pub fn spawn_station_actor(
                             &st.boot_id,
                             &st.boot_id,
                         );
                         );
                     }
                     }
+                    trace_hub.record_hardware_event(
+                        &st.station_id,
+                        "thermal_mcu",
+                        "auto_heat_0x01",
+                        &format!("boot_id={} target_c={}", st.boot_id, st.thermal_target_c),
+                    );
                     state_dirty = true;
                     state_dirty = true;
                 }
                 }
 
 
@@ -2498,6 +2512,10 @@ pub fn spawn_station_actor(
                     if let Ok(mut guard) = view_clone.write() {
                     if let Ok(mut guard) = view_clone.write() {
                         *guard = build_published_view(&st);
                         *guard = build_published_view(&st);
                     }
                     }
+                    trace_hub.record_station_state(
+                        &st,
+                        if rx_bytes_arrived { "serial_rx" } else { "actor_tick" },
+                    );
                     dirty_set.mark(&st.station_id);
                     dirty_set.mark(&st.station_id);
                 }
                 }
                 if let Some(sig) = st.pending_complete_signal.take() {
                 if let Some(sig) = st.pending_complete_signal.take() {

+ 196 - 0
native/stl_accel/src/api.rs

@@ -63,6 +63,7 @@ pub struct AppHub {
     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 thermal_hub: Arc<crate::thermal_mcu::ThermalMcuHub>,
+    pub trace_hub: Arc<crate::trace::TraceHub>,
     pub web_password: RwLock<Option<String>>,
     pub web_password: RwLock<Option<String>>,
     pub web_sessions: Mutex<HashMap<String, i64>>,
     pub web_sessions: Mutex<HashMap<String, i64>>,
 }
 }
@@ -222,6 +223,11 @@ impl AppHub {
         let server_id = format!("stl-{}", started_ms);
         let server_id = format!("stl-{}", started_ms);
         let dirty_set = Arc::new(DirtyStationSet::new());
         let dirty_set = Arc::new(DirtyStationSet::new());
         let push_hub = Arc::new(PushBroadcaster::new());
         let push_hub = Arc::new(PushBroadcaster::new());
+        let trace_hub = crate::trace::TraceHub::init(
+            &args.data_dir,
+            args.detail_log_cli,
+            Arc::clone(&push_hub),
+        );
 
 
         let mut stations_map = BTreeMap::new();
         let mut stations_map = BTreeMap::new();
         for (idx, (sid, st)) in raw_stations.into_iter().enumerate() {
         for (idx, (sid, st)) in raw_stations.into_iter().enumerate() {
@@ -233,6 +239,7 @@ impl AppHub {
                 pxe_tftp_dir.clone(),
                 pxe_tftp_dir.clone(),
                 Arc::clone(&dirty_set),
                 Arc::clone(&dirty_set),
                 Arc::clone(&push_hub),
                 Arc::clone(&push_hub),
+                Arc::clone(&trace_hub),
                 enable_hw_bg_probes,
                 enable_hw_bg_probes,
             );
             );
             stations_map.insert(sid, handle);
             stations_map.insert(sid, handle);
@@ -278,6 +285,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,
             thermal_hub,
+            trace_hub,
             web_password: RwLock::new(effective_web_password),
             web_password: RwLock::new(effective_web_password),
             web_sessions: Mutex::new(HashMap::new()),
             web_sessions: Mutex::new(HashMap::new()),
         });
         });
@@ -470,6 +478,7 @@ impl AppHub {
             self.pxe_tftp_dir.clone(),
             self.pxe_tftp_dir.clone(),
             Arc::clone(&self.dirty_set),
             Arc::clone(&self.dirty_set),
             Arc::clone(&self.push_hub),
             Arc::clone(&self.push_hub),
+            Arc::clone(&self.trace_hub),
             self.enable_hw_bg_probes,
             self.enable_hw_bg_probes,
         );
         );
         self.thermal_hub.add_station(clean_sid.clone(), handle.clone());
         self.thermal_hub.add_station(clean_sid.clone(), handle.clone());
@@ -1097,7 +1106,9 @@ impl AppHub {
         method: &str,
         method: &str,
         params: &JsonVal,
         params: &JsonVal,
     ) -> Result<JsonVal, (String, String)> {
     ) -> Result<JsonVal, (String, String)> {
+        let t0_us = unsafe { lib::stl_mono_us() };
         let res = self.dispatch_rpc_inner(method, params);
         let res = self.dispatch_rpc_inner(method, params);
+        let dur_us = unsafe { lib::stl_mono_us() }.saturating_sub(t0_us);
         let is_polling = matches!(
         let is_polling = matches!(
             method,
             method,
             "GetSystemInfo"
             "GetSystemInfo"
@@ -1111,6 +1122,8 @@ impl AppHub {
                 | "GetTaskStatus"
                 | "GetTaskStatus"
                 | "GetStationErrors"
                 | "GetStationErrors"
                 | "GetDimmCurve"
                 | "GetDimmCurve"
+                | "GetTraceConfig"
+                | "GetTraceStatus"
                 | "GetQueue"
                 | "GetQueue"
                 | "GetQueueItem"
                 | "GetQueueItem"
                 | "GetThermalConsole"
                 | "GetThermalConsole"
@@ -1121,6 +1134,15 @@ impl AppHub {
         );
         );
         if !is_polling || res.is_err() {
         if !is_polling || res.is_err() {
             let sid = params.get_str_or("station_id", "");
             let sid = params.get_str_or("station_id", "");
+            let err_str = res.as_ref().err().map(|(c, m)| format!("{}:{}", c, m));
+            self.trace_hub.record_rpc_event(
+                method,
+                &sid,
+                params,
+                res.is_ok(),
+                dur_us,
+                err_str.as_deref(),
+            );
             let sub = if method == "EnqueueCommand" {
             let sub = if method == "EnqueueCommand" {
                 params.get_str_or("method", "")
                 params.get_str_or("method", "")
             } else {
             } else {
@@ -1259,6 +1281,25 @@ impl AppHub {
                     .get_dimm_curve(&sid, slot)
                     .get_dimm_curve(&sid, slot)
                     .map_err(|e| ("INVALID_ARGUMENT".to_string(), e))
                     .map_err(|e| ("INVALID_ARGUMENT".to_string(), e))
             }
             }
+            "GetTraceConfig" => Ok(self.trace_hub.get_config().to_json()),
+            "GetTraceStatus" => Ok(self.trace_hub.get_status_json()),
+            "ConfigureDetailLog" => {
+                let updated = self.trace_hub.update_config(params);
+                self.commit_audit(
+                    "SYS",
+                    "web",
+                    AuditRecordDraft {
+                        category: "trace".to_string(),
+                        action: "configure_detail_log".to_string(),
+                        summary: format!(
+                            "更新全细节日志配置: enabled={} volume={}MiB retention={}d min_free={}GiB",
+                            updated.enabled, updated.volume_mb, updated.retention_days, updated.min_free_gb
+                        ),
+                        details: updated.to_json(),
+                    },
+                );
+                Ok(self.trace_hub.get_status_json())
+            }
             "GetFirmwareCatalog" => Ok(self.contract.raw_catalog.clone()),
             "GetFirmwareCatalog" => Ok(self.contract.raw_catalog.clone()),
             "GetDiagnostic" => {
             "GetDiagnostic" => {
                 let sid = params.get_str_or("station_id", "S1");
                 let sid = params.get_str_or("station_id", "S1");
@@ -2453,12 +2494,167 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
         return;
         return;
     }
     }
 
 
+    // ---- Phase 2: Full-Detail Local Trace HTTP Endpoints (Authenticated) ----
+    if path_only == "/api/trace/frontend" && method == "POST" {
+        if content_length > 2 * 1024 * 1024 {
+            let body = r#"{"ok":false,"error":{"code":"PAYLOAD_TOO_LARGE","message":"单批前端日志超过 2 MiB 上限"}}"#;
+            let resp = format!(
+                "HTTP/1.1 413 Payload Too Large\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
+                body.len(),
+                body
+            );
+            let _ = stream.write_all(resp.as_bytes());
+            let _ = stream.flush();
+            return;
+        }
+        let body_start = hdr_end + 4;
+        let mut body_bytes = buf[body_start..n_read].to_vec();
+        if body_bytes.len() > content_length {
+            body_bytes.truncate(content_length);
+        }
+        while body_bytes.len() < content_length {
+            let mut chunk = [0u8; 8192];
+            let need = (content_length - body_bytes.len()).min(chunk.len());
+            match stream.read(&mut chunk[..need]) {
+                Ok(0) => break,
+                Ok(n) => body_bytes.extend_from_slice(&chunk[..n]),
+                Err(_) => break,
+            }
+        }
+        let peer_ip = stream
+            .peer_addr()
+            .map(|a| a.ip().to_string())
+            .unwrap_or_else(|_| "unknown".to_string());
+        let body_str = String::from_utf8_lossy(&body_bytes);
+        let events = match parse_json(&body_str) {
+            Ok(JsonVal::Arr(arr)) => arr,
+            Ok(obj) => obj.get_arr("events").cloned().unwrap_or_default(),
+            Err(_) => Vec::new(),
+        };
+        // Anti-recursion: NEVER call hub.trace_hub.record_http_event for `/api/trace/frontend`!
+        let accepted = hub.trace_hub.ingest_frontend_events(events, &peer_ip);
+        let mut out = JsonVal::obj();
+        out.set("ok", JsonVal::Bool(true));
+        out.set("accepted", JsonVal::Num(accepted as f64));
+        out.set("enabled", JsonVal::Bool(hub.trace_hub.get_config().enabled));
+        out.set("disk_low_paused", JsonVal::Bool(!hub.trace_hub.is_active() && hub.trace_hub.get_config().enabled));
+        let ok_body = out.to_json();
+        let resp = format!(
+            "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
+            ok_body.len(),
+            ok_body
+        );
+        let _ = stream.write_all(resp.as_bytes());
+        let _ = stream.flush();
+        return;
+    }
+
+    if path_only == "/api/trace/config" && method == "POST" {
+        if content_length > 16384 {
+            let body = r#"{"ok":false,"error":{"code":"INVALID_ARGUMENT","message":"配置请求体过大"}}"#;
+            let resp = format!(
+                "HTTP/1.1 413 Payload Too Large\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
+                body.len(),
+                body
+            );
+            let _ = stream.write_all(resp.as_bytes());
+            let _ = stream.flush();
+            return;
+        }
+        let body_start = hdr_end + 4;
+        let mut body_bytes = buf[body_start..n_read].to_vec();
+        if body_bytes.len() > content_length {
+            body_bytes.truncate(content_length);
+        }
+        while body_bytes.len() < content_length {
+            let mut chunk = [0u8; 2048];
+            let need = (content_length - body_bytes.len()).min(chunk.len());
+            match stream.read(&mut chunk[..need]) {
+                Ok(0) => break,
+                Ok(n) => body_bytes.extend_from_slice(&chunk[..n]),
+                Err(_) => break,
+            }
+        }
+        let patch = parse_json(&String::from_utf8_lossy(&body_bytes)).unwrap_or_else(|_| JsonVal::obj());
+        let _ = hub.trace_hub.update_config(&patch);
+        let ok_body = hub.trace_hub.get_status_json().to_json();
+        let resp = format!(
+            "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
+            ok_body.len(),
+            ok_body
+        );
+        let _ = stream.write_all(resp.as_bytes());
+        let _ = stream.flush();
+        return;
+    }
+
     if method != "GET" && method != "HEAD" {
     if method != "GET" && method != "HEAD" {
         let resp = "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 18\r\nConnection: close\r\n\r\nMethod Not Allowed";
         let resp = "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 18\r\nConnection: close\r\n\r\nMethod Not Allowed";
         let _ = stream.write_all(resp.as_bytes());
         let _ = stream.write_all(resp.as_bytes());
         return;
         return;
     }
     }
 
 
+    if path_only == "/api/trace/config" {
+        let body = hub.trace_hub.get_config().to_json().to_json().into_bytes();
+        let hdr = format!(
+            "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\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 path_only == "/api/trace/status" {
+        let body = hub.trace_hub.get_status_json().to_json().into_bytes();
+        let hdr = format!(
+            "HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {}\r\nCache-Control: no-store\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 path_only == "/api/trace/bundle" {
+        let sid = parse_query_param(raw_target, "station_id");
+        let day = parse_query_param(raw_target, "day");
+        match hub.trace_hub.build_diagnostic_bundle_tar(&sid, &day) {
+            Ok((fname, bytes)) => {
+                let hdr = format!(
+                    "HTTP/1.1 200 OK\r\nContent-Type: application/x-tar\r\nContent-Length: {}\r\nContent-Disposition: attachment; filename=\"{}\"\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
+                    bytes.len(),
+                    fname
+                );
+                let _ = stream.write_all(hdr.as_bytes());
+                if method == "GET" {
+                    let _ = stream.write_all(&bytes);
+                }
+                let _ = stream.flush();
+                return;
+            }
+            Err(msg) => {
+                let body = msg.into_bytes();
+                let hdr = format!(
+                    "HTTP/1.1 500 Internal Server Error\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(rest) = path_only.strip_prefix("/api/stations/") {
     if let Some(rest) = path_only.strip_prefix("/api/stations/") {
         if let Some(sid_raw) = rest.strip_suffix("/alarms.xlsx") {
         if let Some(sid_raw) = rest.strip_suffix("/alarms.xlsx") {
             let sid: String = sid_raw
             let sid: String = sid_raw

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

@@ -361,6 +361,8 @@ extern "C" {
         summary_out: *mut f32,
         summary_out: *mut f32,
         used_gpu: *mut i32,
         used_gpu: *mut i32,
     ) -> i32;
     ) -> i32;
+    pub fn stl_mono_us() -> u64;
+    pub fn stl_mem_diff_64b_mask(a: *const u8, b: *const u8, len: usize) -> u64;
 }
 }
 
 
 /// Safe RAII wrapper around the monotonic 64-bit mmap ring buffer (Hugepage + 64B tail pad + PROT_NONE guard).
 /// Safe RAII wrapper around the monotonic 64-bit mmap ring buffer (Hugepage + 64B tail pad + PROT_NONE guard).

+ 132 - 0
native/stl_accel/src/main.rs

@@ -15,18 +15,55 @@ mod pxe;
 mod results;
 mod results;
 mod storage;
 mod storage;
 mod thermal_mcu;
 mod thermal_mcu;
+mod trace;
 mod workflow;
 mod workflow;
 mod xlsx;
 mod xlsx;
 
 
 use api::{handle_http_client, AppHub};
 use api::{handle_http_client, AppHub};
 use config::ServerArgs;
 use config::ServerArgs;
 use std::net::TcpListener;
 use std::net::TcpListener;
+use std::path::PathBuf;
 use std::process;
 use std::process;
 use std::sync::Arc;
 use std::sync::Arc;
 use std::thread;
 use std::thread;
 
 
 fn main() {
 fn main() {
     lib::init_hardware();
     lib::init_hardware();
+    // Offline CLI Trace State Reconstructor: `--replay-trace <dir> [--station S1] [--at-ms <unix_ms>]`
+    let raw_args: Vec<String> = std::env::args().collect();
+    if let Some(pos) = raw_args.iter().position(|a| a == "--replay-trace") {
+        let dir = raw_args
+            .get(pos + 1)
+            .map(PathBuf::from)
+            .unwrap_or_else(|| PathBuf::from("data/trace"));
+        let mut station: Option<String> = None;
+        let mut at_ms: i64 = i64::MAX;
+        let mut idx = 1;
+        while idx < raw_args.len() {
+            match raw_args[idx].as_str() {
+                "--station" if idx + 1 < raw_args.len() => {
+                    station = Some(raw_args[idx + 1].clone());
+                    idx += 2;
+                }
+                "--at-ms" if idx + 1 < raw_args.len() => {
+                    at_ms = raw_args[idx + 1].parse::<i64>().unwrap_or(i64::MAX);
+                    idx += 2;
+                }
+                _ => idx += 1,
+            }
+        }
+        match trace::replay_trace_dir(&dir, station.as_deref(), at_ms) {
+            Ok(json) => {
+                println!("{}", json.to_json());
+                process::exit(0);
+            }
+            Err(e) => {
+                eprintln!("[stl_native_server] --replay-trace error: {}", e);
+                process::exit(1);
+            }
+        }
+    }
+
     let args = match ServerArgs::parse() {
     let args = match ServerArgs::parse() {
         Ok(a) => a,
         Ok(a) => a,
         Err(msg) => {
         Err(msg) => {
@@ -4801,4 +4838,99 @@ FS0:\\EFI\\> \r\n",
 
 
         let _ = std::fs::remove_dir_all(&tmp_dir);
         let _ = std::fs::remove_dir_all(&tmp_dir);
     }
     }
+
+    #[test]
+    fn test_phase2_full_detail_trace_simd_diff_replay_disk_guard_and_frontend() {
+        let tmp_dir = std::env::temp_dir().join(format!("stl_phase2_trace_{}", now_ms()));
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+        let args = ServerArgs {
+            config_path: std::path::PathBuf::from("config/backend.example.json"),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: std::path::PathBuf::from("web"),
+            contracts_path: std::path::PathBuf::from("contracts/firmware-vd012.json"),
+            web_password: None,
+            raw_ring_mb: 2,
+            clean_ring_mb: 2,
+            detail_log_cli: Some(true),
+            version: "0.9.1.0".to_string(),
+            commit: "phase2-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+        assert!(hub.trace_hub.is_active(), "Trace must be enabled by default");
+        let cfg = hub.trace_hub.get_config();
+        assert_eq!(cfg.volume_mb, 50);
+        assert_eq!(cfg.retention_days, 30);
+        assert_eq!(cfg.min_free_gb, 2);
+
+        // 1. Inject serial transitions on S1 -> must stream raw bytes AND emit state_snapshot + state_diff
+        let raw_chunk = b"[HS_BIOS]Version:108_VD012\r\n[0][Hovsee]Current stage is 1\r\n[0][Hovsee]Please input your command:\r\n";
+        hub.test_inject_serial("S1", raw_chunk, Some("running"), true);
+        let mid_ts = now_ms();
+        std::thread::sleep(Duration::from_millis(20));
+        let raw_chunk2 = b"[0][Hovsee]Exit ICT ddr test and go on training\r\n[HS_BIOS][Training][ScktId: 0][124]DDR Training -- SUCCEEDED,Time=900 ms\r\n[HS_EndMemTrain]\r\n";
+        hub.test_inject_serial("S1", raw_chunk2, Some("running"), true);
+        let end_ts = now_ms() + 10;
+
+        // 2. Frontend trace ingestion with secret redaction
+        let fe_ev = parse_json(r##"{"kind":"ui_action","target":"#btn-save","password":"super-secret-123","nested":{"bmc_password":"abc"}}"##).unwrap();
+        let accepted = hub.trace_hub.ingest_frontend_events(vec![fe_ev], "127.0.0.1");
+        assert_eq!(accepted, 1);
+
+        // 3. RPC logging with secret redaction
+        let mut p = JsonVal::obj();
+        p.set("station_id", JsonVal::Str("S1".to_string()));
+        p.set("password", JsonVal::Str("secret-rpc-pw".to_string()));
+        let _ = hub.dispatch_rpc("ConfigureDetailLog", &parse_json(r#"{"volume_mb":50}"#).unwrap());
+        hub.trace_hub.flush();
+
+        // Verify files written on disk
+        let today = hub.trace_hub.get_status_json().get_str_or("today", "");
+        let day_dir = tmp_dir.join("trace").join(&today);
+        let raw_bin_path = day_dir.join("station-S1.raw.0001.bin");
+        let raw_bytes = std::fs::read(&raw_bin_path).expect("station-S1.raw.0001.bin must exist");
+        assert!(raw_bytes.windows(raw_chunk.len()).any(|w| w == raw_chunk), "Raw serial stream missing chunk 1");
+        assert!(raw_bytes.windows(raw_chunk2.len()).any(|w| w == raw_chunk2), "Raw serial stream missing chunk 2");
+
+        let fe_txt = std::fs::read_to_string(day_dir.join("frontend.0001.jsonl")).expect("frontend.0001.jsonl must exist");
+        assert!(fe_txt.contains("[REDACTED]"), "Frontend trace must redact passwords");
+        assert!(!fe_txt.contains("super-secret-123"), "Raw password leaked in frontend trace!");
+
+        // 4. Offline CLI state reconstructor (`replay_trace_dir`) reconstructs exact state at `mid_ts` vs `end_ts`
+        let rep_mid = crate::trace::replay_trace_dir(&tmp_dir.join("trace"), Some("S1"), mid_ts).unwrap();
+        let rep_end = crate::trace::replay_trace_dir(&tmp_dir.join("trace"), Some("S1"), end_ts).unwrap();
+        let s1_mid = rep_mid.get("stations").unwrap().get("S1").unwrap().get("state").unwrap();
+        let s1_end = rep_end.get("stations").unwrap().get("S1").unwrap().get("state").unwrap();
+        assert_eq!(s1_mid.get_str_or("phase", ""), "uip", "Replayed mid_ts must be uip: {}", s1_mid.to_json());
+        assert_eq!(s1_end.get_str_or("phase", ""), "training", "Replayed end_ts must be training: {}", s1_end.to_json());
+
+        // 5. Diagnostic .tar bundle contains config, status, backend, frontend, and S1 raw serial
+        let (tar_name, tar_bytes) = hub.trace_hub.build_diagnostic_bundle_tar("S1", &today).unwrap();
+        assert!(tar_name.ends_with(".tar"));
+        let tar_str = String::from_utf8_lossy(&tar_bytes);
+        assert!(tar_str.contains("trace/config.json"));
+        assert!(tar_str.contains("backend.0001.jsonl"));
+        assert!(tar_str.contains("frontend.0001.jsonl"));
+        assert!(tar_str.contains("station-S1.raw.0001.bin"));
+
+        // 6. < 2 GiB free-disk guard automatically pauses writing and resumes above 2 GiB + 256 MiB
+        hub.trace_hub.set_test_fake_free_bytes(1024 * 1024 * 1024); // 1 GiB < 2 GiB
+        assert!(!hub.trace_hub.is_active(), "Trace must auto-pause when free disk < 2 GiB");
+        assert_eq!(hub.trace_hub.get_status_json().get_bool("disk_low_paused"), Some(true));
+        let before_ev = hub.trace_hub.get_status_json().get_i64("written_events").unwrap_or(0);
+        hub.trace_hub.ingest_frontend_events(vec![parse_json(r#"{"kind":"ignored"}"#).unwrap()], "127.0.0.1");
+        hub.trace_hub.flush();
+        assert_eq!(hub.trace_hub.get_status_json().get_i64("written_events").unwrap_or(0), before_ev);
+
+        hub.trace_hub.set_test_fake_free_bytes(3 * 1024 * 1024 * 1024); // 3 GiB > 2.25 GiB
+        assert!(hub.trace_hub.is_active(), "Trace must auto-resume when free disk recovers");
+
+        // 7. Dynamic toggle OFF stops writes immediately without restart
+        let _ = hub.dispatch_rpc("ConfigureDetailLog", &parse_json(r#"{"enabled":false}"#).unwrap());
+        assert!(!hub.trace_hub.is_active());
+        assert_eq!(hub.trace_hub.ingest_frontend_events(vec![parse_json(r#"{"kind":"off_test"}"#).unwrap()], "127.0.0.1"), 0);
+
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+    }
 }
 }

+ 24 - 0
native/stl_accel/src/pxe.rs

@@ -1768,6 +1768,12 @@ fn handle_tftp_rrq(
             data.len()
             data.len()
         ),
         ),
     );
     );
+    hub.trace_hub.record_hardware_event(
+        "PXE",
+        "tftp",
+        "rrq_begin",
+        &format!("peer={} file={} bytes={}", peer, filename, data.len()),
+    );
     let (blksize, timeout_secs, oack_pairs) = negotiate_tftp_options(&opts, Some(data.len()));
     let (blksize, timeout_secs, oack_pairs) = negotiate_tftp_options(&opts, Some(data.len()));
     let _ = sock.set_read_timeout(Some(Duration::from_secs(timeout_secs)));
     let _ = sock.set_read_timeout(Some(Duration::from_secs(timeout_secs)));
 
 
@@ -2125,6 +2131,24 @@ fn handle_tftp_wrq(
             force_targets.join(",")
             force_targets.join(",")
         ),
         ),
     );
     );
+    hub.trace_hub.record_hardware_event(
+        if force_targets.len() == 1 {
+            &force_targets[0]
+        } else {
+            "PXE"
+        },
+        "tftp",
+        "wrq_report",
+        &format!(
+            "peer={} mac={} file={} bytes={} verdict={} targets={}",
+            peer,
+            peer_mac,
+            clean_name,
+            total_bytes,
+            report.get_str_or("verdict", ""),
+            force_targets.join(",")
+        ),
+    );
 
 
     for sid in force_targets {
     for sid in force_targets {
         append_debug_log_path(
         append_debug_log_path(

+ 5 - 0
native/stl_accel/src/results.rs

@@ -688,6 +688,7 @@ pub struct StationState {
     pub dimm_seen_in_boot: [bool; 24],
     pub dimm_seen_in_boot: [bool; 24],
     pub had_bmc_sdr: [bool; 24],
     pub had_bmc_sdr: [bool; 24],
     pub sdr_absent_streak: [u8; 24],
     pub sdr_absent_streak: [u8; 24],
+    pub trace_hub: Option<std::sync::Arc<crate::trace::TraceHub>>,
 }
 }
 
 
 impl StationState {
 impl StationState {
@@ -920,6 +921,7 @@ impl StationState {
             dimm_seen_in_boot: [false; 24],
             dimm_seen_in_boot: [false; 24],
             had_bmc_sdr: [false; 24],
             had_bmc_sdr: [false; 24],
             sdr_absent_streak: [0; 24],
             sdr_absent_streak: [0; 24],
+            trace_hub: None,
         }
         }
     }
     }
 
 
@@ -2532,6 +2534,9 @@ impl StationState {
             self.hot.last_clear_screen_offset = cs;
             self.hot.last_clear_screen_offset = cs;
         }
         }
         self.raw_ring.append(slice);
         self.raw_ring.append(slice);
+        if let Some(ref th) = self.trace_hub {
+            th.record_raw_serial(&self.station_id, slice);
+        }
 
 
         let mut parsed_lines: Vec<(Vec<u8>, u32)> = Vec::new();
         let mut parsed_lines: Vec<(Vec<u8>, u32)> = Vec::new();
         let clean_ring_ref = &mut self.clean_ring;
         let clean_ring_ref = &mut self.clean_ring;

File diff suppressed because it is too large
+ 1410 - 0
native/stl_accel/src/trace.rs


+ 6 - 4
native/stl_accel/stl_accel.h

@@ -305,10 +305,12 @@ int    stl_batch_rmt_eye_reduce(
     float       *summary_out,  /* [station_count * 4] (min_timing, min_vref, mean_timing, mean_vref) */
     float       *summary_out,  /* [station_count * 4] (min_timing, min_vref, mean_timing, mean_vref) */
     int         *used_gpu);
     int         *used_gpu);
 
 
-/* Filesystem free-space guard, idle priority & permission helpers */
-int    stl_free_disk_bytes(const char *path, uint64_t *out_avail_bytes);
-void   stl_set_thread_idle_priority(void);
-int    stl_chmod_0600(const char *path);
+/* Filesystem free-space guard, idle priority, monotonic clock, SIMD diff & permission helpers */
+int      stl_free_disk_bytes(const char *path, uint64_t *out_avail_bytes);
+void     stl_set_thread_idle_priority(void);
+int      stl_chmod_0600(const char *path);
+uint64_t stl_mono_us(void);
+uint64_t stl_mem_diff_64b_mask(const uint8_t *a, const uint8_t *b, size_t len);
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }

+ 62 - 1
sim/web_e2e/test_tier4_chrome_web_e2e.py

@@ -413,12 +413,73 @@ async def run_tier4_web_suite() -> Dict[str, Any]:
                 assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 5: {cdp.js_exceptions}"
                 assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 5: {cdp.js_exceptions}"
                 results.append({"scenario": "5_production_view_dimm_curve_and_xlsx", "status": "PASS", "xlsx_size": xlsx_ok.get("size")})
                 results.append({"scenario": "5_production_view_dimm_curve_and_xlsx", "status": "PASS", "xlsx_size": xlsx_ok.get("size")})
                 print(f"      -> PASS (alarms.xlsx={xlsx_ok.get('size')} bytes)", flush=True)
                 print(f"      -> PASS (alarms.xlsx={xlsx_ok.get('size')} bytes)", flush=True)
+
+                # ============================================================
+                # Scenario 6: Phase 2 Full-Detail Frontend + Backend Trace, Dynamic Toggle & .tar Bundle
+                # ============================================================
+                print("[Tier4][6/6] Verifying Phase 2 full-detail frontend+backend trace ingestion, toggle OFF & .tar bundle...", flush=True)
+                await cdp.eval_js("window.stlTrace && window.stlTrace.flush(false)")
+                trace_st = await wait_until(
+                    lambda: cdp.eval_js(
+                        """(async () => {
+                            const r = await fetch('/api/trace/status', { credentials: 'same-origin' });
+                            if (!r.ok) return null;
+                            const d = await r.json();
+                            return (d.frontend_events_ingested > 0 && d.written_events > 0) ? d : null;
+                        })()"""
+                    ),
+                    timeout_s=10.0,
+                    desc="Frontend trace events ingested on disk",
+                )
+                # Verify .tar diagnostic bundle download
+                tar_ok = await cdp.eval_js(
+                    """(async () => {
+                        const r = await fetch('/api/trace/bundle?station_id=S1', { credentials: 'same-origin' });
+                        if (!r.ok) return { ok: false, status: r.status };
+                        const txt = await r.text();
+                        return { ok: txt.includes('trace/config.json') && txt.includes('frontend.0001.jsonl') && txt.includes('backend.0001.jsonl'), size: txt.length };
+                    })()"""
+                )
+                assert tar_ok and tar_ok.get("ok") is True, f"Diagnostic .tar bundle invalid: {tar_ok}"
+                # Toggle trace OFF dynamically via UI/HTTP and verify WS broadcast syncs browser trace.js immediately
+                await cdp.eval_js(
+                    """(async () => {
+                        await fetch('/api/trace/config', {
+                            method: 'POST',
+                            credentials: 'same-origin',
+                            headers: { 'Content-Type': 'application/json' },
+                            body: JSON.stringify({ enabled: false }),
+                        });
+                        return true;
+                    })()"""
+                )
+                toggled_off = await wait_until(
+                    lambda: cdp.eval_js("window.stlTrace && window.stlTrace.isActive() === false"),
+                    timeout_s=6.0,
+                    desc="Browser stlTrace dynamically disabled via WS broadcast",
+                )
+                assert toggled_off is True
+                # Re-enable so default state remains intact
+                await cdp.eval_js(
+                    """(async () => {
+                        await fetch('/api/trace/config', {
+                            method: 'POST',
+                            credentials: 'same-origin',
+                            headers: { 'Content-Type': 'application/json' },
+                            body: JSON.stringify({ enabled: true }),
+                        });
+                        return true;
+                    })()"""
+                )
+                assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 6: {cdp.js_exceptions}"
+                results.append({"scenario": "6_full_detail_trace_frontend_backend_and_toggle", "status": "PASS", "fe_events": trace_st.get("frontend_events_ingested"), "tar_size": tar_ok.get("size")})
+                print(f"      -> PASS (fe_events={trace_st.get('frontend_events_ingested')}, tar={tar_ok.get('size')}B)", flush=True)
             finally:
             finally:
                 await cdp.close()
                 await cdp.close()
 
 
         elapsed_s = round(time.monotonic() - t0, 2)
         elapsed_s = round(time.monotonic() - t0, 2)
         summary = {"tier": "Tier4_Headless_Chrome156_Web_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
         summary = {"tier": "Tier4_Headless_Chrome156_Web_E2E", "ok": True, "elapsed_s": elapsed_s, "results": results}
-        print(f"\n[Tier4] ALL 5 HEADLESS CHROME 156 WEB E2E SCENARIOS PASSED in {elapsed_s}s!", flush=True)
+        print(f"\n[Tier4] ALL 6 HEADLESS CHROME 156 WEB E2E SCENARIOS PASSED in {elapsed_s}s!", flush=True)
         return summary
         return summary
     finally:
     finally:
         if chrome_proc and chrome_proc.poll() is None:
         if chrome_proc and chrome_proc.poll() is None:

File diff suppressed because it is too large
+ 44 - 11
web/index.html


+ 645 - 0
web/trace.js

@@ -0,0 +1,645 @@
+// trace.js — Phase 2 Full-Detail Frontend Trace Recorder & Offline IndexedDB Spool
+// Loaded FIRST before all other scripts. Enabled by default; dynamically synced with backend config.
+(() => {
+  const nativeFetch = window.fetch ? window.fetch.bind(window) : null;
+  const nativeSendBeacon = navigator.sendBeacon ? navigator.sendBeacon.bind(navigator) : null;
+  const nativeConsoleError = console.error ? console.error.bind(console) : () => {};
+  const nativeConsoleWarn = console.warn ? console.warn.bind(console) : () => {};
+
+  const SESSION_ID = `fe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
+  const FLUSH_INTERVAL_MS = 2000;
+  const FLUSH_MAX_EVENTS = 50;
+  const FLUSH_MAX_BYTES = 65536;
+  const DB_NAME = 'xjkj_stl_trace_spool';
+  const DB_STORE = 'batches';
+
+  let config = {
+    enabled: true,
+    backend_state_diff: true,
+    backend_rpc_http: true,
+    backend_serial_stream: true,
+    backend_hardware_io: true,
+    frontend_trace: true,
+    compress_rotated: true,
+    volume_mb: 50,
+    retention_days: 30,
+    min_free_gb: 2,
+  };
+  let diskLowPaused = false;
+  let seq = 0;
+  let buffer = [];
+  let bufferBytes = 0;
+  let flushTimer = null;
+  let flushing = false;
+  let idbPromise = null;
+  let spooledCount = 0;
+  let recentRing = [];
+  const RECENT_RING_MAX = 500;
+
+  const SECRET_KEY_RE = /^(password|passwd|secret|token|api_token|authorization|cookie|current_password|new_password|bmc_password)$/i;
+  const SECRET_ELEM_RE = /(password|passwd|secret|token|pw-)/i;
+
+  function isActive() {
+    return !!config.enabled && !!config.frontend_trace && !diskLowPaused;
+  }
+
+  function sanitize(value, depth = 0) {
+    if (depth > 5) return '[DEPTH_LIMIT]';
+    if (value === null || value === undefined) return value;
+    if (typeof value === 'string') {
+      return value.length > 512 ? value.slice(0, 512) + `...[+${value.length - 512}B]` : value;
+    }
+    if (typeof value === 'number' || typeof value === 'boolean') return value;
+    if (Array.isArray(value)) {
+      if (value.length > 32) {
+        return { _type: 'array', length: value.length, sample: value.slice(0, 6).map(v => sanitize(v, depth + 1)) };
+      }
+      return value.map(v => sanitize(v, depth + 1));
+    }
+    if (typeof value === 'object') {
+      const out = {};
+      const entries = Object.entries(value);
+      for (let i = 0; i < Math.min(entries.length, 40); i++) {
+        const [k, v] = entries[i];
+        out[k] = SECRET_KEY_RE.test(k) ? '[REDACTED]' : sanitize(v, depth + 1);
+      }
+      if (entries.length > 40) out._truncated_keys = entries.length - 40;
+      return out;
+    }
+    return String(value);
+  }
+
+  function elementDescriptor(el) {
+    if (!el || el.nodeType !== 1) return '';
+    const tag = (el.tagName || '').toLowerCase();
+    const id = el.id ? `#${el.id}` : '';
+    const name = el.getAttribute?.('name') ? `[name=${el.getAttribute('name')}]` : '';
+    const dataPage = el.dataset?.page ? `[data-page=${el.dataset.page}]` : '';
+    const dataAct = el.dataset?.prodAction ? `[data-prod-action=${el.dataset.prodAction}]` : '';
+    return `${tag}${id}${name}${dataPage}${dataAct}`;
+  }
+
+  function safeElementValue(el) {
+    if (!el) return undefined;
+    const type = (el.type || '').toLowerCase();
+    if (type === 'password' || SECRET_ELEM_RE.test(el.id || '') || SECRET_ELEM_RE.test(el.name || '')) {
+      return '[REDACTED]';
+    }
+    if (type === 'checkbox' || type === 'radio') return !!el.checked;
+    if (typeof el.value === 'string') {
+      return el.value.length > 200 ? el.value.slice(0, 200) + '...' : el.value;
+    }
+    return undefined;
+  }
+
+  // ---- Dynamic IndexedDB Offline Spool (zero hardcoded 20MB cap) ----
+  function openIdb() {
+    if (idbPromise) return idbPromise;
+    if (!window.indexedDB) return Promise.resolve(null);
+    idbPromise = new Promise(resolve => {
+      try {
+        const req = indexedDB.open(DB_NAME, 1);
+        req.onupgradeneeded = () => {
+          const db = req.result;
+          if (!db.objectStoreNames.contains(DB_STORE)) {
+            db.createObjectStore(DB_STORE, { keyPath: 'id', autoIncrement: true });
+          }
+        };
+        req.onsuccess = () => resolve(req.result);
+        req.onerror = () => resolve(null);
+      } catch (_) {
+        resolve(null);
+      }
+    });
+    return idbPromise;
+  }
+
+  async function spoolBatchToIdb(events) {
+    if (!events.length) return;
+    const db = await openIdb();
+    if (!db) return;
+    try {
+      // Dynamic browser origin quota check (retain up to 25% of available browser storage)
+      let maxBytes = 64 * 1024 * 1024;
+      if (navigator.storage?.estimate) {
+        const est = await navigator.storage.estimate();
+        if (est && typeof est.quota === 'number' && typeof est.usage === 'number') {
+          const avail = Math.max(0, est.quota - est.usage);
+          maxBytes = Math.max(4 * 1024 * 1024, Math.floor(avail * 0.25));
+        }
+      }
+      const payloadStr = JSON.stringify(events);
+      if (payloadStr.length > maxBytes) return;
+      await new Promise(resolve => {
+        const tx = db.transaction(DB_STORE, 'readwrite');
+        tx.objectStore(DB_STORE).add({ ts_ms: Date.now(), bytes: payloadStr.length, events });
+        tx.oncomplete = () => { spooledCount += 1; resolve(); };
+        tx.onerror = () => resolve();
+      });
+    } catch (_) {}
+  }
+
+  async function drainIdbSpool() {
+    if (!isActive() || !nativeFetch) return;
+    const db = await openIdb();
+    if (!db) return;
+    try {
+      const records = await new Promise(resolve => {
+        const tx = db.transaction(DB_STORE, 'readonly');
+        const req = tx.objectStore(DB_STORE).getAll(null, 10);
+        req.onsuccess = () => resolve(req.result || []);
+        req.onerror = () => resolve([]);
+      });
+      if (!records.length) {
+        spooledCount = 0;
+        return;
+      }
+      for (const rec of records) {
+        const res = await nativeFetch('/api/trace/frontend', {
+          method: 'POST',
+          credentials: 'same-origin',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ events: rec.events }),
+        });
+        if (!res.ok) break;
+        await new Promise(resolve => {
+          const tx = db.transaction(DB_STORE, 'readwrite');
+          tx.objectStore(DB_STORE).delete(rec.id);
+          tx.oncomplete = () => resolve();
+          tx.onerror = () => resolve();
+        });
+        spooledCount = Math.max(0, spooledCount - 1);
+      }
+    } catch (_) {}
+  }
+
+  async function exportOfflineJsonl() {
+    const all = [...recentRing];
+    const db = await openIdb();
+    if (db) {
+      const records = await new Promise(resolve => {
+        try {
+          const tx = db.transaction(DB_STORE, 'readonly');
+          const req = tx.objectStore(DB_STORE).getAll();
+          req.onsuccess = () => resolve(req.result || []);
+          req.onerror = () => resolve([]);
+        } catch (_) {
+          resolve([]);
+        }
+      });
+      for (const rec of records) {
+        if (Array.isArray(rec.events)) all.push(...rec.events);
+      }
+    }
+    const text = all.map(e => JSON.stringify(e)).join('\n') + '\n';
+    const url = URL.createObjectURL(new Blob([text], { type: 'application/x-ndjson' }));
+    const a = document.createElement('a');
+    a.href = url;
+    a.download = `stl_frontend_offline_${SESSION_ID}.jsonl`;
+    a.click();
+    setTimeout(() => URL.revokeObjectURL(url), 10000);
+  }
+
+  // ---- Event Recorder & Batch Uploader ----
+  function record(kind, payload = {}) {
+    if (!isActive()) return;
+    const ev = {
+      kind,
+      session_id: SESSION_ID,
+      seq: ++seq,
+      ts_ms: Date.now(),
+      mono_ms: Math.round((performance.now?.() || 0) * 100) / 100,
+      page: document.body?.dataset?.currentPage || '',
+      ui_mode: document.body?.dataset?.uiMode || '',
+      ...sanitize(payload),
+    };
+    recentRing.push(ev);
+    if (recentRing.length > RECENT_RING_MAX) recentRing.shift();
+
+    let approxLen = 128;
+    try { approxLen = JSON.stringify(ev).length; } catch (_) {}
+    buffer.push(ev);
+    bufferBytes += approxLen;
+
+    if (buffer.length >= FLUSH_MAX_EVENTS || bufferBytes >= FLUSH_MAX_BYTES) {
+      void flush(false);
+    } else if (!flushTimer) {
+      flushTimer = setTimeout(() => {
+        flushTimer = null;
+        void flush(false);
+      }, FLUSH_INTERVAL_MS);
+    }
+  }
+
+  async function flush(useBeacon = false) {
+    if (!buffer.length) return;
+    if (flushTimer) { clearTimeout(flushTimer); flushTimer = null; }
+    const batch = buffer;
+    buffer = [];
+    bufferBytes = 0;
+
+    if (!isActive()) return;
+    const body = JSON.stringify({ events: batch });
+
+    if (useBeacon && nativeSendBeacon) {
+      try {
+        const blob = new Blob([body], { type: 'application/json' });
+        if (nativeSendBeacon('/api/trace/frontend', blob)) return;
+      } catch (_) {}
+    }
+
+    if (!nativeFetch) return;
+    if (flushing) {
+      await spoolBatchToIdb(batch);
+      return;
+    }
+    flushing = true;
+    try {
+      const res = await nativeFetch('/api/trace/frontend', {
+        method: 'POST',
+        credentials: 'same-origin',
+        headers: { 'Content-Type': 'application/json' },
+        body,
+      });
+      if (!res.ok) {
+        if (res.status !== 401 && res.status !== 403) {
+          await spoolBatchToIdb(batch);
+        }
+      } else {
+        const data = await res.json().catch(() => null);
+        if (data && typeof data.enabled === 'boolean') config.enabled = data.enabled;
+        if (data && typeof data.disk_low_paused === 'boolean') setDiskLowBanner(data.disk_low_paused);
+        if (spooledCount > 0) void drainIdbSpool();
+      }
+    } catch (_) {
+      await spoolBatchToIdb(batch);
+    } finally {
+      flushing = false;
+    }
+  }
+
+  // ---- 1. Wrap window.fetch with strict anti-recursion ----
+  if (nativeFetch) {
+    window.fetch = async function wrappedFetch(input, init) {
+      const urlStr = typeof input === 'string' ? input : (input?.url || '');
+      const skip = !isActive() || urlStr.includes('/api/trace/frontend') || init?.__stlTraceInternal;
+      if (skip) return nativeFetch(input, init);
+      const t0 = performance.now();
+      const method = (init?.method || (typeof input === 'object' && input?.method) || 'GET').toUpperCase();
+      try {
+        const res = await nativeFetch(input, init);
+        record('fe_http', {
+          method,
+          url: urlStr,
+          status: res.status,
+          ok: res.ok,
+          duration_ms: Math.round((performance.now() - t0) * 100) / 100,
+        });
+        return res;
+      } catch (err) {
+        record('fe_http', {
+          method,
+          url: urlStr,
+          status: 0,
+          ok: false,
+          error: err?.message || String(err),
+          duration_ms: Math.round((performance.now() - t0) * 100) / 100,
+        });
+        throw err;
+      }
+    };
+  }
+
+  // ---- 2. Global Error & Console Interceptors ----
+  window.addEventListener('error', ev => {
+    record('fe_error', {
+      source: 'window.error',
+      message: ev.message || '',
+      filename: ev.filename || '',
+      lineno: ev.lineno || 0,
+      colno: ev.colno || 0,
+    });
+  }, true);
+
+  window.addEventListener('unhandledrejection', ev => {
+    const r = ev.reason;
+    record('fe_error', {
+      source: 'unhandledrejection',
+      message: r?.message || String(r || ''),
+    });
+  });
+
+  console.error = (...args) => {
+    nativeConsoleError(...args);
+    record('fe_error', { source: 'console.error', args: args.map(a => String(a)).slice(0, 6) });
+  };
+  console.warn = (...args) => {
+    nativeConsoleWarn(...args);
+    record('fe_error', { source: 'console.warn', args: args.map(a => String(a)).slice(0, 6) });
+  };
+
+  // ---- 3. Capture-Phase UI Action Listeners ----
+  document.addEventListener('click', ev => {
+    const t = ev.target?.closest?.('button,a,input,select,[role="button"],summary') || ev.target;
+    record('ui_action', {
+      event: 'click',
+      target: elementDescriptor(t),
+      text: (t?.textContent || '').trim().slice(0, 80),
+      value: safeElementValue(t),
+    });
+  }, true);
+
+  document.addEventListener('change', ev => {
+    const t = ev.target;
+    record('ui_action', {
+      event: 'change',
+      target: elementDescriptor(t),
+      value: safeElementValue(t),
+    });
+  }, true);
+
+  document.addEventListener('submit', ev => {
+    record('ui_action', {
+      event: 'submit',
+      target: elementDescriptor(ev.target),
+    });
+  }, true);
+
+  document.addEventListener('keydown', ev => {
+    if (ev.key === 'Enter' || ev.key === 'Escape') {
+      record('ui_action', {
+        event: 'keydown',
+        key: ev.key,
+        target: elementDescriptor(ev.target),
+      });
+    }
+  }, true);
+
+  window.addEventListener('hashchange', () => {
+    record('ui_action', { event: 'hashchange', hash: location.hash });
+  });
+
+  document.addEventListener('visibilitychange', () => {
+    record('ui_action', { event: 'visibilitychange', state: document.visibilityState });
+    if (document.visibilityState === 'hidden') void flush(true);
+  });
+
+  window.addEventListener('pagehide', () => {
+    record('ui_action', { event: 'pagehide' });
+    void flush(true);
+  });
+
+  // ---- 4. Disk-Low Alert Banner & Trace Config UI Manager ----
+  function setDiskLowBanner(paused, message = '') {
+    diskLowPaused = !!paused;
+    const banner = document.getElementById('trace-disk-low-banner');
+    if (!banner) return;
+    if (diskLowPaused) {
+      banner.textContent = message || `磁盘剩余空间低于 ${config.min_free_gb || 2} GiB,全细节本地日志已自动暂停写入(不影响正常内存测试),清理磁盘空间后自动恢复。`;
+      banner.classList.remove('hidden');
+    } else {
+      banner.classList.add('hidden');
+    }
+  }
+
+  function applyConfig(nextCfg) {
+    if (!nextCfg || typeof nextCfg !== 'object') return;
+    config = { ...config, ...nextCfg };
+    syncConfigForm();
+  }
+
+  function syncConfigForm() {
+    const $ = id => document.getElementById(id);
+    if (!$('trace-enabled-toggle')) return;
+    $('trace-enabled-toggle').checked = !!config.enabled;
+    if ($('trace-sub-state')) $('trace-sub-state').checked = !!config.backend_state_diff;
+    if ($('trace-sub-rpc')) $('trace-sub-rpc').checked = !!config.backend_rpc_http;
+    if ($('trace-sub-serial')) $('trace-sub-serial').checked = !!config.backend_serial_stream;
+    if ($('trace-sub-hw')) $('trace-sub-hw').checked = !!config.backend_hardware_io;
+    if ($('trace-sub-fe')) $('trace-sub-fe').checked = !!config.frontend_trace;
+    if ($('trace-sub-compress')) $('trace-sub-compress').checked = !!config.compress_rotated;
+    if ($('trace-vol-mb')) $('trace-vol-mb').value = String(config.volume_mb ?? 50);
+    if ($('trace-ret-days')) $('trace-ret-days').value = String(config.retention_days ?? 30);
+    if ($('trace-min-free-gb')) $('trace-min-free-gb').value = String(config.min_free_gb ?? 2);
+    const badge = $('trace-status-badge');
+    if (badge) {
+      badge.textContent = diskLowPaused ? '空间不足暂停' : (config.enabled ? '全细节落盘运行中' : '已关闭');
+      badge.classList.toggle('connected', !!config.enabled && !diskLowPaused);
+      badge.classList.toggle('error', diskLowPaused);
+    }
+  }
+
+  async function refreshTraceStatus() {
+    if (!nativeFetch) return;
+    try {
+      const res = await nativeFetch('/api/trace/status', { credentials: 'same-origin', cache: 'no-store' });
+      if (!res.ok) return;
+      const st = await res.json();
+      if (st.config) applyConfig(st.config);
+      setDiskLowBanner(!!st.disk_low_paused);
+      const line = document.getElementById('trace-metrics-line');
+      if (line) {
+        const mb = ((Number(st.written_bytes || 0)) / (1024 * 1024)).toFixed(2);
+        const serMb = ((Number(st.serial_bytes_written || 0)) / (1024 * 1024)).toFixed(2);
+        line.textContent = `当日目录: ${st.today || '-'} · 累计事件 ${st.written_events || 0} 条 · 已落盘 ${mb} MiB (原始串口 ${serMb} MiB) · 前端入库 ${st.frontend_events_ingested || 0} 条 · 丢弃 ${st.dropped_events || 0} · 分区可用 ${st.free_disk_gib ?? '--'} GiB · 浏览器离线队列 ${spooledCount} 批`;
+      }
+    } catch (_) {}
+  }
+
+  async function saveTraceConfigFromUi() {
+    if (!nativeFetch) return;
+    const $ = id => document.getElementById(id);
+    const patch = {
+      enabled: !!$('trace-enabled-toggle')?.checked,
+      backend_state_diff: !!$('trace-sub-state')?.checked,
+      backend_rpc_http: !!$('trace-sub-rpc')?.checked,
+      backend_serial_stream: !!$('trace-sub-serial')?.checked,
+      backend_hardware_io: !!$('trace-sub-hw')?.checked,
+      frontend_trace: !!$('trace-sub-fe')?.checked,
+      compress_rotated: !!$('trace-sub-compress')?.checked,
+      volume_mb: Math.max(1, Number($('trace-vol-mb')?.value || 50)),
+      retention_days: Math.max(1, Number($('trace-ret-days')?.value || 30)),
+      min_free_gb: Math.max(0, Number($('trace-min-free-gb')?.value ?? 2)),
+    };
+    const res = await nativeFetch('/api/trace/config', {
+      method: 'POST',
+      credentials: 'same-origin',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify(patch),
+    });
+    if (res.ok) {
+      const st = await res.json().catch(() => null);
+      if (st?.config) applyConfig(st.config);
+      setDiskLowBanner(!!st?.disk_low_paused);
+      await refreshTraceStatus();
+      const note = $('trace-save-note');
+      if (note) note.textContent = `已生效(${patch.enabled ? '开启' : '已关闭'} · 无需重启)`;
+    }
+  }
+
+  // ---- 5. Hook Store, WebSocket Transport, UI Alert MutationObserver & Periodic Perf ----
+  function wireRuntimeHooks() {
+    // Store state_diff + initial state_snapshot
+    if (window.stlStore?.subscribe) {
+      let diffCount = 0;
+      record('fe_state_snapshot', {
+        trigger: 'init',
+        uiMode: window.stlStore.get('uiMode'),
+        page: window.stlStore.get('page'),
+        stationId: window.stlStore.get('stationId'),
+        connected: window.stlStore.get('connected'),
+      });
+      window.stlStore.subscribe(({ path, prev, next, trigger }) => {
+        if (!isActive()) return;
+        const summarizeVal = (p, v) => {
+          if (p === 'stations' && Array.isArray(v)) {
+            return v.map(s => `${s.station_id}:${s.task_status}:${s.verdict}:${s.fault_code || ''}`).join('|');
+          }
+          if (p.startsWith('controlByStation.')) {
+            return v ? `${v.task_status || ''}:${v.verdict || ''}:${v.firmware?.observed_phase || ''}:${v.watchdog?.fault_code || ''}` : '';
+          }
+          if (p.startsWith('diagnosticsByStation.')) {
+            return v ? `${v.state || ''}:${v.bytes_received || 0}` : '';
+          }
+          return sanitize(v);
+        };
+        const oldS = summarizeVal(path, prev);
+        const newS = summarizeVal(path, next);
+        if (JSON.stringify(oldS) === JSON.stringify(newS)) return;
+        diffCount += 1;
+        record('fe_state_diff', { path, old: oldS, new: newS, trigger });
+        if (diffCount % 200 === 0) {
+          record('fe_state_snapshot', {
+            trigger: 'periodic',
+            uiMode: window.stlStore.get('uiMode'),
+            page: window.stlStore.get('page'),
+            stationId: window.stlStore.get('stationId'),
+            connected: window.stlStore.get('connected'),
+            stationCount: (window.stlStore.get('stations') || []).length,
+          });
+        }
+      });
+    }
+
+    // Wrap WebSocket RPC calls
+    if (window.stlTransport?.call && !window.stlTransport.__traceWrapped) {
+      const origCall = window.stlTransport.call;
+      window.stlTransport.__traceWrapped = true;
+      window.stlTransport.call = async function tracedCall(method, params, timeoutMs) {
+        const isNoisyPoll = method === 'ReadCleanedUart' || method === 'GetThermalConsole';
+        const t0 = performance.now();
+        try {
+          const res = await origCall(method, params, timeoutMs);
+          if (!isNoisyPoll) {
+            record('fe_ws', {
+              method,
+              ok: true,
+              duration_ms: Math.round((performance.now() - t0) * 100) / 100,
+              params: sanitize(params),
+            });
+          }
+          return res;
+        } catch (err) {
+          record('fe_ws', {
+            method,
+            ok: false,
+            code: err?.code || 'ERR',
+            error: err?.message || String(err),
+            duration_ms: Math.round((performance.now() - t0) * 100) / 100,
+            params: sanitize(params),
+          });
+          throw err;
+        }
+      };
+    }
+
+    window.addEventListener('stl:transport-state', ev => {
+      const d = ev.detail || {};
+      record('fe_ws', { event: 'transport_state', state: d.state, generation: d.generation, pending: d.pending });
+      if (d.state === 'open') {
+        void refreshTraceStatus();
+        void drainIdbSpool();
+      }
+    });
+
+    window.addEventListener('stl:server-event', ev => {
+      const msg = ev.detail || {};
+      if (msg.event === 'trace_config_changed' && msg.result) {
+        applyConfig(msg.result);
+        return;
+      }
+      if (msg.event === 'trace_disk_low' && msg.result) {
+        setDiskLowBanner(!!msg.result.paused, msg.result.message || '');
+        return;
+      }
+      if (msg.event === 'task_complete') {
+        record('fe_ws', { event: 'task_complete', result: sanitize(msg.result) });
+      }
+    });
+
+    // UI Alert MutationObserver
+    const obsTargets = ['action-status', 'watchdog-alert-banner', 'dimm-replacement-banner'];
+    const mo = new MutationObserver(muts => {
+      for (const m of muts) {
+        const el = m.target.nodeType === 1 ? m.target : m.target.parentElement;
+        if (!el) continue;
+        const txt = (el.textContent || '').trim().slice(0, 240);
+        record('fe_ui_alert', {
+          target: elementDescriptor(el),
+          hidden: el.classList?.contains('hidden') || false,
+          alert_kind: el.dataset?.alertKind || '',
+          text: txt,
+        });
+      }
+    });
+    for (const tid of obsTargets) {
+      const node = document.getElementById(tid);
+      if (node) mo.observe(node, { childList: true, characterData: true, subtree: true, attributes: true, attributeFilter: ['class', 'data-alert-kind'] });
+    }
+
+    // Bind Trace Management Panel buttons in Engineering Records page
+    document.getElementById('btn-trace-save')?.addEventListener('click', () => { void saveTraceConfigFromUi(); });
+    document.getElementById('btn-trace-refresh')?.addEventListener('click', () => { void refreshTraceStatus(); });
+    document.getElementById('btn-trace-export-offline')?.addEventListener('click', () => { void exportOfflineJsonl(); });
+    document.getElementById('btn-trace-download-bundle')?.addEventListener('click', () => {
+      const sid = document.getElementById('trace-bundle-station')?.value || '';
+      const url = `/api/trace/bundle${sid ? '?station_id=' + encodeURIComponent(sid) : ''}`;
+      const a = document.createElement('a');
+      a.href = url;
+      a.download = '';
+      a.click();
+    });
+
+    // Periodic 30s fe_perf snapshot
+    setInterval(() => {
+      if (!isActive()) return;
+      const mem = performance.memory ? {
+        used_mb: Math.round(performance.memory.usedJSHeapSize / 1048576),
+        total_mb: Math.round(performance.memory.totalJSHeapSize / 1048576),
+      } : null;
+      record('fe_perf', {
+        dom_nodes: document.getElementsByTagName('*').length,
+        heap: mem,
+        spooled_batches: spooledCount,
+        station_id: window.stlStore?.get('stationId') || '',
+      });
+    }, 30000);
+
+    void refreshTraceStatus();
+  }
+
+  window.stlTrace = {
+    record,
+    flush,
+    refreshStatus: refreshTraceStatus,
+    exportOfflineJsonl,
+    getConfig: () => ({ ...config }),
+    isActive,
+  };
+
+  if (document.readyState === 'loading') {
+    document.addEventListener('DOMContentLoaded', wireRuntimeHooks);
+  } else {
+    wireRuntimeHooks();
+  }
+})();