Explorar o código

Release v0.9.5-preview.1: Built-in ProxyDHCP/HTTP Boot, RMT calibration, 3-mode hang recovery, full BMC telemetry, Sharded Reactor 200+ scale & 36+ bug fixes

- Built-in RFC 2131 DHCP / PXE 2.1 ProxyDHCP (UDP 67/4011) + UEFI HTTP Boot (/pxe/118.efi, /pxe/mt86.cfg) + 1-click LAN DHCP conflict probe inside stl_native_server
- RMT stage calibration fix: manual mode and unrequested/disabled 0-row wrapper lines classify as rmt_status=skipped (rmt_complete=false) instead of false RMT stage display
- 3-mode hang recovery (stop / retry_current_task / restart_full_plan) across both single-run and batch queues with consecutive hang circuit breaker
- Full BMC sensor telemetry (temp/voltage/fan/power/current/discrete) persisted to bmc_sensors.jsonl & displayed in Web UI, plus TEMP-1 MCU/SDR fusion and TEMP-2 SDR curve fallback
- Full-detail frontend & backend local disk trace logging (default ON, toggleable OFF) with background gzip rotation, .idx.json index, and streaming .tar export
- Sharded epoll reactor pool + sharded IPMI worker pool + adaptive batch window + 6-tier CPU SIMD (incl. 1024-bit VPCLMULQDQ) + OpenCL KRN-1 2-pass fix; dead code & Qt-Clean legacy cleanup
- Preview version 0.9.5-preview.1 verified across all 6 simulation & benchmark tiers (213.57s, incl. real 100% diskless KVM+OVMF ProxyDHCP under competing LAN DHCP router & live 200-station 37.34 MB/s / 756k lines/s benchmark)
XJKJ STL hai 1 semana
pai
achega
9264883152
Modificáronse 52 ficheiros con 7998 adicións e 1979 borrados
  1. 4 4
      Dockerfile
  2. 18 19
      README.md
  3. 1 1
      VERSION
  4. 0 14
      config/dimms.example.json
  5. 40 3
      deploy/pxe-dhcp/entrypoint.sh
  6. 4 3
      deploy/stl-backend.service
  7. 10 3
      docker-compose.yml
  8. 1 1
      docs/6400高温罩快速使用说明书.md
  9. 6 2
      docs/WEBSOCKET_API_ZH.md
  10. 13 15
      docs/XJKJ-STL-Architecture-Map.html
  11. 3 0
      native/stl_accel/build.sh
  12. 433 77
      native/stl_accel/c_bridge.c
  13. 148 71
      native/stl_accel/opencl_batch.c
  14. 2 110
      native/stl_accel/scan_asm.S
  15. 114 7
      native/stl_accel/simd_kernels.c
  16. 1273 894
      native/stl_accel/src/actors.rs
  17. 439 96
      native/stl_accel/src/api.rs
  18. 41 9
      native/stl_accel/src/commands.rs
  19. 87 9
      native/stl_accel/src/config.rs
  20. 112 35
      native/stl_accel/src/devices.rs
  21. 3 0
      native/stl_accel/src/json.rs
  22. 103 35
      native/stl_accel/src/lib.rs
  23. 475 12
      native/stl_accel/src/main.rs
  24. 242 34
      native/stl_accel/src/pxe.rs
  25. 1485 0
      native/stl_accel/src/pxe_dhcp.rs
  26. 323 25
      native/stl_accel/src/results.rs
  27. 77 16
      native/stl_accel/src/storage.rs
  28. 41 6
      native/stl_accel/src/thermal_mcu.rs
  29. 301 89
      native/stl_accel/src/trace.rs
  30. 285 60
      native/stl_accel/src/workflow.rs
  31. 39 2
      native/stl_accel/stl_accel.h
  32. 5 161
      native/stl_accel/zig_kernels.zig
  33. 16 13
      sim/README.md
  34. 444 0
      sim/bench_scale_performance.py
  35. 134 9
      sim/hil_cluster/bmc_ssh_hil_sim.c
  36. 1 0
      sim/hil_cluster/cluster_harness.py
  37. 26 16
      sim/hil_cluster/dut_and_hood_sim.py
  38. 62 13
      sim/hil_cluster/test_tier2_hil_e2e.py
  39. 8 5
      sim/kvm_uefi_tier/test_tier3_kvm_uefi_e2e.py
  40. 645 0
      sim/kvm_uefi_tier/test_tier3b_diskless_pxe.py
  41. 5 2
      sim/run_all_tiers.py
  42. 64 4
      sim/web_e2e/test_tier4_chrome_web_e2e.py
  43. 1 1
      web/amt-controls.js
  44. 64 15
      web/app.js
  45. 54 25
      web/boot-plan-controls.js
  46. 148 6
      web/firmware-controls.js
  47. 72 17
      web/index.html
  48. 15 4
      web/stage-progress.js
  49. 34 5
      web/store-and-ui.js
  50. 16 4
      web/style.css
  51. 53 27
      web/trace.js
  52. 8 0
      web/ui-navigation.js

+ 4 - 4
Dockerfile

@@ -4,7 +4,7 @@ ENV DEBIAN_FRONTEND=noninteractive
 WORKDIR /app
 WORKDIR /app
 
 
 RUN apt-get update && \
 RUN apt-get update && \
-    apt-get install -y --no-install-recommends libfreeipmi17 libipmiconsole2 libssh-4 ocl-icd-libopencl1 ca-certificates && \
+    apt-get install -y --no-install-recommends libfreeipmi17 libipmiconsole2 libssh-4 ocl-icd-libopencl1 gzip ca-certificates && \
     rm -rf /var/lib/apt/lists/*
     rm -rf /var/lib/apt/lists/*
 
 
 COPY VERSION README.md ./
 COPY VERSION README.md ./
@@ -14,9 +14,9 @@ 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=1.0.0.0
+ARG STL_VERSION=0.9.5-preview.1
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
 ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
     STL_VERSION=${STL_VERSION}
     STL_VERSION=${STL_VERSION}
 
 
-EXPOSE 8080 69/udp
-CMD ["/usr/local/bin/stl_native_server", "--config", "/app/config/station0-live.json", "--web-listen", "0.0.0.0:8080", "--tftp-listen", "0.0.0.0:69", "--data-dir", "/app/data", "--web-dir", "/app/web", "--contracts", "/app/contracts/firmware-vd012.json"]
+EXPOSE 8080 67/udp 69/udp 4011/udp
+CMD ["/usr/local/bin/stl_native_server", "--config", "/app/config/station0-live.json", "--web-listen", "0.0.0.0:8080", "--tftp-listen", "0.0.0.0:69", "--pxe-mode", "proxy", "--data-dir", "/app/data", "--web-dir", "/app/web", "--contracts", "/app/contracts/firmware-vd012.json"]

+ 18 - 19
README.md

@@ -1,28 +1,27 @@
 # XJKJ-STL 高温内存测试工作台
 # XJKJ-STL 高温内存测试工作台
 
 
-当前版本:`1.0.0.0`(分支:`dev`)。
+当前版本:`0.9.5-preview.1`(分支:`dev` · 预览验证版)。
 
 
-本仓库为 `XJKJ-STL` DDR5 内存高温测试与 BIOS 串口诊断工作台全栈源码,包含原生高性能后端 `stl_native_server` 与统一网页前端 `web/`(已彻底移除旧版 Windows/Linux Qt 客户端及 `/ws?view=qt-clean` 历史兼容层,仅维护唯一网页端)。
+本仓库为 `XJKJ-STL` DDR5 内存高温测试与 BIOS 串口诊断工作台全栈源码,包含原生高性能后端 `stl_native_server` 与唯一网页前端 `web/`(前端专注于实时状态展示与轻量指令下发,后端承载全部硬件通信、引导、解析、温控闭环与落盘日志)。
 
 
 ## 核心功能
 ## 核心功能
 
 
-1. **统一网页端(登录 + 产线视图 / 工程视图切换)**:
-   - 打开网页统一输入管理员密码登录(默认 `xjkj123456!`,支持页内【修改密码】并持久化至 `data/web_auth.json`),登录后可在顶部一键切换【产线视图】与【工程视图】。
-   - **产线视图**:不限工位数量的 24 槽位实时总览卡片,支持腔体温度、高温罩在线状态、秒表、24 路 PASS/FAIL/IDLE 状态、单槽点击查看温度曲线、一键开测/停止、以及一键导出标准 Excel 异常表(`.xlsx`)。
-   - **工程视图**:全量 224 项 ICT + 30 项 AMT 参数配置表、快捷 15 参数任务创建与跨工位批量指派、后端持久化多计划队列(支持 `repeat=0` 无限连续压测)、动态新增/移除工位、防卡死超时检测与双断保护配置、以及 6400 高温罩独立控制采集台。
-2. **6400 高温罩后端闭环自动控温**:
-   - 现场 6400 高温罩 USB 3.0 线统一插至控制工控机(`192.168.2.68`),由后端 `ThermalMcuHub` 按工位 1:1 托管。
-   - 开测前自动校验高温罩在线状态(产线视图强制拦截,工程视图可勾选跳过);DDR Training 完成后自动发 `0x01` 加热至目标温度;多轮队列中间轮次 PASS 发 `0x08 01` 保温;最终完成、FAIL、卡死超时、异常掉电或手动停止时自动发 `0x08 00` 吹扫降温。
-3. **PXE 双模式支持(隔离专网传统 DHCP / 同网段傻瓜交换机 ProxyDHCP)**:
-   - `deploy/pxe-dhcp/` 支持 `PXE_MODE=isolated`(默认,传统 DHCP + 独立网段)与 `PXE_MODE=proxy`(同网段与办公网 DHCP 共存,不分配 IP 仅回复 UEFI x64 引导文件 `118.efi`,默认不设 MAC 白名单,可选配置 `PXE_MAC_WHITELIST`)。
-   - 内建非阻塞 UDP `:69` TFTP 服务流式落盘接收 MemTest86 HTML/XML 报告,并结合同网段 ARP(IP → MAC)匹配工位 `os_mac`。
-4. **全细节本地落盘日志(前端 + 后端,默认开启、可动态关闭)**:
-   - 后端基于 64 字节对齐内存快照与 SIMD 异或块比对,实时记录内存状态全量快照(`state_snapshot`)、字段级变化(`state_diff`)、RPC/HTTP、硬件通信及各工位原始串口字节流(`station-<sid>.raw.0001.bin`)。
-   - 前端 `web/trace.js` 同步记录用户操作、前端状态变化、WebSocket/HTTP、告警与报错,支持断网时写入浏览器 `IndexedDB` 并在重连后自动补传。
-   - 单卷 `50 MiB` 自动切卷并后台低优先级 `gzip` 压缩,最长保留 `30` 天,分区剩余空间低于 `2 GiB` 自动暂停写入并在页面告警;支持一键下载 `.tar` 诊断包及离线命令行 `--replay-trace` 重建任意毫秒的后端状态。
-5. **6 档 CPU 指令集自动适配与 OpenCL 零拷贝批处理**:
-   - 启动时通过 `CPUID + XGETBV` 自动识别工控机芯片并在 6 个档位间切换(`Tier 0 SSE2`、`Tier 1 SSSE3 2012 Atom`、`Tier 2 SSE4.2+POPCNT+PCLMULQDQ 赛扬 J1800/N2830`、`Tier 3 Goldmont+ SHA-NI 赛扬 J4125/奔腾 J5005`、`Tier 4 AVX2+BMI1/2 Intel N100/酷睿`、`Tier 5 AVX-512`),绝不在低配芯片触发非法指令崩溃。
-   - 对离线历史日志索引、大块 Hex 编码、50 MiB 日志分块 CRC-32 与多工位 RMT 眼图归约使用 4KB 页对齐零拷贝 OpenCL 核显分流(带启动 20ms 自标定与 TDP 保护,无核显或小数据自动退回 CPU SIMD)。
+1. **无盘仅插网线 PXE / 同网段 ProxyDHCP / UEFI HTTP Boot(直接内置进后端主程序)**:
+   - `stl_native_server` 内置 RFC 2131 DHCP / PXE 2.1 ProxyDHCP(UDP `67` / `4011`)、非阻塞 TFTP(UDP `69`)与免登录 UEFI HTTP Boot(`GET /pxe/118.efi`、`GET /pxe/mt86.cfg`),不再依赖外部独立 `pxe-dhcp` 容器。
+   - **默认 `proxy` 模式**:直接插在已有路由器的局域网内即可使用,不分配 IP、忽略所有普通办公电脑请求,仅向 UEFI PXE / HTTP Boot 机子下发 `118.efi` 引导地址,并按请求端 MAC 动态在内存生成该工位独立的 `mt86.cfg`;网页内支持模式切换(`proxy` / `isolated` / `disabled`)、网卡选择与【局域网 DHCP / PXE 环境一键自检】。
+   - 有本地盘(`FSx:`)时正常兼容,无本地盘时可完全通过 PXE / UEFI HTTP Boot 启动 `118.efi` 并经 TFTP 回传 HTML/XML 报告。
+2. **统一网页端(登录 + 产线视图 / 工程视图切换)**:
+   - 支持密码登录(默认 `xjkj123456!`,可页内【修改密码】或用 `--web-password disabled` 关闭认证),登录后一键切换【产线视图】与【工程视图】。
+   - **产线视图**:不限工位数量的 24 槽位实时总览卡片,显示腔温、高温罩状态、24 路 PASS/FAIL/IDLE 与温度(MCU `0x82` 优先,未连高温罩自动回退 BMC SDR)、单槽温度曲线(2 秒自动刷新)与标准 Excel 异常导出(`.xlsx`)。
+   - **工程视图**:全量 224 项 ICT + 30 项 AMT 参数表、Profile 库与多计划循环队列、RMT 裕量/Training 观测详情(未启用或跳过时明确显示 `已跳过`)、BMC 全量传感器表(温度 / 电压 / 风扇转速 / 电流 / 功率 / 离散状态)以及 6400 高温罩控制采集台。
+3. **死机超时三种可配置处理模式**:
+   - 阶段静默超时或 BMC+2200 双断超时后自动归档现场日志并下发高温罩 `0x08 00` 吹扫降温,并按所选模式处理:① `stop`(停机保留死机现场,默认);② `retry_current_task`(自动重启并重新执行当前未完成的完整任务/轮次);③ `restart_full_plan`(自动重启并从头重做整个测试计划);单轮计划与多计划队列均支持,`max_consecutive_hangs=0` 表示不限次。
+4. **全细节本地落盘日志与完整 BMC 传感器归档(默认开启、允许关闭)**:
+   - 后端记录内存状态全量快照(320B 紧凑结构 + 64B 块 SIMD 批量差分)、RPC/HTTP、硬件通信、全量 BMC 传感器历史(单次任务归档 `bmc_sensors.jsonl`)与原始串口流(`.raw.0001.bin`);前端 `web/trace.js` 同步记录用户动作、前端状态差分、网络请求与报错,断网时写入 `IndexedDB` 重连自动补传。
+   - 单卷 `50 MiB` 自动切卷、后台低优先级并行计算索引(`.idx.json`)与 `gzip` 压缩,最长保留 `30` 天,分区剩余低于 `2 GiB` 自动暂停写入;支持流式下载 `.tar` 诊断包及离线 `--replay-trace`(透明支持 `.jsonl.gz`)重建任意毫秒状态。
+5. **面向廉价未知指令集工控机与 200~500+ 工位的高吞吐架构**:
+   - 后端将每工位独立线程重构为固定规模的 **分片 epoll 反应堆池(Sharded Reactor Pool,按 CPU 物理核数 `1..8` 分片)** 与 **分片持久 IPMI 工作池**,并引入可配置的批处理时间窗(`--batch-window-ms`,多工位下自动聚批 100ms),牺牲微秒级交互延迟以换取海量工位高吞吐并行能力与极低内存占用(`>=16` 工位自动缩容环形缓冲)。
+   - 启动通过 `CPUID + XGETBV` 自动识别并切换 6 档 CPU SIMD 内核(SSE2 / SSSE3 / SSE4.2+PCLMULQDQ / SHA-NI / AVX2+BMI2+VPCLMULQDQ / AVX-512),大块日志重扫、Hex 编码、分块 CRC-32 与 RMT 眼图归约自动经 4KB 页对齐 OpenCL 核显分流(带精确两遍算法与启动自标定,无核显时无损回退 CPU SIMD)。
 
 
 ## 目录结构
 ## 目录结构
 
 

+ 1 - 1
VERSION

@@ -1 +1 @@
-1.0.0.0
+0.9.5-preview.1

+ 0 - 14
config/dimms.example.json

@@ -1,14 +0,0 @@
-[
-  {
-    "sn": "EXAMPLE-SN-001",
-    "cpu": 0,
-    "channel": "A",
-    "slot": "A1"
-  },
-  {
-    "sn": "EXAMPLE-SN-002",
-    "cpu": 1,
-    "channel": "A",
-    "slot": "A1"
-  }
-]

+ 40 - 3
deploy/pxe-dhcp/entrypoint.sh

@@ -36,10 +36,14 @@ if [[ "$PXE_MODE" == "proxy" ]]; then
 port=0
 port=0
 interface=${PXE_IFACE}
 interface=${PXE_IFACE}
 except-interface=lo
 except-interface=lo
-bind-interfaces
+bind-dynamic
 dhcp-range=${PXE_SUBNET},proxy,${PXE_NETMASK}
 dhcp-range=${PXE_SUBNET},proxy,${PXE_NETMASK}
+pxe-prompt="XJKJ-STL PXE Boot",0
+dhcp-match=set:efi-ia32,option:client-arch,6
 dhcp-match=set:efi-x86_64,option:client-arch,7
 dhcp-match=set:efi-x86_64,option:client-arch,7
 dhcp-match=set:efi-x86_64,option:client-arch,9
 dhcp-match=set:efi-x86_64,option:client-arch,9
+dhcp-match=set:efi-arm64,option:client-arch,11
+dhcp-match=set:efi-http,option:client-arch,16
 EOF
 EOF
   if [[ -n "$PXE_MAC_WHITELIST" ]]; then
   if [[ -n "$PXE_MAC_WHITELIST" ]]; then
     IFS=',' read -ra MACS <<< "$PXE_MAC_WHITELIST"
     IFS=',' read -ra MACS <<< "$PXE_MAC_WHITELIST"
@@ -51,11 +55,21 @@ EOF
     done
     done
     cat >> /etc/dnsmasq.pxe.conf << EOF
     cat >> /etc/dnsmasq.pxe.conf << EOF
 dhcp-ignore=tag:!sut
 dhcp-ignore=tag:!sut
+dhcp-boot=tag:sut,tag:efi-x86_64,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+dhcp-boot=tag:sut,tag:efi-ia32,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+dhcp-boot=tag:sut,tag:efi-arm64,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
 pxe-service=tag:sut,tag:efi-x86_64,X86-64_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
 pxe-service=tag:sut,tag:efi-x86_64,X86-64_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
+pxe-service=tag:sut,tag:efi-ia32,BC_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
+pxe-service=tag:sut,tag:efi-arm64,ARM64_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
 EOF
 EOF
   else
   else
     cat >> /etc/dnsmasq.pxe.conf << EOF
     cat >> /etc/dnsmasq.pxe.conf << EOF
+dhcp-boot=tag:efi-x86_64,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+dhcp-boot=tag:efi-ia32,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+dhcp-boot=tag:efi-arm64,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
 pxe-service=tag:efi-x86_64,X86-64_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
 pxe-service=tag:efi-x86_64,X86-64_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
+pxe-service=tag:efi-ia32,BC_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
+pxe-service=tag:efi-arm64,ARM64_EFI,"XJKJ-STL MemTest86",${PXE_BOOT_FILE},${PXE_SERVER_IP}
 EOF
 EOF
   fi
   fi
   cat >> /etc/dnsmasq.pxe.conf << EOF
   cat >> /etc/dnsmasq.pxe.conf << EOF
@@ -76,15 +90,38 @@ EOF
     echo "except-interface=${PXE_DENY_IFACE}" >> /etc/dnsmasq.pxe.conf
     echo "except-interface=${PXE_DENY_IFACE}" >> /etc/dnsmasq.pxe.conf
   fi
   fi
   cat >> /etc/dnsmasq.pxe.conf << EOF
   cat >> /etc/dnsmasq.pxe.conf << EOF
-bind-interfaces
+bind-dynamic
 dhcp-range=${PXE_RANGE_START},${PXE_RANGE_END},${PXE_NETMASK},12h
 dhcp-range=${PXE_RANGE_START},${PXE_RANGE_END},${PXE_NETMASK},12h
 dhcp-option=3,${PXE_SERVER_IP}
 dhcp-option=3,${PXE_SERVER_IP}
 dhcp-option=6,${PXE_SERVER_IP}
 dhcp-option=6,${PXE_SERVER_IP}
 dhcp-option=66,"${PXE_SERVER_IP}"
 dhcp-option=66,"${PXE_SERVER_IP}"
-dhcp-boot=${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+pxe-prompt="XJKJ-STL PXE Boot",0
+dhcp-match=set:efi-ia32,option:client-arch,6
 dhcp-match=set:efi-x86_64,option:client-arch,7
 dhcp-match=set:efi-x86_64,option:client-arch,7
 dhcp-match=set:efi-x86_64,option:client-arch,9
 dhcp-match=set:efi-x86_64,option:client-arch,9
+dhcp-match=set:efi-arm64,option:client-arch,11
+EOF
+  if [[ -n "$PXE_MAC_WHITELIST" ]]; then
+    IFS=',' read -ra MACS <<< "$PXE_MAC_WHITELIST"
+    for raw_mac in "${MACS[@]}"; do
+      mac="$(echo "$raw_mac" | tr -d '[:space:]')"
+      if [[ -n "$mac" ]]; then
+        echo "dhcp-host=${mac},set:sut" >> /etc/dnsmasq.pxe.conf
+      fi
+    done
+    cat >> /etc/dnsmasq.pxe.conf << EOF
+dhcp-ignore=tag:!sut
+dhcp-boot=tag:sut,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+EOF
+  else
+    cat >> /etc/dnsmasq.pxe.conf << EOF
+dhcp-boot=${PXE_BOOT_FILE},,${PXE_SERVER_IP}
 dhcp-boot=tag:efi-x86_64,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
 dhcp-boot=tag:efi-x86_64,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+dhcp-boot=tag:efi-ia32,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+dhcp-boot=tag:efi-arm64,${PXE_BOOT_FILE},,${PXE_SERVER_IP}
+EOF
+  fi
+  cat >> /etc/dnsmasq.pxe.conf << EOF
 log-dhcp
 log-dhcp
 log-facility=/pxe/logs/dnsmasq.log
 log-facility=/pxe/logs/dnsmasq.log
 EOF
 EOF

+ 4 - 3
deploy/stl-backend.service

@@ -7,11 +7,12 @@ After=network-online.target
 Type=simple
 Type=simple
 User=stl
 User=stl
 Group=stl
 Group=stl
-AmbientCapabilities=CAP_NET_BIND_SERVICE
-CapabilityBoundingSet=CAP_NET_BIND_SERVICE
+SupplementaryGroups=dialout
+AmbientCapabilities=CAP_NET_BIND_SERVICE CAP_NET_RAW
+CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_NET_RAW
 WorkingDirectory=/opt/xjkj-stl
 WorkingDirectory=/opt/xjkj-stl
 EnvironmentFile=/etc/xjkj-stl/stl-backend.env
 EnvironmentFile=/etc/xjkj-stl/stl-backend.env
-ExecStart=/usr/local/bin/stl_native_server --config /etc/xjkj-stl/station0-live.json --web-listen 0.0.0.0:8080 --tftp-listen 0.0.0.0:69 --data-dir /var/lib/xjkj-stl --web-dir /opt/xjkj-stl/web --contracts /opt/xjkj-stl/contracts/firmware-vd012.json
+ExecStart=/usr/local/bin/stl_native_server --config /etc/xjkj-stl/station0-live.json --web-listen 0.0.0.0:8080 --tftp-listen 0.0.0.0:69 --pxe-mode proxy --data-dir /var/lib/xjkj-stl --web-dir /opt/xjkj-stl/web --contracts /opt/xjkj-stl/contracts/firmware-vd012.json
 StateDirectory=xjkj-stl
 StateDirectory=xjkj-stl
 StateDirectoryMode=0750
 StateDirectoryMode=0750
 UMask=0027
 UMask=0027

+ 10 - 3
docker-compose.yml

@@ -3,13 +3,16 @@ services:
     build:
     build:
       context: .
       context: .
       args:
       args:
-        STL_VERSION: ${STL_VERSION:-0.8.1.30}
+        STL_VERSION: ${STL_VERSION:-0.9.5-preview.1}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
         STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
-    image: xjkj-stl:0.8.1.30
+    image: xjkj-stl:0.9.5-preview.1
     container_name: xjkj-stl-backend
     container_name: xjkj-stl-backend
     restart: unless-stopped
     restart: unless-stopped
     stop_grace_period: 30s
     stop_grace_period: 30s
     network_mode: host
     network_mode: host
+    cap_add:
+      - NET_BIND_SERVICE
+      - NET_RAW
     device_cgroup_rules:
     device_cgroup_rules:
       - "c 188:* rmw"
       - "c 188:* rmw"
       - "c 166:* rmw"
       - "c 166:* rmw"
@@ -36,6 +39,8 @@ services:
       - 0.0.0.0:8080
       - 0.0.0.0:8080
       - --tftp-listen
       - --tftp-listen
       - 0.0.0.0:69
       - 0.0.0.0:69
+      - --pxe-mode
+      - ${PXE_MODE:-proxy}
       - --data-dir
       - --data-dir
       - /app/data
       - /app/data
       - --web-dir
       - --web-dir
@@ -44,9 +49,11 @@ services:
       - /app/contracts/firmware-vd012.json
       - /app/contracts/firmware-vd012.json
 
 
   pxe-dhcp:
   pxe-dhcp:
+    profiles:
+      - legacy-pxe-dhcp
     build:
     build:
       context: ./deploy/pxe-dhcp
       context: ./deploy/pxe-dhcp
-    image: xjkj-pxe-dhcp:0.8.1.26
+    image: xjkj-pxe-dhcp:0.9.5-preview.1
     container_name: xjkj-pxe-dhcp
     container_name: xjkj-pxe-dhcp
     restart: unless-stopped
     restart: unless-stopped
     network_mode: host
     network_mode: host

+ 1 - 1
docs/6400高温罩快速使用说明书.md

@@ -1,4 +1,4 @@
-# 6400 高温罩 & 内存高温测试工作台 快速使用说明书(v1.0.0.0 网页单端版)
+# 6400 高温罩 & 内存高温测试工作台 快速使用说明书(v0.9.5-preview.1 预览版)
 
 
 > **适用范围**:6400 V2.0 自动升降高温罩 + 配套 DDR5 RDIMM 测试服务器 + 控制工控机(`192.168.2.68`)+ 浏览器网页端(`http://192.168.2.68:8080/`)。
 > **适用范围**:6400 V2.0 自动升降高温罩 + 配套 DDR5 RDIMM 测试服务器 + 控制工控机(`192.168.2.68`)+ 浏览器网页端(`http://192.168.2.68:8080/`)。
 > **重要变更**:系统现仅保留**唯一网页端**(内置【产线视图】与【工程视图】切换),彻底取消旧版桌面软件及本地 `config.json` / `port.json` 配置;**所有 6400 高温罩的 USB 3.0 线统一直接插在控制工控机上**,由后端统一控温与采集。
 > **重要变更**:系统现仅保留**唯一网页端**(内置【产线视图】与【工程视图】切换),彻底取消旧版桌面软件及本地 `config.json` / `port.json` 配置;**所有 6400 高温罩的 USB 3.0 线统一直接插在控制工控机上**,由后端统一控温与采集。

+ 6 - 2
docs/WEBSOCKET_API_ZH.md

@@ -1,6 +1,6 @@
-# XJKJ-STL 1.0.0.0:WebSocket 与 HTTP 服务接口手册(唯一网页端版)
+# XJKJ-STL 0.9.5-preview.1:WebSocket 与 HTTP 服务接口手册
 
 
-本文档对应 `1.0.0.0` 原生控制后端 `stl_native_server` 的全部公开接口,包含认证后的唯一 WebSocket 入口 `/ws`、HTTP 业务与诊断日志接口,以及内建非阻塞 UDP `:69` TFTP PXE 服务。
+本文档对应 `0.9.5-preview.1` 原生控制后端 `stl_native_server` 的全部公开接口,包含认证后的唯一 WebSocket 入口 `/ws`、HTTP 业务/诊断日志/UEFI HTTP Boot 接口,以及内置的 UDP `67`/`4011` ProxyDHCP 与 UDP `69` TFTP 引导服务。
 
 
 > 说明:自 `0.9.0.0` 起已彻底移除所有 Qt 客户端源码、`/ws?view=qt-clean` 免密入口及重复别名 RPC(`GetState`、`StartTest`、`StageAction`、`ReadBiosUart`、`GetCommand`、`GetTaskBatch` 等);自 `0.9.1.0` 起新增全细节前后端本地落盘日志与 CLI 离线状态回放;自 `1.0.0.0` 起全面启用 6 档 CPU 指令集运行时分派与 4KB 页对齐零拷贝 OpenCL 批处理引擎。
 > 说明:自 `0.9.0.0` 起已彻底移除所有 Qt 客户端源码、`/ws?view=qt-clean` 免密入口及重复别名 RPC(`GetState`、`StartTest`、`StageAction`、`ReadBiosUart`、`GetCommand`、`GetTaskBatch` 等);自 `0.9.1.0` 起新增全细节前后端本地落盘日志与 CLI 离线状态回放;自 `1.0.0.0` 起全面启用 6 档 CPU 指令集运行时分派与 4KB 页对齐零拷贝 OpenCL 批处理引擎。
 
 
@@ -56,6 +56,9 @@
 | `GetThermalConsole` / `ThermalAction` | 查询/控制 | `{"station_id":"S1","action":"scan_ports\|save_mappings\|connect\|disconnect\|set_temp\|..."}` | 6400 高温罩独立串口绑定、实时控温与 34 列模板 CSV 采集 |
 | `GetThermalConsole` / `ThermalAction` | 查询/控制 | `{"station_id":"S1","action":"scan_ports\|save_mappings\|connect\|disconnect\|set_temp\|..."}` | 6400 高温罩独立串口绑定、实时控温与 34 列模板 CSV 采集 |
 | `GetTraceConfig` / `GetTraceStatus` / `ConfigureDetailLog` | 查询/控制 | `{"enabled":true,"volume_mb":50,"retention_days":30,"min_free_gb":2,...}` | 查询或热更新全细节前后端本地落盘日志开关与配额 |
 | `GetTraceConfig` / `GetTraceStatus` / `ConfigureDetailLog` | 查询/控制 | `{"enabled":true,"volume_mb":50,"retention_days":30,"min_free_gb":2,...}` | 查询或热更新全细节前后端本地落盘日志开关与配额 |
 | `GetHardwareInfo` | 只读 | `{}` | 查询 6 档 CPU 指令集检测结果、物理线程数及 OpenCL 批处理引擎状态 |
 | `GetHardwareInfo` | 只读 | `{}` | 查询 6 档 CPU 指令集检测结果、物理线程数及 OpenCL 批处理引擎状态 |
+| `GetPxeStatus` | 只读 | `{}` | 查询内置 ProxyDHCP / Isolated DHCP / TFTP / UEFI HTTP Boot 绑定状态、网卡列表、收发计数与已发现无盘客户端 |
+| `ProbePxeNetwork` | 探测 | `{"iface":"","timeout_ms":1000}` | 局域网 DHCP / PXE 冲突一键自检,主动探测同网段外部 DHCP 路由器并给出推荐引导模式 |
+| `ConfigurePxe` | 控制 | `{"pxe_mode":"proxy\|isolated\|disabled","pxe_iface":"","pxe_server_ip":"","pxe_dhcp_range_start":"","pxe_dhcp_range_end":"","pxe_mac_whitelist":[]}` | 顶层调用:热切换内置引导服务模式与网卡(立即重绑端口无需重启服务) |
 
 
 ---
 ---
 
 
@@ -88,3 +91,4 @@
 | `POST /api/trace/frontend` | 接收网页端 `web/trace.js` 批量上报的前端操作/状态变化/告警/报错事件(不递归写 HTTP 访问日志) |
 | `POST /api/trace/frontend` | 接收网页端 `web/trace.js` 批量上报的前端操作/状态变化/告警/报错事件(不递归写 HTTP 访问日志) |
 | `GET /api/trace/bundle?station_id=<sid>&day=<YYYY-MM-DD>` | 一键打包下载当日诊断日志包(标准 POSIX `.tar`,含配置、状态、后端差分日志、前端日志及原始串口流) |
 | `GET /api/trace/bundle?station_id=<sid>&day=<YYYY-MM-DD>` | 一键打包下载当日诊断日志包(标准 POSIX `.tar`,含配置、状态、后端差分日志、前端日志及原始串口流) |
 | `GET /api/hw/info` | 返回 6 档 CPU 指令集特性位与 OpenCL 零拷贝核显批处理标定信息 |
 | `GET /api/hw/info` | 返回 6 档 CPU 指令集特性位与 OpenCL 零拷贝核显批处理标定信息 |
+| `GET /pxe/<filename>` / `HEAD /pxe/<filename>` | 免登录 UEFI HTTP Boot 静态与动态文件下载(支持 `118.efi`、`pxe_sync.efi` 及按来源 IP/MAC 动态生成的工位独立 `mt86.cfg`) |

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 13 - 15
docs/XJKJ-STL-Architecture-Map.html


+ 3 - 0
native/stl_accel/build.sh

@@ -12,6 +12,9 @@ gcc -c -O3 -fPIC -march=x86-64 -I. simd_kernels.c -o "${BUILD_DIR}/simd_kernels.
 gcc -c -O3 -fPIC -march=x86-64 -I. opencl_batch.c -o "${BUILD_DIR}/opencl_batch.o"
 gcc -c -O3 -fPIC -march=x86-64 -I. opencl_batch.c -o "${BUILD_DIR}/opencl_batch.o"
 gcc -c -O3 -fPIC -march=x86-64 scan_asm.S -o "${BUILD_DIR}/scan_asm.o"
 gcc -c -O3 -fPIC -march=x86-64 scan_asm.S -o "${BUILD_DIR}/scan_asm.o"
 zig build-obj -O ReleaseFast -fPIC -mcpu=x86_64 -femit-bin="${BUILD_DIR}/zig_kernels.o" zig_kernels.zig
 zig build-obj -O ReleaseFast -fPIC -mcpu=x86_64 -femit-bin="${BUILD_DIR}/zig_kernels.o" zig_kernels.zig
+if [ -f "${ROOT_DIR}/tools/pxe_sync.zig" ]; then
+    zig build-exe -O ReleaseSmall -target x86_64-uefi-msvc -femit-bin="${BUILD_DIR}/pxe_sync.efi" "${ROOT_DIR}/tools/pxe_sync.zig"
+fi
 gcc -c -O3 -fPIC -march=x86-64 -I. c_bridge.c -o "${BUILD_DIR}/c_bridge.o"
 gcc -c -O3 -fPIC -march=x86-64 -I. c_bridge.c -o "${BUILD_DIR}/c_bridge.o"
 ar rcs "${BUILD_DIR}/libstl_kernels.a" \
 ar rcs "${BUILD_DIR}/libstl_kernels.a" \
     "${BUILD_DIR}/parser_re2c.o" \
     "${BUILD_DIR}/parser_re2c.o" \

+ 433 - 77
native/stl_accel/c_bridge.c

@@ -17,10 +17,12 @@
 #include <fcntl.h>
 #include <fcntl.h>
 #include <freeipmi/freeipmi.h>
 #include <freeipmi/freeipmi.h>
 #include <freeipmi/record-format/ipmi-sdr-record-format.h>
 #include <freeipmi/record-format/ipmi-sdr-record-format.h>
+#include <ifaddrs.h>
 #include <ipmiconsole.h>
 #include <ipmiconsole.h>
 #include <libssh/callbacks.h>
 #include <libssh/callbacks.h>
 #include <libssh/libssh.h>
 #include <libssh/libssh.h>
 #include <libssh/sftp.h>
 #include <libssh/sftp.h>
+#include <net/if.h>
 #include <netdb.h>
 #include <netdb.h>
 #include <netinet/in.h>
 #include <netinet/in.h>
 #include <netinet/tcp.h>
 #include <netinet/tcp.h>
@@ -33,6 +35,7 @@
 #include <string.h>
 #include <string.h>
 #include <sys/epoll.h>
 #include <sys/epoll.h>
 #include <sys/eventfd.h>
 #include <sys/eventfd.h>
+#include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/mman.h>
 #include <sys/resource.h>
 #include <sys/resource.h>
 #include <sys/socket.h>
 #include <sys/socket.h>
@@ -246,6 +249,9 @@ size_t stl_hex_encode(const uint8_t *src, size_t len, uint8_t *dst) {
 uint32_t stl_crc32_ieee(uint32_t init_crc, const uint8_t *buf, size_t len) {
 uint32_t stl_crc32_ieee(uint32_t init_crc, const uint8_t *buf, size_t len) {
     if (!buf || len == 0) return init_crc;
     if (!buf || len == 0) return init_crc;
     int tier = stl_active_isa_tier();
     int tier = stl_active_isa_tier();
+    if (tier >= STL_ISA_AVX2_BMI && g_hw_caps.has_vpclmul && len >= 128u) {
+        return simd_crc32_ieee_vpclmul(init_crc, buf, len);
+    }
     if (tier >= STL_ISA_SSE42_PCLMUL && g_hw_caps.has_pclmul) {
     if (tier >= STL_ISA_SSE42_PCLMUL && g_hw_caps.has_pclmul) {
         return simd_crc32_ieee_pclmul(init_crc, buf, len);
         return simd_crc32_ieee_pclmul(init_crc, buf, len);
     }
     }
@@ -308,34 +314,11 @@ void stl_clean_split_classify(
     }
     }
 }
 }
 
 
-/* Pure SSE2 helper for legacy single-buffer scan (zero rdtsc/lfence!) */
-size_t c_dispatch_scan_special(
-    const uint8_t *buf,
-    size_t         len,
-    uint64_t      *out_newlines,
-    uint64_t      *out_specials) {
-    uint64_t nl = 0;
-    uint64_t sp = 0;
-    size_t first_ctrl = len;
-    for (size_t i = 0; i < len; i++) {
-        uint8_t b = buf[i];
-        if (b == '\n' || b == '\r') {
-            nl++;
-        } else if (b < 0x20 || b == 0x7f) {
-            sp++;
-            if (first_ctrl == len) first_ctrl = i;
-        }
-    }
-    if (out_newlines) *out_newlines = nl;
-    if (out_specials) *out_specials = sp;
-    return first_ctrl;
-}
-
 /* =========================================================================
 /* =========================================================================
- * 2. Monotonic 64-Bit mmap Ring Buffer (Hugepage + 64B Pad + PROT_NONE Guard)
+ * 2. Monotonic 64-Bit mmap Ring Buffer (Optional Hugepage + 64B Pad + PROT_NONE Guard)
  * ========================================================================= */
  * ========================================================================= */
-static size_t round_up_pow2_min2m(size_t v) {
-    size_t cap = 2u * 1024u * 1024u; /* 2 MiB hugepage granularity */
+static size_t round_up_pow2_min256k(size_t v) {
+    size_t cap = 256u * 1024u; /* 256 KiB floor for high-density 200-500 station deployments */
     while (cap < v && cap < (1ULL << 30)) {
     while (cap < v && cap < (1ULL << 30)) {
         cap <<= 1;
         cap <<= 1;
     }
     }
@@ -346,7 +329,7 @@ int stl_ring_init(StlRingBuf *rb, size_t requested_cap) {
     if (!rb) return -1;
     if (!rb) return -1;
     memset(rb, 0, sizeof(*rb));
     memset(rb, 0, sizeof(*rb));
 
 
-    size_t cap = round_up_pow2_min2m(requested_cap == 0 ? (8u * 1024u * 1024u) : requested_cap);
+    size_t cap = round_up_pow2_min256k(requested_cap == 0 ? (8u * 1024u * 1024u) : requested_cap);
     size_t page_sz = 4096u;
     size_t page_sz = 4096u;
     /* [0..cap): circular ring; [cap..cap+4096): 64B+ zeroed tail pad page; [cap+4096..cap+8192): PROT_NONE guard */
     /* [0..cap): circular ring; [cap..cap+4096): 64B+ zeroed tail pad page; [cap+4096..cap+8192): PROT_NONE guard */
     size_t pad_bytes   = page_sz;
     size_t pad_bytes   = page_sz;
@@ -359,7 +342,9 @@ int stl_ring_init(StlRingBuf *rb, size_t requested_cap) {
     }
     }
 
 
 #ifdef MADV_HUGEPAGE
 #ifdef MADV_HUGEPAGE
-    (void)madvise(mem, cap, MADV_HUGEPAGE);
+    if (cap >= 2u * 1024u * 1024u) {
+        (void)madvise(mem, cap, MADV_HUGEPAGE);
+    }
 #endif
 #endif
 
 
     /* Arm hardware guard page immediately after the 4KB tail-padding page */
     /* Arm hardware guard page immediately after the 4KB tail-padding page */
@@ -802,19 +787,25 @@ static StlIpmiSlot    **g_ipmi_slots   = NULL;
 static int              g_ipmi_cap     = 0;
 static int              g_ipmi_cap     = 0;
 
 
 static StlSshSlot *alloc_ssh_slot_locked(int *out_idx) {
 static StlSshSlot *alloc_ssh_slot_locked(int *out_idx) {
+    int first_null = -1;
     for (int i = 0; i < g_ssh_cap; i++) {
     for (int i = 0; i < g_ssh_cap; i++) {
-        if (g_ssh_slots[i] && !g_ssh_slots[i]->in_use) {
+        if (g_ssh_slots[i] == NULL) {
+            if (first_null < 0) first_null = i;
+        } else if (!g_ssh_slots[i]->in_use) {
             *out_idx = i;
             *out_idx = i;
             return g_ssh_slots[i];
             return g_ssh_slots[i];
         }
         }
     }
     }
-    int new_cap = (g_ssh_cap == 0) ? 16 : (g_ssh_cap * 2);
-    StlSshSlot **next = (StlSshSlot **)realloc(g_ssh_slots, (size_t)new_cap * sizeof(StlSshSlot *));
-    if (!next) return NULL;
-    memset(next + g_ssh_cap, 0, (size_t)(new_cap - g_ssh_cap) * sizeof(StlSshSlot *));
-    g_ssh_slots = next;
-    int idx = g_ssh_cap;
-    g_ssh_cap = new_cap;
+    int idx = first_null;
+    if (idx < 0) {
+        int new_cap = (g_ssh_cap == 0) ? 16 : (g_ssh_cap * 2);
+        StlSshSlot **next = (StlSshSlot **)realloc(g_ssh_slots, (size_t)new_cap * sizeof(StlSshSlot *));
+        if (!next) return NULL;
+        memset(next + g_ssh_cap, 0, (size_t)(new_cap - g_ssh_cap) * sizeof(StlSshSlot *));
+        g_ssh_slots = next;
+        idx = g_ssh_cap;
+        g_ssh_cap = new_cap;
+    }
     StlSshSlot *s = (StlSshSlot *)calloc(1, sizeof(StlSshSlot));
     StlSshSlot *s = (StlSshSlot *)calloc(1, sizeof(StlSshSlot));
     if (!s) return NULL;
     if (!s) return NULL;
     g_ssh_slots[idx] = s;
     g_ssh_slots[idx] = s;
@@ -823,19 +814,25 @@ static StlSshSlot *alloc_ssh_slot_locked(int *out_idx) {
 }
 }
 
 
 static StlSolSlot *alloc_sol_slot_locked(int *out_idx) {
 static StlSolSlot *alloc_sol_slot_locked(int *out_idx) {
+    int first_null = -1;
     for (int i = 0; i < g_sol_cap; i++) {
     for (int i = 0; i < g_sol_cap; i++) {
-        if (g_sol_slots[i] && !g_sol_slots[i]->in_use) {
+        if (g_sol_slots[i] == NULL) {
+            if (first_null < 0) first_null = i;
+        } else if (!g_sol_slots[i]->in_use) {
             *out_idx = i;
             *out_idx = i;
             return g_sol_slots[i];
             return g_sol_slots[i];
         }
         }
     }
     }
-    int new_cap = (g_sol_cap == 0) ? 16 : (g_sol_cap * 2);
-    StlSolSlot **next = (StlSolSlot **)realloc(g_sol_slots, (size_t)new_cap * sizeof(StlSolSlot *));
-    if (!next) return NULL;
-    memset(next + g_sol_cap, 0, (size_t)(new_cap - g_sol_cap) * sizeof(StlSolSlot *));
-    g_sol_slots = next;
-    int idx = g_sol_cap;
-    g_sol_cap = new_cap;
+    int idx = first_null;
+    if (idx < 0) {
+        int new_cap = (g_sol_cap == 0) ? 16 : (g_sol_cap * 2);
+        StlSolSlot **next = (StlSolSlot **)realloc(g_sol_slots, (size_t)new_cap * sizeof(StlSolSlot *));
+        if (!next) return NULL;
+        memset(next + g_sol_cap, 0, (size_t)(new_cap - g_sol_cap) * sizeof(StlSolSlot *));
+        g_sol_slots = next;
+        idx = g_sol_cap;
+        g_sol_cap = new_cap;
+    }
     StlSolSlot *s = (StlSolSlot *)calloc(1, sizeof(StlSolSlot));
     StlSolSlot *s = (StlSolSlot *)calloc(1, sizeof(StlSolSlot));
     if (!s) return NULL;
     if (!s) return NULL;
     g_sol_slots[idx] = s;
     g_sol_slots[idx] = s;
@@ -844,8 +841,11 @@ static StlSolSlot *alloc_sol_slot_locked(int *out_idx) {
 }
 }
 
 
 static StlIpmiSlot *alloc_ipmi_slot_locked(int *out_idx) {
 static StlIpmiSlot *alloc_ipmi_slot_locked(int *out_idx) {
+    int first_null = -1;
     for (int i = 0; i < g_ipmi_cap; i++) {
     for (int i = 0; i < g_ipmi_cap; i++) {
-        if (g_ipmi_slots[i]) {
+        if (g_ipmi_slots[i] == NULL) {
+            if (first_null < 0) first_null = i;
+        } else {
             pthread_mutex_lock(&g_ipmi_slots[i]->mu);
             pthread_mutex_lock(&g_ipmi_slots[i]->mu);
             if (!g_ipmi_slots[i]->in_use) {
             if (!g_ipmi_slots[i]->in_use) {
                 *out_idx = i;
                 *out_idx = i;
@@ -854,13 +854,16 @@ static StlIpmiSlot *alloc_ipmi_slot_locked(int *out_idx) {
             pthread_mutex_unlock(&g_ipmi_slots[i]->mu);
             pthread_mutex_unlock(&g_ipmi_slots[i]->mu);
         }
         }
     }
     }
-    int new_cap = (g_ipmi_cap == 0) ? 16 : (g_ipmi_cap * 2);
-    StlIpmiSlot **next = (StlIpmiSlot **)realloc(g_ipmi_slots, (size_t)new_cap * sizeof(StlIpmiSlot *));
-    if (!next) return NULL;
-    memset(next + g_ipmi_cap, 0, (size_t)(new_cap - g_ipmi_cap) * sizeof(StlIpmiSlot *));
-    g_ipmi_slots = next;
-    int idx = g_ipmi_cap;
-    g_ipmi_cap = new_cap;
+    int idx = first_null;
+    if (idx < 0) {
+        int new_cap = (g_ipmi_cap == 0) ? 16 : (g_ipmi_cap * 2);
+        StlIpmiSlot **next = (StlIpmiSlot **)realloc(g_ipmi_slots, (size_t)new_cap * sizeof(StlIpmiSlot *));
+        if (!next) return NULL;
+        memset(next + g_ipmi_cap, 0, (size_t)(new_cap - g_ipmi_cap) * sizeof(StlIpmiSlot *));
+        g_ipmi_slots = next;
+        idx = g_ipmi_cap;
+        g_ipmi_cap = new_cap;
+    }
     StlIpmiSlot *s = (StlIpmiSlot *)calloc(1, sizeof(StlIpmiSlot));
     StlIpmiSlot *s = (StlIpmiSlot *)calloc(1, sizeof(StlIpmiSlot));
     if (!s) return NULL;
     if (!s) return NULL;
     pthread_mutex_init(&s->mu, NULL);
     pthread_mutex_init(&s->mu, NULL);
@@ -990,10 +993,9 @@ int c_pty_open_serial_115200(const char *path) {
     return stl_open_tty_115200_raw(path);
     return stl_open_tty_115200_raw(path);
 }
 }
 
 
-/* Open serial with configurable baud rate (115200 / 230400 / 460800 / 921600) for thermal hood */
+/* Open serial with configurable baud rate (115200 / 230400 / 460800 / 921600) */
 int c_open_tty_baud_raw(const char *path, int baud) {
 int c_open_tty_baud_raw(const char *path, int baud) {
     if (!path || path[0] == '\0') return -1;
     if (!path || path[0] == '\0') return -1;
-    if (strstr(path, "ttyUSB1") != NULL) return -1;
     int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
     int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
     if (fd < 0) return -1;
     if (fd < 0) return -1;
 
 
@@ -1770,9 +1772,13 @@ int c_ipmi_open(
 }
 }
 
 
 void c_ipmi_close(int handle) {
 void c_ipmi_close(int handle) {
-    StlIpmiSlot *slot = get_ipmi_slot(handle);
-    if (!slot) return;
+    if (handle < 1) return;
     pthread_mutex_lock(&g_slots_lock);
     pthread_mutex_lock(&g_slots_lock);
+    StlIpmiSlot *slot = (handle <= g_ipmi_cap) ? g_ipmi_slots[handle - 1] : NULL;
+    if (!slot) {
+        pthread_mutex_unlock(&g_slots_lock);
+        return;
+    }
     pthread_mutex_lock(&slot->mu);
     pthread_mutex_lock(&slot->mu);
     if (slot->in_use) {
     if (slot->in_use) {
         if (slot->ctx) {
         if (slot->ctx) {
@@ -1964,6 +1970,20 @@ static int contains_ci_dimm(const char *s) {
     return 0;
     return 0;
 }
 }
 
 
+static const char *ipmi_unit_label(uint8_t base_u, uint8_t pct) {
+    if (pct == 1) return "%";
+    switch (base_u) {
+        case IPMI_SENSOR_UNIT_DEGREES_C: return "degrees C";
+        case IPMI_SENSOR_UNIT_DEGREES_F: return "degrees F";
+        case IPMI_SENSOR_UNIT_VOLTS:     return "Volts";
+        case IPMI_SENSOR_UNIT_AMPS:      return "Amps";
+        case IPMI_SENSOR_UNIT_WATTS:     return "Watts";
+        case IPMI_SENSOR_UNIT_RPM:       return "RPM";
+        case IPMI_SENSOR_UNIT_HZ:        return "Hz";
+        default:                         return "units";
+    }
+}
+
 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,
@@ -1986,6 +2006,9 @@ static int sdr_iterate_cb(
     int units_ok = (ipmi_sdr_parse_sensor_units(
     int units_ok = (ipmi_sdr_parse_sensor_units(
                         sdr, sdr_record, sdr_record_len,
                         sdr, sdr_record, sdr_record_len,
                         &pct, &mod, &rate, &base_u, &mod_u) == 0);
                         &pct, &mod, &rate, &base_u, &mod_u) == 0);
+    uint8_t stype = 0, ert = 0;
+    int has_type = (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);
 
 
     uint8_t raw = 0;
     uint8_t raw = 0;
     double *reading = NULL;
     double *reading = NULL;
@@ -1993,31 +2016,24 @@ static int sdr_iterate_cb(
     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 && units_ok) {
     if (src == 1 && reading != NULL && units_ok) {
-        if (base_u == IPMI_SENSOR_UNIT_DEGREES_C) {
-            snprintf(line, sizeof(line), "%s | %.2f degrees C | ok\n", name, *reading);
-        } else {
-            snprintf(line, sizeof(line), "%s | %.2f | ok\n", name, *reading);
-        }
+        const char *ulab = ipmi_unit_label(base_u, pct);
+        snprintf(line, sizeof(line), "%s | %.2f %s | ok\n", name, *reading, ulab);
     } else if (units_ok && 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 (src == 1 && has_type) {
+        if (contains_ci_dimm(name) && stype == IPMI_SENSOR_TYPE_MEMORY && ert == 0x6F) {
+            snprintf(line, sizeof(line), "%s | discrete_mem=0x%04X | ok\n", name, (unsigned)bitmask);
+        } else if (contains_ci_dimm(name) && stype == IPMI_SENSOR_TYPE_ENTITY_PRESENCE && ert == 0x6F) {
+            snprintf(line, sizeof(line), "%s | discrete_presence=0x%04X | ok\n", name, (unsigned)bitmask);
+        } else if (contains_ci_dimm(name) && ert == 0x08) {
+            snprintf(line, sizeof(line), "%s | discrete_devpres=0x%04X | ok\n", name, (unsigned)bitmask);
         } else {
         } else {
-            if (reading) free(reading);
-            return 0;
+            snprintf(line, sizeof(line), "%s | discrete_state=0x%04X | type=0x%02X\n",
+                     name, (unsigned)bitmask, (unsigned)stype);
         }
         }
+    } else if (units_ok && (base_u == IPMI_SENSOR_UNIT_VOLTS || base_u == IPMI_SENSOR_UNIT_AMPS ||
+                            base_u == IPMI_SENSOR_UNIT_WATTS || base_u == IPMI_SENSOR_UNIT_RPM)) {
+        snprintf(line, sizeof(line), "%s | no reading (%s) | ns\n", name, ipmi_unit_label(base_u, pct));
     } else {
     } else {
         if (reading) free(reading);
         if (reading) free(reading);
         return 0;
         return 0;
@@ -2346,6 +2362,136 @@ int c_ipmi_device_info(
             ipmi_fru_ctx_destroy(fru);
             ipmi_fru_ctx_destroy(fru);
             if (!has_any) append_str(out_buf, out_cap, &used, "FRU empty\n");
             if (!has_any) append_str(out_buf, out_cap, &used, "FRU empty\n");
         }
         }
+    } else if (strcmp(kind, "sol") == 0) {
+        uint8_t chs[2] = { 1, 8 };
+        int got_sol = 0;
+        for (int ci = 0; ci < 2 && !got_sol; ci++) {
+            uint8_t ch = chs[ci];
+            uint8_t rq_en[4] = { 0x22, ch, 0x01, 0x00 }; /* Get SOL Config Param: Enable */
+            uint8_t rs_en[16];
+            int rl = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_en, sizeof(rq_en), rs_en, sizeof(rs_en));
+            if (rl >= 4 && rs_en[1] == 0x00) {
+                got_sol = 1;
+                int enabled = (rs_en[3] & 0x01) ? 1 : 0;
+                uint8_t rq_auth[4] = { 0x22, ch, 0x02, 0x00 };
+                uint8_t rs_auth[16];
+                int rla = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_auth, sizeof(rq_auth), rs_auth, sizeof(rs_auth));
+                uint8_t rq_br[4] = { 0x22, ch, 0x05, 0x00 };
+                uint8_t rs_br[16];
+                int rlb = ipmi_cmd_raw(slot->ctx, 0, 0x0C, rq_br, sizeof(rq_br), rs_br, sizeof(rs_br));
+                const char *baud_s = "default";
+                if (rlb >= 4 && rs_br[1] == 0x00) {
+                    switch (rs_br[3] & 0x0F) {
+                        case 0x06: baud_s = "9600"; break;
+                        case 0x07: baud_s = "19200"; break;
+                        case 0x08: baud_s = "38400"; break;
+                        case 0x09: baud_s = "57600"; break;
+                        case 0x0A: baud_s = "115200"; break;
+                        default:   baud_s = "serial-default"; break;
+                    }
+                }
+                char tmp[320];
+                snprintf(
+                    tmp, sizeof(tmp),
+                    "SOL Channel               : %u\n"
+                    "Enabled                   : %s\n"
+                    "Force Encryption          : %s\n"
+                    "Force Authentication      : %s\n"
+                    "Non-Volatile Bit Rate     : %s\n",
+                    (unsigned)ch,
+                    enabled ? "true" : "false",
+                    (rla >= 4 && rs_auth[1] == 0x00 && (rs_auth[3] & 0x80)) ? "true" : "false",
+                    (rla >= 4 && rs_auth[1] == 0x00 && (rs_auth[3] & 0x40)) ? "true" : "false",
+                    baud_s);
+                append_str(out_buf, out_cap, &used, tmp);
+            }
+        }
+        if (!got_sol) {
+            append_str(out_buf, out_cap, &used, "SOL configuration not reported by BMC (NetFn 0x0C Cmd 0x22)\n");
+        }
+    } else if (strcmp(kind, "sessions") == 0) {
+        uint8_t rq[2] = { 0x3D, 0x00 }; /* App NetFn 0x06, Get Session Info (current active session) */
+        uint8_t rs[64];
+        int rl = ipmi_cmd_raw(slot->ctx, 0, 0x06, rq, sizeof(rq), rs, sizeof(rs));
+        if (rl >= 6 && rs[1] == 0x00) {
+            char tmp[320];
+            snprintf(
+                tmp, sizeof(tmp),
+                "Session Handle            : 0x%02X\n"
+                "Session Slots Total       : %u\n"
+                "Active Sessions           : %u\n"
+                "Current User ID           : %u\n"
+                "Current Privilege Level   : %u\n",
+                (unsigned)rs[2],
+                (unsigned)(rs[3] & 0x3F),
+                (unsigned)(rs[4] & 0x3F),
+                (unsigned)(rs[5] & 0x3F),
+                (unsigned)(rl >= 7 ? (rs[6] & 0x0F) : 0));
+            append_str(out_buf, out_cap, &used, tmp);
+        } else {
+            append_str(out_buf, out_cap, &used, "BMC did not return active session table (NetFn 0x06 Cmd 0x3D)\n");
+        }
+    } else if (strcmp(kind, "events") == 0) {
+        fiid_obj_t rs_info = fiid_obj_create(tmpl_cmd_get_sel_info_rs);
+        if (rs_info && ipmi_cmd_get_sel_info(slot->ctx, rs_info) == 0) {
+            uint64_t entries = 0, free_sp = 0, ovf = 0;
+            (void)fiid_obj_get(rs_info, "entries", &entries);
+            (void)fiid_obj_get(rs_info, "free_space", &free_sp);
+            (void)fiid_obj_get(rs_info, "overflow_flag", &ovf);
+            char hdr[256];
+            snprintf(
+                hdr, sizeof(hdr),
+                "SEL Entries               : %llu\n"
+                "SEL Free Space (bytes)    : %llu\n"
+                "SEL Overflow              : %s\n",
+                (unsigned long long)entries,
+                (unsigned long long)free_sp,
+                ovf ? "true" : "false");
+            append_str(out_buf, out_cap, &used, hdr);
+        }
+        if (rs_info) fiid_obj_destroy(rs_info);
+        ipmi_sdr_ctx_t sdr = ipmi_sdr_ctx_create();
+        if (sdr && ensure_sdr_cache_open(sdr, slot->ctx, slot->sdr_cache_path) != 0) {
+            ipmi_sdr_ctx_destroy(sdr);
+            sdr = NULL;
+        }
+        ipmi_sel_ctx_t sel = ipmi_sel_ctx_create(slot->ctx, sdr);
+        if (sel) {
+            SelIterCtx sc = { .out_buf = out_buf, .out_cap = out_cap, .used = used, .count = 0 };
+            if (ipmi_sel_parse(sel, IPMI_SEL_RECORD_ID_FIRST, IPMI_SEL_RECORD_ID_LAST, sel_iterate_cb, &sc) >= 0) {
+                used = sc.used;
+                if (sc.count == 0) {
+                    append_str(out_buf, out_cap, &used, "No SEL event records\n");
+                }
+            }
+            ipmi_sel_ctx_destroy(sel);
+        }
+        if (sdr) {
+            (void)ipmi_sdr_cache_close(sdr);
+            ipmi_sdr_ctx_destroy(sdr);
+        }
+    } else if (strcmp(kind, "fan_mode") == 0) {
+        /* Try Supermicro / Intel / AMI OEM Get Fan Mode first (0x30 0x45 0x00) */
+        uint8_t rq[2] = { 0x45, 0x00 };
+        uint8_t rs[16];
+        int rl = ipmi_cmd_raw(slot->ctx, 0, 0x30, rq, sizeof(rq), rs, sizeof(rs));
+        if (rl >= 3 && rs[1] == 0x00) {
+            const char *mode_s = "unknown";
+            switch (rs[2]) {
+                case 0x00: mode_s = "Standard (0x00)"; break;
+                case 0x01: mode_s = "Full (0x01)"; break;
+                case 0x02: mode_s = "Optimal (0x02)"; break;
+                case 0x04: mode_s = "HeavyIO (0x04)"; break;
+                default:   mode_s = "Custom/Manual"; break;
+            }
+            char tmp[160];
+            snprintf(tmp, sizeof(tmp), "BMC Fan Mode              : %s (raw=0x%02X)\n", mode_s, (unsigned)rs[2]);
+            append_str(out_buf, out_cap, &used, tmp);
+        } else {
+            /* Standard IPMI does not expose a vendor-neutral fan-mode getter; report real status cleanly */
+            append_str(out_buf, out_cap, &used,
+                       "BMC Fan Mode              : OEM readback unsupported (use manual fan_low_speed_on/off or inspect Fan RPM sensors)\n");
+        }
     } else {
     } else {
         rc = -1;
         rc = -1;
     }
     }
@@ -2400,3 +2546,213 @@ uint64_t stl_mem_diff_64b_mask(const uint8_t *a, const uint8_t *b, size_t len) {
     }
     }
     return simd_mem_diff_64b_sse2(a, b, len);
     return simd_mem_diff_64b_sse2(a, b, len);
 }
 }
+
+void stl_batch_mem_diff_64b_masks(
+    const uint8_t *prev_base,
+    const uint8_t *cur_base,
+    size_t         stride,
+    size_t         item_len,
+    size_t         count,
+    uint64_t      *out_masks) {
+    if (!prev_base || !cur_base || !out_masks || count == 0 || item_len == 0 || stride < item_len) {
+        return;
+    }
+    int tier = stl_active_isa_tier();
+    if (tier >= STL_ISA_AVX512) {
+        for (size_t i = 0; i < count; i++) {
+            out_masks[i] = simd_mem_diff_64b_avx512(prev_base + i * stride, cur_base + i * stride, item_len);
+        }
+    } else if (tier >= STL_ISA_AVX2_BMI) {
+        for (size_t i = 0; i < count; i++) {
+            out_masks[i] = simd_mem_diff_64b_avx2(prev_base + i * stride, cur_base + i * stride, item_len);
+        }
+    } else if (tier >= STL_ISA_SSE42_PCLMUL) {
+        for (size_t i = 0; i < count; i++) {
+            out_masks[i] = simd_mem_diff_64b_sse42(prev_base + i * stride, cur_base + i * stride, item_len);
+        }
+    } else {
+        for (size_t i = 0; i < count; i++) {
+            out_masks[i] = simd_mem_diff_64b_sse2(prev_base + i * stride, cur_base + i * stride, item_len);
+        }
+    }
+}
+
+/* =========================================================================
+ * 7. Multi-NIC IPv4 Enumeration & IP_PKTINFO Broadcast UDP Helpers (ProxyDHCP)
+ * ========================================================================= */
+int c_list_ipv4_ifaces(StlNetIface *out_list, int max_count) {
+    if (!out_list || max_count <= 0) return -1;
+    struct ifaddrs *ifas = NULL;
+    if (getifaddrs(&ifas) != 0 || !ifas) return -1;
+
+    int io_fd = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+    int n = 0;
+    for (struct ifaddrs *ifa = ifas; ifa != NULL && n < max_count; ifa = ifa->ifa_next) {
+        if (!ifa->ifa_name || !ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) {
+            continue;
+        }
+        StlNetIface *dst = &out_list[n];
+        memset(dst, 0, sizeof(*dst));
+        snprintf(dst->name, sizeof(dst->name), "%s", ifa->ifa_name);
+        const struct sockaddr_in *sin = (const struct sockaddr_in *)ifa->ifa_addr;
+        dst->ip_be = sin->sin_addr.s_addr;
+        if (ifa->ifa_netmask && ifa->ifa_netmask->sa_family == AF_INET) {
+            const struct sockaddr_in *sm = (const struct sockaddr_in *)ifa->ifa_netmask;
+            dst->mask_be = sm->sin_addr.s_addr;
+        }
+        if (ifa->ifa_ifu.ifu_broadaddr && ifa->ifa_ifu.ifu_broadaddr->sa_family == AF_INET &&
+            (ifa->ifa_flags & IFF_BROADCAST)) {
+            const struct sockaddr_in *sb = (const struct sockaddr_in *)ifa->ifa_ifu.ifu_broadaddr;
+            dst->bcast_be = sb->sin_addr.s_addr;
+        } else {
+            dst->bcast_be = dst->ip_be | (~dst->mask_be);
+        }
+        dst->ifindex     = if_nametoindex(ifa->ifa_name);
+        dst->is_up       = (ifa->ifa_flags & IFF_UP) ? 1 : 0;
+        dst->is_loopback = (ifa->ifa_flags & IFF_LOOPBACK) ? 1 : 0;
+        if (io_fd >= 0) {
+            struct ifreq ifr;
+            memset(&ifr, 0, sizeof(ifr));
+            snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", ifa->ifa_name);
+            if (ioctl(io_fd, SIOCGIFHWADDR, &ifr) == 0) {
+                memcpy(dst->mac, ifr.ifr_hwaddr.sa_data, 6);
+            }
+        }
+        n++;
+    }
+    if (io_fd >= 0) close(io_fd);
+    freeifaddrs(ifas);
+    return n;
+}
+
+int c_udp_bind_dhcp_socket(const char *iface, int port, int reuse_port) {
+    if (port < 0 || port > 65535) return -1;
+    int fd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+    if (fd < 0) return -1;
+
+    int one = 1;
+    (void)setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
+#ifdef SO_REUSEPORT
+    if (reuse_port) {
+        (void)setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));
+    }
+#endif
+    (void)setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one));
+    (void)setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &one, sizeof(one));
+
+    if (iface && iface[0] != '\0') {
+        size_t ilen = strlen(iface);
+        if (ilen < IFNAMSIZ) {
+            /* Best effort: requires CAP_NET_RAW; if EPERM, keep INADDR_ANY and filter by ifindex in userspace */
+            (void)setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface, (socklen_t)(ilen + 1));
+        }
+    }
+
+    struct sockaddr_in addr;
+    memset(&addr, 0, sizeof(addr));
+    addr.sin_family      = AF_INET;
+    addr.sin_addr.s_addr = htonl(INADDR_ANY);
+    addr.sin_port        = htons((uint16_t)port);
+    if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
+        close(fd);
+        return -1;
+    }
+    return fd;
+}
+
+ssize_t c_udp_recv_pktinfo(
+    int       fd,
+    uint8_t  *buf,
+    size_t    cap,
+    uint32_t *out_peer_ip_be,
+    uint16_t *out_peer_port,
+    uint32_t *out_local_ip_be,
+    uint32_t *out_ifindex) {
+    if (fd < 0 || !buf || cap == 0) return -1;
+    if (out_peer_ip_be)  *out_peer_ip_be  = 0;
+    if (out_peer_port)   *out_peer_port   = 0;
+    if (out_local_ip_be) *out_local_ip_be = 0;
+    if (out_ifindex)     *out_ifindex     = 0;
+
+    struct sockaddr_in peer;
+    memset(&peer, 0, sizeof(peer));
+    struct iovec iov = { .iov_base = buf, .iov_len = cap };
+    uint8_t cbuf[256];
+    struct msghdr msg;
+    memset(&msg, 0, sizeof(msg));
+    msg.msg_name       = &peer;
+    msg.msg_namelen    = sizeof(peer);
+    msg.msg_iov        = &iov;
+    msg.msg_iovlen     = 1;
+    msg.msg_control    = cbuf;
+    msg.msg_controllen = sizeof(cbuf);
+
+    ssize_t n = recvmsg(fd, &msg, 0);
+    if (n < 0) {
+        if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
+        return -1;
+    }
+    if (out_peer_ip_be) *out_peer_ip_be = peer.sin_addr.s_addr;
+    if (out_peer_port)  *out_peer_port  = ntohs(peer.sin_port);
+
+    for (struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); cm != NULL; cm = CMSG_NXTHDR(&msg, cm)) {
+        if (cm->cmsg_level == IPPROTO_IP && cm->cmsg_type == IP_PKTINFO &&
+            cm->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo))) {
+            struct in_pktinfo pi;
+            memcpy(&pi, CMSG_DATA(cm), sizeof(pi));
+            if (out_local_ip_be) *out_local_ip_be = pi.ipi_spec_dst.s_addr;
+            if (out_ifindex)     *out_ifindex     = (uint32_t)pi.ipi_ifindex;
+            break;
+        }
+    }
+    return n;
+}
+
+ssize_t c_udp_send_pktinfo(
+    int            fd,
+    const uint8_t *buf,
+    size_t         len,
+    uint32_t       dst_ip_be,
+    uint16_t       dst_port,
+    uint32_t       src_ip_be,
+    uint32_t       ifindex) {
+    if (fd < 0 || !buf || len == 0) return -1;
+    struct sockaddr_in dst;
+    memset(&dst, 0, sizeof(dst));
+    dst.sin_family      = AF_INET;
+    dst.sin_addr.s_addr = dst_ip_be;
+    dst.sin_port        = htons(dst_port);
+
+    struct iovec iov = { .iov_base = (void *)buf, .iov_len = len };
+    uint8_t cbuf[CMSG_SPACE(sizeof(struct in_pktinfo))];
+    memset(cbuf, 0, sizeof(cbuf));
+    struct msghdr msg;
+    memset(&msg, 0, sizeof(msg));
+    msg.msg_name    = &dst;
+    msg.msg_namelen = sizeof(dst);
+    msg.msg_iov     = &iov;
+    msg.msg_iovlen  = 1;
+
+    if (ifindex > 0 || src_ip_be != 0) {
+        msg.msg_control    = cbuf;
+        msg.msg_controllen = sizeof(cbuf);
+        struct cmsghdr *cm = CMSG_FIRSTHDR(&msg);
+        cm->cmsg_level = IPPROTO_IP;
+        cm->cmsg_type  = IP_PKTINFO;
+        cm->cmsg_len   = CMSG_LEN(sizeof(struct in_pktinfo));
+        struct in_pktinfo pi;
+        memset(&pi, 0, sizeof(pi));
+        pi.ipi_ifindex        = (int)ifindex;
+        pi.ipi_spec_dst.s_addr = src_ip_be;
+        memcpy(CMSG_DATA(cm), &pi, sizeof(pi));
+    }
+
+    ssize_t n = sendmsg(fd, &msg, MSG_NOSIGNAL);
+    if (n < 0 && (ifindex > 0 || src_ip_be != 0)) {
+        /* Fallback without IP_PKTINFO if routing table rejects pinned spec_dst (e.g. loopback tests) */
+        msg.msg_control    = NULL;
+        msg.msg_controllen = 0;
+        n = sendmsg(fd, &msg, MSG_NOSIGNAL);
+    }
+    return n;
+}

+ 148 - 71
native/stl_accel/opencl_batch.c

@@ -100,37 +100,70 @@ static const char *k_opencl_src =
     "    float ny   = fabs(((float)row - 7.5f) / 7.5f * 32.0f) / hv;\n"
     "    float ny   = fabs(((float)row - 7.5f) / 7.5f * 32.0f) / hv;\n"
     "    eye_out[ch_idx * 256 + pix] = fmax(0.0f, 1.0f - (nx * nx + ny * ny));\n"
     "    eye_out[ch_idx * 256 + pix] = fmax(0.0f, 1.0f - (nx * nx + ny * ny));\n"
     "}\n"
     "}\n"
-    "__kernel void batch_tile_log_index(\n"
+    "__kernel void batch_tile_line_count(\n"
     "    __global const uchar *buf,\n"
     "    __global const uchar *buf,\n"
     "    uint len,\n"
     "    uint len,\n"
-    "    __global uint *tile_lines,\n"
-    "    __global uchar *tile_tags)\n"
+    "    __global uint *tile_counts)\n"
     "{\n"
     "{\n"
     "    uint tile = get_global_id(0);\n"
     "    uint tile = get_global_id(0);\n"
     "    uint base = tile << 12;\n"
     "    uint base = tile << 12;\n"
     "    uint lim  = base + 4096u;\n"
     "    uint lim  = base + 4096u;\n"
     "    if (lim > len) lim = len;\n"
     "    if (lim > len) lim = len;\n"
     "    uint lines = 0u;\n"
     "    uint lines = 0u;\n"
-    "    uchar tags = 0u;\n"
-    "    uchar prev_cr = 0u;\n"
     "    for (uint i = base; i < lim; i++) {\n"
     "    for (uint i = base; i < lim; i++) {\n"
     "        uchar c = buf[i];\n"
     "        uchar c = buf[i];\n"
-    "        if (c == 10u) {\n"
-    "            if (!prev_cr) lines++;\n"
-    "            prev_cr = 0u;\n"
-    "        } else if (c == 13u) {\n"
-    "            lines++;\n"
-    "            prev_cr = 1u;\n"
-    "        } else {\n"
-    "            prev_cr = 0u;\n"
-    "            if (c == 91u) tags |= 1u;\n"
-    "            else if (c == 62u || c == 35u) tags |= 2u;\n"
-    "            else if (c == 69u || c == 70u || c == 87u || c == 85u) tags |= 4u;\n"
-    "            else if (c >= 48u && c <= 57u) tags |= 8u;\n"
+    "        if (c != 10u && c != 13u) {\n"
+    "            if (i == 0u) {\n"
+    "                lines++;\n"
+    "            } else {\n"
+    "                uchar prev = buf[i - 1u];\n"
+    "                if (prev == 10u || prev == 13u) lines++;\n"
+    "            }\n"
+    "        }\n"
+    "    }\n"
+    "    tile_counts[tile] = lines;\n"
+    "}\n"
+    "__kernel void batch_tile_line_emit(\n"
+    "    __global const uchar *buf,\n"
+    "    uint len,\n"
+    "    __global const uint *tile_base_idx,\n"
+    "    uint max_lines,\n"
+    "    __global uint *out_offsets,\n"
+    "    __global uchar *out_tags)\n"
+    "{\n"
+    "    uint tile = get_global_id(0);\n"
+    "    uint base = tile << 12;\n"
+    "    uint lim  = base + 4096u;\n"
+    "    if (lim > len) lim = len;\n"
+    "    uint out_idx = tile_base_idx[tile];\n"
+    "    if (out_idx >= max_lines) return;\n"
+    "    for (uint i = base; i < lim && out_idx < max_lines; i++) {\n"
+    "        uchar c = buf[i];\n"
+    "        if (c != 10u && c != 13u) {\n"
+    "            int is_start = (i == 0u);\n"
+    "            if (!is_start) {\n"
+    "                uchar prev = buf[i - 1u];\n"
+    "                is_start = (prev == 10u || prev == 13u);\n"
+    "            }\n"
+    "            if (is_start) {\n"
+    "                uchar tag = 0u;\n"
+    "                uint j = i;\n"
+    "                while (j < len) {\n"
+    "                    uchar ch = buf[j];\n"
+    "                    if (ch == 10u || ch == 13u) break;\n"
+    "                    if (ch == 91u) tag |= 1u;\n"
+    "                    else if (ch == 62u || ch == 35u) tag |= 2u;\n"
+    "                    else if (ch == 69u || ch == 70u || ch == 87u || ch == 85u) tag |= 4u;\n"
+    "                    else if (ch >= 48u && ch <= 57u) tag |= 8u;\n"
+    "                    j++;\n"
+    "                }\n"
+    "                out_offsets[out_idx] = i;\n"
+    "                out_tags[out_idx]    = tag;\n"
+    "                out_idx++;\n"
+    "                i = (j > i) ? (j - 1u) : i;\n"
+    "            }\n"
     "        }\n"
     "        }\n"
     "    }\n"
     "    }\n"
-    "    tile_lines[tile] = lines;\n"
-    "    tile_tags[tile]  = tags;\n"
     "}\n"
     "}\n"
     "__kernel void batch_hex_encode(\n"
     "__kernel void batch_hex_encode(\n"
     "    __global const uchar *src,\n"
     "    __global const uchar *src,\n"
@@ -175,10 +208,11 @@ static uint64_t         g_cpu_falls = 0;
 static void            *g_cl_lib    = NULL;
 static void            *g_cl_lib    = NULL;
 static cl_context       g_cl_ctx    = NULL;
 static cl_context       g_cl_ctx    = NULL;
 static cl_command_queue g_cl_queue  = NULL;
 static cl_command_queue g_cl_queue  = NULL;
-static cl_kernel        g_cl_eye_k  = NULL;
-static cl_kernel        g_cl_log_k  = NULL;
-static cl_kernel        g_cl_hex_k  = NULL;
-static cl_kernel        g_cl_crc_k  = NULL;
+static cl_kernel        g_cl_eye_k    = NULL;
+static cl_kernel        g_cl_lcnt_k   = NULL;
+static cl_kernel        g_cl_lemit_k  = NULL;
+static cl_kernel        g_cl_hex_k    = NULL;
+static cl_kernel        g_cl_crc_k    = NULL;
 
 
 static fn_clCreateBuffer          p_clCreateBuffer          = NULL;
 static fn_clCreateBuffer          p_clCreateBuffer          = NULL;
 static fn_clSetKernelArg          p_clSetKernelArg          = NULL;
 static fn_clSetKernelArg          p_clSetKernelArg          = NULL;
@@ -308,14 +342,18 @@ static void init_opencl_once(void) {
     if (!prog || err != CL_SUCCESS) return;
     if (!prog || err != CL_SUCCESS) return;
     if (p_bldProg(prog, 1, &chosen_dev, "-cl-fast-relaxed-math", NULL, NULL) != CL_SUCCESS) return;
     if (p_bldProg(prog, 1, &chosen_dev, "-cl-fast-relaxed-math", NULL, NULL) != CL_SUCCESS) return;
 
 
-    g_cl_ctx   = ctx;
-    g_cl_queue = q;
-    g_cl_eye_k = p_mkKern(prog, "rmt_eye_surface", &err);
-    g_cl_log_k = p_mkKern(prog, "batch_tile_log_index", &err);
-    g_cl_hex_k = p_mkKern(prog, "batch_hex_encode", &err);
-    g_cl_crc_k = p_mkKern(prog, "batch_chunk_crc32_ieee", &err);
-
-    g_cl_info.available     = (g_cl_eye_k != NULL || g_cl_hex_k != NULL || g_cl_crc_k != NULL) ? 1 : 0;
+    g_cl_ctx     = ctx;
+    g_cl_queue   = q;
+    g_cl_eye_k   = p_mkKern(prog, "rmt_eye_surface", &err);
+    g_cl_lcnt_k  = p_mkKern(prog, "batch_tile_line_count", &err);
+    g_cl_lemit_k = p_mkKern(prog, "batch_tile_line_emit", &err);
+    g_cl_hex_k   = p_mkKern(prog, "batch_hex_encode", &err);
+    g_cl_crc_k   = p_mkKern(prog, "batch_chunk_crc32_ieee", &err);
+
+    g_cl_info.available = (g_cl_eye_k != NULL || g_cl_hex_k != NULL || g_cl_crc_k != NULL ||
+                           (g_cl_lcnt_k != NULL && g_cl_lemit_k != NULL))
+                              ? 1
+                              : 0;
     g_cl_info.zero_copy_llc = (unified == CL_TRUE) ? 1 : 0;
     g_cl_info.zero_copy_llc = (unified == CL_TRUE) ? 1 : 0;
     g_cl_info.compute_units = cus;
     g_cl_info.compute_units = cus;
     snprintf(g_cl_info.device_name, sizeof(g_cl_info.device_name), "%s", name_buf);
     snprintf(g_cl_info.device_name, sizeof(g_cl_info.device_name), "%s", name_buf);
@@ -359,7 +397,7 @@ void stl_opencl_query_info(StlOpenClInfo *out_info) {
     out_info->cpu_fallback_count = __atomic_load_n(&g_cpu_falls, __ATOMIC_RELAXED);
     out_info->cpu_fallback_count = __atomic_load_n(&g_cpu_falls, __ATOMIC_RELAXED);
 }
 }
 
 
-/* Kernel 1: 4KB-tile vectorized log index (NO per-newline scalar fallback!) */
+/* Kernel 1: Two-pass 4KB-tile exact per-line GPU index (bit-exact parity with zig_batch_rescan_logs_cpu) */
 size_t stl_batch_rescan_logs(
 size_t stl_batch_rescan_logs(
     const uint8_t *buf_4k_aligned,
     const uint8_t *buf_4k_aligned,
     size_t         len,
     size_t         len,
@@ -372,7 +410,8 @@ size_t stl_batch_rescan_logs(
     if (!buf_4k_aligned || len == 0 || !out_line_offsets || !out_line_tags || max_lines == 0) {
     if (!buf_4k_aligned || len == 0 || !out_line_offsets || !out_line_tags || max_lines == 0) {
         return 0;
         return 0;
     }
     }
-    if (!g_cl_info.available || !g_cl_log_k || len < (size_t)g_cl_info.break_even_bytes ||
+    if (!g_cl_info.available || !g_cl_lcnt_k || !g_cl_lemit_k ||
+        len < (size_t)g_cl_info.break_even_bytes ||
         ((uintptr_t)buf_4k_aligned & 4095u) != 0 || !stl_opencl_has_tdp_headroom()) {
         ((uintptr_t)buf_4k_aligned & 4095u) != 0 || !stl_opencl_has_tdp_headroom()) {
         __atomic_add_fetch(&g_cpu_falls, 1, __ATOMIC_RELAXED);
         __atomic_add_fetch(&g_cpu_falls, 1, __ATOMIC_RELAXED);
         return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
         return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
@@ -380,64 +419,102 @@ size_t stl_batch_rescan_logs(
 
 
     size_t n_tiles = (len + 4095u) >> 12;
     size_t n_tiles = (len + 4095u) >> 12;
     size_t in_bytes = n_tiles << 12;
     size_t in_bytes = n_tiles << 12;
-    size_t l_cap = 0, t_cap = 0;
-    uint32_t *tile_lines = (uint32_t *)stl_aligned_buf_alloc(n_tiles * sizeof(uint32_t), &l_cap);
-    uint8_t  *tile_tags  = (uint8_t *)stl_aligned_buf_alloc(n_tiles, &t_cap);
-    if (!tile_lines || !tile_tags) {
-        stl_aligned_buf_free(tile_lines);
-        stl_aligned_buf_free(tile_tags);
+    size_t cnt_cap = 0, off_cap = 0, tag_cap = 0;
+    uint32_t *tile_counts = (uint32_t *)stl_aligned_buf_alloc(n_tiles * sizeof(uint32_t), &cnt_cap);
+    uint32_t *off_4k      = (uint32_t *)stl_aligned_buf_alloc(max_lines * sizeof(uint32_t), &off_cap);
+    uint8_t  *tag_4k      = (uint8_t *)stl_aligned_buf_alloc(max_lines, &tag_cap);
+    if (!tile_counts || !off_4k || !tag_4k) {
+        stl_aligned_buf_free(tile_counts);
+        stl_aligned_buf_free(off_4k);
+        stl_aligned_buf_free(tag_4k);
         __atomic_add_fetch(&g_cpu_falls, 1, __ATOMIC_RELAXED);
         __atomic_add_fetch(&g_cpu_falls, 1, __ATOMIC_RELAXED);
         return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
         return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
     }
     }
 
 
     int gpu_ok = 0;
     int gpu_ok = 0;
+    size_t total_lines = 0;
     pthread_mutex_lock(&g_cl_mutex);
     pthread_mutex_lock(&g_cl_mutex);
-    cl_int e1 = 0, e2 = 0, e3 = 0;
-    cl_mem m_in = p_clCreateBuffer(g_cl_ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, in_bytes, (void *)buf_4k_aligned, &e1);
-    cl_mem m_ln = p_clCreateBuffer(g_cl_ctx, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, l_cap, tile_lines, &e2);
-    cl_mem m_tg = p_clCreateBuffer(g_cl_ctx, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, t_cap, tile_tags, &e3);
+    cl_int e1 = 0, e2 = 0, e3 = 0, e4 = 0;
+    cl_mem m_in   = p_clCreateBuffer(g_cl_ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, in_bytes, (void *)buf_4k_aligned, &e1);
+    cl_mem m_cnt  = p_clCreateBuffer(g_cl_ctx, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, cnt_cap, tile_counts, &e2);
+    cl_mem m_off  = p_clCreateBuffer(g_cl_ctx, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, off_cap, off_4k, &e3);
+    cl_mem m_tag  = p_clCreateBuffer(g_cl_ctx, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, tag_cap, tag_4k, &e4);
     cl_uint u_len = (cl_uint)(len > 0xFFFFFFFFu ? 0xFFFFFFFFu : len);
     cl_uint u_len = (cl_uint)(len > 0xFFFFFFFFu ? 0xFFFFFFFFu : len);
-    if (m_in && m_ln && m_tg && e1 == CL_SUCCESS && e2 == CL_SUCCESS && e3 == CL_SUCCESS) {
-        if (p_clSetKernelArg(g_cl_log_k, 0, sizeof(cl_mem), &m_in) == CL_SUCCESS &&
-            p_clSetKernelArg(g_cl_log_k, 1, sizeof(cl_uint), &u_len) == CL_SUCCESS &&
-            p_clSetKernelArg(g_cl_log_k, 2, sizeof(cl_mem), &m_ln) == CL_SUCCESS &&
-            p_clSetKernelArg(g_cl_log_k, 3, sizeof(cl_mem), &m_tg) == CL_SUCCESS) {
+    cl_uint u_max = (cl_uint)(max_lines > 0xFFFFFFFFu ? 0xFFFFFFFFu : max_lines);
+
+    if (m_in && m_cnt && m_off && m_tag &&
+        e1 == CL_SUCCESS && e2 == CL_SUCCESS && e3 == CL_SUCCESS && e4 == CL_SUCCESS) {
+        /* Pass 1: parallel per-4KiB-tile line-start count */
+        if (p_clSetKernelArg(g_cl_lcnt_k, 0, sizeof(cl_mem), &m_in) == CL_SUCCESS &&
+            p_clSetKernelArg(g_cl_lcnt_k, 1, sizeof(cl_uint), &u_len) == CL_SUCCESS &&
+            p_clSetKernelArg(g_cl_lcnt_k, 2, sizeof(cl_mem), &m_cnt) == CL_SUCCESS) {
             size_t gws[1] = { n_tiles };
             size_t gws[1] = { n_tiles };
-            if (p_clEnqueueNDRangeKernel(g_cl_queue, g_cl_log_k, 1, NULL, gws, NULL, 0, NULL, NULL) == CL_SUCCESS) {
-                (void)p_clFinish(g_cl_queue);
-                gpu_ok = 1;
+            if (p_clEnqueueNDRangeKernel(g_cl_queue, g_cl_lcnt_k, 1, NULL, gws, NULL, 0, NULL, NULL) == CL_SUCCESS) {
+                cl_int me = 0;
+                uint32_t *mapped_cnt = (uint32_t *)p_clEnqueueMapBuffer(
+                    g_cl_queue, m_cnt, CL_TRUE, CL_MAP_READ | (1ULL << 1), 0, n_tiles * sizeof(uint32_t), 0, NULL, NULL, &me);
+                if (mapped_cnt && me == CL_SUCCESS) {
+                    /* Host exclusive prefix sum over tiny n_tiles array */
+                    uint32_t acc = 0;
+                    for (size_t t = 0; t < n_tiles; t++) {
+                        uint32_t c = mapped_cnt[t];
+                        mapped_cnt[t] = acc;
+                        acc += c;
+                    }
+                    total_lines = (size_t)acc;
+                    if (total_lines > max_lines) total_lines = max_lines;
+                    (void)p_clEnqueueUnmapMemObject(g_cl_queue, m_cnt, mapped_cnt, 0, NULL, NULL);
+
+                    if (total_lines == 0) {
+                        (void)p_clFinish(g_cl_queue);
+                        gpu_ok = 1;
+                    } else if (
+                        p_clSetKernelArg(g_cl_lemit_k, 0, sizeof(cl_mem), &m_in) == CL_SUCCESS &&
+                        p_clSetKernelArg(g_cl_lemit_k, 1, sizeof(cl_uint), &u_len) == CL_SUCCESS &&
+                        p_clSetKernelArg(g_cl_lemit_k, 2, sizeof(cl_mem), &m_cnt) == CL_SUCCESS &&
+                        p_clSetKernelArg(g_cl_lemit_k, 3, sizeof(cl_uint), &u_max) == CL_SUCCESS &&
+                        p_clSetKernelArg(g_cl_lemit_k, 4, sizeof(cl_mem), &m_off) == CL_SUCCESS &&
+                        p_clSetKernelArg(g_cl_lemit_k, 5, sizeof(cl_mem), &m_tag) == CL_SUCCESS &&
+                        p_clEnqueueNDRangeKernel(g_cl_queue, g_cl_lemit_k, 1, NULL, gws, NULL, 0, NULL, NULL) == CL_SUCCESS) {
+                        cl_int mo = 0, mt = 0;
+                        void *moff_p = p_clEnqueueMapBuffer(
+                            g_cl_queue, m_off, CL_TRUE, CL_MAP_READ, 0, total_lines * sizeof(uint32_t), 0, NULL, NULL, &mo);
+                        void *mtag_p = p_clEnqueueMapBuffer(
+                            g_cl_queue, m_tag, CL_TRUE, CL_MAP_READ, 0, total_lines, 0, NULL, NULL, &mt);
+                        if (moff_p && mtag_p && mo == CL_SUCCESS && mt == CL_SUCCESS) {
+                            memcpy(out_line_offsets, moff_p, total_lines * sizeof(uint32_t));
+                            memcpy(out_line_tags, mtag_p, total_lines);
+                            (void)p_clEnqueueUnmapMemObject(g_cl_queue, m_off, moff_p, 0, NULL, NULL);
+                            (void)p_clEnqueueUnmapMemObject(g_cl_queue, m_tag, mtag_p, 0, NULL, NULL);
+                            (void)p_clFinish(g_cl_queue);
+                            gpu_ok = 1;
+                        } else {
+                            if (moff_p) (void)p_clEnqueueUnmapMemObject(g_cl_queue, m_off, moff_p, 0, NULL, NULL);
+                            if (mtag_p) (void)p_clEnqueueUnmapMemObject(g_cl_queue, m_tag, mtag_p, 0, NULL, NULL);
+                        }
+                    }
+                }
             }
             }
         }
         }
     }
     }
-    if (m_in) (void)p_clReleaseMemObject(m_in);
-    if (m_ln) (void)p_clReleaseMemObject(m_ln);
-    if (m_tg) (void)p_clReleaseMemObject(m_tg);
+    if (m_in)  (void)p_clReleaseMemObject(m_in);
+    if (m_cnt) (void)p_clReleaseMemObject(m_cnt);
+    if (m_off) (void)p_clReleaseMemObject(m_off);
+    if (m_tag) (void)p_clReleaseMemObject(m_tag);
     pthread_mutex_unlock(&g_cl_mutex);
     pthread_mutex_unlock(&g_cl_mutex);
 
 
+    stl_aligned_buf_free(tile_counts);
+    stl_aligned_buf_free(off_4k);
+    stl_aligned_buf_free(tag_4k);
+
     if (!gpu_ok) {
     if (!gpu_ok) {
-        stl_aligned_buf_free(tile_lines);
-        stl_aligned_buf_free(tile_tags);
         __atomic_add_fetch(&g_cpu_falls, 1, __ATOMIC_RELAXED);
         __atomic_add_fetch(&g_cpu_falls, 1, __ATOMIC_RELAXED);
         return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
         return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
     }
     }
 
 
-    /* Compact tile summaries cleanly without revisiting tiles that carry zero tags of interest when full */
-    size_t count = 0;
-    for (size_t t = 0; t < n_tiles && count < max_lines; t++) {
-        if (tile_lines[t] == 0 && tile_tags[t] == 0) continue;
-        size_t base = t << 12;
-        size_t lim = base + 4096u;
-        if (lim > len) lim = len;
-        out_line_offsets[count] = (uint32_t)base;
-        out_line_tags[count] = tile_tags[t];
-        count++;
-        (void)lim;
-    }
-    stl_aligned_buf_free(tile_lines);
-    stl_aligned_buf_free(tile_tags);
     __atomic_add_fetch(&g_gpu_hits, 1, __ATOMIC_RELAXED);
     __atomic_add_fetch(&g_gpu_hits, 1, __ATOMIC_RELAXED);
     if (used_gpu) *used_gpu = 1;
     if (used_gpu) *used_gpu = 1;
-    return count;
+    return total_lines;
 }
 }
 
 
 /* Kernel 2: Large-buffer Batch Hex Encode (GPU >= S*, CPU AVX2/SSSE3/SSE2 fallback) */
 /* Kernel 2: Large-buffer Batch Hex Encode (GPU >= S*, CPU AVX2/SSSE3/SSE2 fallback) */

+ 2 - 110
native/stl_accel/scan_asm.S

@@ -2,8 +2,8 @@
  * XJKJ-STL Native Hand-Written x86-64 Assembly Kernels (v0.8.1.19)
  * XJKJ-STL Native Hand-Written x86-64 Assembly Kernels (v0.8.1.19)
  *
  *
  * Strictly retains ONLY:
  * Strictly retains ONLY:
- *   1. asm_xgetbv_eax0: OSXSAVE YMM state check for runtime CPUID dispatch.
- *   2. asm_base64_encode_{sse2,avx2}: Vectorized RFC 4648 Base64 encoders.
+ *   1. asm_xgetbv_eax0: OSXSAVE YMM/ZMM state check for runtime CPUID dispatch.
+ *   2. asm_base64_encode_sse2: Pure SSE2 RFC 4648 Base64 baseline & tail encoder.
  *   3. asm_clean_split_classify_{sse2,sse42,avx2}: Single-pass zero-allocation
  *   3. asm_clean_split_classify_{sse2,sse42,avx2}: Single-pass zero-allocation
  *      serial hot kernel combining printable SIMD scan, UEFI cursor relocation
  *      serial hot kernel combining printable SIMD scan, UEFI cursor relocation
  *      (\x1b[row;colH / \x1b[nC) & ANSI CSI/OSC stripping/folding into clean
  *      (\x1b[row;colH / \x1b[nC) & ANSI CSI/OSC stripping/folding into clean
@@ -253,114 +253,6 @@ asm_base64_encode_sse2:
     ret
     ret
     .size asm_base64_encode_sse2, .-asm_base64_encode_sse2
     .size asm_base64_encode_sse2, .-asm_base64_encode_sse2
 
 
-/* =========================================================================
- * 2b. size_t asm_base64_encode_avx2(const uint8_t *src, size_t len, uint8_t *dst)
- *     AVX2 24 bytes -> 32 Base64 chars per vector iteration + SSE2/scalar tail.
- * ========================================================================= */
-    .pushsection .text.avx2,"ax",@progbits
-    .p2align 4
-    .globl asm_base64_encode_avx2
-    .type asm_base64_encode_avx2, @function
-asm_base64_encode_avx2:
-    movq    %rdx, %r8
-    cmpq    $28, %rsi               /* need >= 28 bytes so 21(%rdi) 4B load is in-bounds */
-    jb      .Lb64_avx2_fallback
-
-    vmovdqa .Lb64_mask_c0(%rip), %ymm6
-    vmovdqa .Lb64_mask_c1(%rip), %ymm7
-
-    .p2align 4
-.Lb64_avx2_loop:
-    /* Load 8 x 24-bit big-endian groups into %ymm0 */
-    movl    (%rdi), %eax
-    movl    3(%rdi), %ecx
-    bswapl  %eax
-    bswapl  %ecx
-    shrl    $8, %eax
-    shrl    $8, %ecx
-    shlq    $32, %rcx
-    orq     %rcx, %rax
-    vmovq   %rax, %xmm0
-
-    movl    6(%rdi), %eax
-    movl    9(%rdi), %ecx
-    bswapl  %eax
-    bswapl  %ecx
-    shrl    $8, %eax
-    shrl    $8, %ecx
-    shlq    $32, %rcx
-    orq     %rcx, %rax
-    vmovq   %rax, %xmm1
-    vpunpcklqdq %xmm1, %xmm0, %xmm0
-
-    movl    12(%rdi), %eax
-    movl    15(%rdi), %ecx
-    bswapl  %eax
-    bswapl  %ecx
-    shrl    $8, %eax
-    shrl    $8, %ecx
-    shlq    $32, %rcx
-    orq     %rcx, %rax
-    vmovq   %rax, %xmm2
-
-    movl    18(%rdi), %eax
-    movl    21(%rdi), %ecx
-    bswapl  %eax
-    bswapl  %ecx
-    shrl    $8, %eax
-    shrl    $8, %ecx
-    shlq    $32, %rcx
-    orq     %rcx, %rax
-    vmovq   %rax, %xmm3
-    vpunpcklqdq %xmm3, %xmm2, %xmm2
-    vinserti128 $1, %xmm2, %ymm0, %ymm0
-
-    vpsrld  $18, %ymm0, %ymm1
-    vpsrld  $4,  %ymm0, %ymm2
-    vpslld  $10, %ymm0, %ymm3
-    vpslld  $24, %ymm0, %ymm0
-    vpand   %ymm6, %ymm1, %ymm1
-    vpand   %ymm7, %ymm2, %ymm2
-    vpand   .Lb64_mask_c2(%rip), %ymm3, %ymm3
-    vpand   .Lb64_mask_c3(%rip), %ymm0, %ymm0
-    vpor    %ymm2, %ymm1, %ymm1
-    vpor    %ymm3, %ymm0, %ymm0
-    vpor    %ymm1, %ymm0, %ymm0
-
-    vpaddb   .Lb64_add65(%rip), %ymm0, %ymm5
-    vpcmpgtb .Lb64_25(%rip), %ymm0, %ymm1
-    vpcmpgtb .Lb64_51(%rip), %ymm0, %ymm2
-    vpcmpeqb .Lb64_62(%rip), %ymm0, %ymm3
-    vpcmpeqb .Lb64_63(%rip), %ymm0, %ymm4
-    vpand    .Lb64_add6(%rip), %ymm1, %ymm1
-    vpand    .Lb64_sub75(%rip), %ymm2, %ymm2
-    vpand    .Lb64_sub15(%rip), %ymm3, %ymm3
-    vpand    .Lb64_sub12(%rip), %ymm4, %ymm4
-    vpaddb   %ymm1, %ymm5, %ymm5
-    vpsubb   %ymm2, %ymm5, %ymm5
-    vpsubb   %ymm3, %ymm5, %ymm5
-    vpsubb   %ymm4, %ymm5, %ymm5
-
-    vmovdqu %ymm5, (%rdx)
-    addq    $24, %rdi
-    addq    $32, %rdx
-    subq    $24, %rsi
-    cmpq    $28, %rsi
-    jae     .Lb64_avx2_loop
-
-    vzeroupper
-.Lb64_avx2_fallback:
-    /* Finish remaining < 28 bytes via pure SSE2/scalar tail */
-    movq    %rdx, %rax
-    subq    %r8, %rax
-    pushq   %rax
-    call    asm_base64_encode_sse2
-    popq    %rcx
-    addq    %rcx, %rax
-    ret
-    .size asm_base64_encode_avx2, .-asm_base64_encode_avx2
-    .popsection
-
 /* =========================================================================
 /* =========================================================================
  * 3. Single-pass zero-allocation clean + UEFI cursor fold + split + classify
  * 3. Single-pass zero-allocation clean + UEFI cursor fold + split + classify
  *
  *

+ 114 - 7
native/stl_accel/simd_kernels.c

@@ -247,8 +247,8 @@ size_t simd_base64_encode_ssse3(const uint8_t *src, size_t len, uint8_t *dst) {
     const __m128i m_t2 = _mm_set1_epi32(0x003F03F0);
     const __m128i m_t2 = _mm_set1_epi32(0x003F03F0);
     const __m128i m_t3 = _mm_set1_epi32(0x01000010);
     const __m128i m_t3 = _mm_set1_epi32(0x01000010);
     const __m128i v_51 = _mm_set1_epi8(51);
     const __m128i v_51 = _mm_set1_epi8(51);
-    const __m128i v_25 = _mm_set1_epi8(25);
-    const __m128i v_13 = _mm_set1_epi8(13);
+    const __m128i v_26 = _mm_set1_epi8(26);
+    const __m128i v_m13 = _mm_set1_epi8(-13);
     const __m128i lut  = _mm_setr_epi8(
     const __m128i lut  = _mm_setr_epi8(
         'a' - 26, '0' - 52, '0' - 52, '0' - 52,
         'a' - 26, '0' - 52, '0' - 52, '0' - 52,
         '0' - 52, '0' - 52, '0' - 52, '0' - 52,
         '0' - 52, '0' - 52, '0' - 52, '0' - 52,
@@ -266,12 +266,9 @@ size_t simd_base64_encode_ssse3(const uint8_t *src, size_t len, uint8_t *dst) {
         __m128i idx = _mm_or_si128(t1, t3);
         __m128i idx = _mm_or_si128(t1, t3);
 
 
         __m128i res = _mm_subs_epu8(idx, v_51);
         __m128i res = _mm_subs_epu8(idx, v_51);
-        __m128i lt26 = _mm_cmpgt_epi8(v_25, idx); /* 0xFF if idx <= 25? wait: 25 > idx means idx <= 24! Use v_26 = 26! */
-        (void)lt26;
-        __m128i is_upper = _mm_cmpgt_epi8(_mm_set1_epi8(26), idx);
-        res = _mm_sub_epi8(res, _mm_and_si128(is_upper, _mm_set1_epi8(-13))); /* +13 -> LUT index 13 = 'A' */
+        __m128i is_upper = _mm_cmpgt_epi8(v_26, idx);
+        res = _mm_sub_epi8(res, _mm_and_si128(is_upper, v_m13));
         __m128i out = _mm_add_epi8(idx, _mm_shuffle_epi8(lut, res));
         __m128i out = _mm_add_epi8(idx, _mm_shuffle_epi8(lut, res));
-        (void)v_25; (void)v_13;
         _mm_storeu_si128((__m128i *)(dst + out_pos), out);
         _mm_storeu_si128((__m128i *)(dst + out_pos), out);
         in_pos += 12;
         in_pos += 12;
         out_pos += 16;
         out_pos += 16;
@@ -463,6 +460,116 @@ uint32_t simd_crc32_ieee_pclmul(uint32_t init_crc, const uint8_t *buf, size_t le
     return ~crc;
     return ~crc;
 }
 }
 
 
+__attribute__((target("avx2,vpclmulqdq,pclmul")))
+uint32_t simd_crc32_ieee_vpclmul(uint32_t init_crc, const uint8_t *buf, size_t len) {
+    if (len < 128u) {
+        return simd_crc32_ieee_pclmul(init_crc, buf, len);
+    }
+    /* 4 x 256-bit (1024-bit = 128B/step) VPCLMULQDQ IEEE 802.3 CRC-32 folding */
+    __m256i y0 = _mm256_loadu_si256((const __m256i *)(buf + 0));
+    __m256i y1 = _mm256_loadu_si256((const __m256i *)(buf + 32));
+    __m256i y2 = _mm256_loadu_si256((const __m256i *)(buf + 64));
+    __m256i y3 = _mm256_loadu_si256((const __m256i *)(buf + 96));
+    __m256i init_v = _mm256_setr_epi32((int)(~init_crc), 0, 0, 0, 0, 0, 0, 0);
+    y0 = _mm256_xor_si256(y0, init_v);
+
+    buf += 128;
+    len -= 128;
+
+    /* k1024_lo = x^(1024+32) mod P' = 0x1e88ef372, k1024_hi = x^(1024-32) mod P' = 0x14a7fe880 */
+    const __m128i k1024_128 = _mm_set_epi64x(0x000000014a7fe880LL, 0x00000001e88ef372LL);
+    const __m256i yk1024    = _mm256_broadcastsi128_si256(k1024_128);
+
+    while (len >= 128u) {
+        __m256i t0 = _mm256_clmulepi64_epi128(y0, yk1024, 0x11);
+        y0 = _mm256_clmulepi64_epi128(y0, yk1024, 0x00);
+        y0 = _mm256_xor_si256(y0, t0);
+        y0 = _mm256_xor_si256(y0, _mm256_loadu_si256((const __m256i *)(buf + 0)));
+
+        __m256i t1 = _mm256_clmulepi64_epi128(y1, yk1024, 0x11);
+        y1 = _mm256_clmulepi64_epi128(y1, yk1024, 0x00);
+        y1 = _mm256_xor_si256(y1, t1);
+        y1 = _mm256_xor_si256(y1, _mm256_loadu_si256((const __m256i *)(buf + 32)));
+
+        __m256i t2 = _mm256_clmulepi64_epi128(y2, yk1024, 0x11);
+        y2 = _mm256_clmulepi64_epi128(y2, yk1024, 0x00);
+        y2 = _mm256_xor_si256(y2, t2);
+        y2 = _mm256_xor_si256(y2, _mm256_loadu_si256((const __m256i *)(buf + 64)));
+
+        __m256i t3 = _mm256_clmulepi64_epi128(y3, yk1024, 0x11);
+        y3 = _mm256_clmulepi64_epi128(y3, yk1024, 0x00);
+        y3 = _mm256_xor_si256(y3, t3);
+        y3 = _mm256_xor_si256(y3, _mm256_loadu_si256((const __m256i *)(buf + 96)));
+
+        buf += 128;
+        len -= 128;
+    }
+
+    /* Fold 1024 bits (y0,y1,y2,y3) -> 512 bits (y2,y3) using 512-bit k1k2 */
+    const __m128i k512_128 = _mm_set_epi64x(0x00000001c6e41596LL, 0x0000000154442bd4LL);
+    const __m256i yk512    = _mm256_broadcastsi128_si256(k512_128);
+    y2 = _mm256_xor_si256(
+        y2,
+        _mm256_xor_si256(_mm256_clmulepi64_epi128(y0, yk512, 0x00),
+                         _mm256_clmulepi64_epi128(y0, yk512, 0x11)));
+    y3 = _mm256_xor_si256(
+        y3,
+        _mm256_xor_si256(_mm256_clmulepi64_epi128(y1, yk512, 0x00),
+                         _mm256_clmulepi64_epi128(y1, yk512, 0x11)));
+
+    if (len >= 64u) {
+        __m256i t2 = _mm256_clmulepi64_epi128(y2, yk512, 0x11);
+        y2 = _mm256_xor_si256(_mm256_clmulepi64_epi128(y2, yk512, 0x00), t2);
+        y2 = _mm256_xor_si256(y2, _mm256_loadu_si256((const __m256i *)(buf + 0)));
+
+        __m256i t3 = _mm256_clmulepi64_epi128(y3, yk512, 0x11);
+        y3 = _mm256_xor_si256(_mm256_clmulepi64_epi128(y3, yk512, 0x00), t3);
+        y3 = _mm256_xor_si256(y3, _mm256_loadu_si256((const __m256i *)(buf + 32)));
+
+        buf += 64;
+        len -= 64;
+    }
+
+    /* Collapse 4 x 128-bit lanes -> 1 x 128-bit lane */
+    __m128i x0 = _mm256_castsi256_si128(y2);
+    __m128i x1 = _mm256_extracti128_si256(y2, 1);
+    __m128i x2 = _mm256_castsi256_si128(y3);
+    __m128i x3 = _mm256_extracti128_si256(y3, 1);
+    const __m128i k3k4 = _mm_set_epi64x(0x00000000ccaa009eLL, 0x00000001751997d0LL);
+    __m128i r;
+    r  = _mm_xor_si128(_mm_clmulepi64_si128(x0, k3k4, 0x00), _mm_clmulepi64_si128(x0, k3k4, 0x11));
+    x1 = _mm_xor_si128(x1, r);
+    r  = _mm_xor_si128(_mm_clmulepi64_si128(x1, k3k4, 0x00), _mm_clmulepi64_si128(x1, k3k4, 0x11));
+    x2 = _mm_xor_si128(x2, r);
+    r  = _mm_xor_si128(_mm_clmulepi64_si128(x2, k3k4, 0x00), _mm_clmulepi64_si128(x2, k3k4, 0x11));
+    x3 = _mm_xor_si128(x3, r);
+
+    while (len >= 16u) {
+        r  = _mm_xor_si128(_mm_clmulepi64_si128(x3, k3k4, 0x00), _mm_clmulepi64_si128(x3, k3k4, 0x11));
+        x3 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)buf), r);
+        buf += 16;
+        len -= 16;
+    }
+
+    const __m128i k5k6    = _mm_set_epi64x(0x00000001db710640LL, 0x0000000163cd6124LL);
+    const __m128i mask32  = _mm_set_epi32(0, -1, 0, -1);
+    r  = _mm_clmulepi64_si128(x3, k3k4, 0x10);
+    x3 = _mm_xor_si128(_mm_srli_si128(x3, 8), r);
+    r  = _mm_clmulepi64_si128(_mm_and_si128(x3, mask32), k5k6, 0x00);
+    x3 = _mm_xor_si128(_mm_srli_si128(x3, 4), r);
+
+    const __m128i barrett = _mm_set_epi64x(0x00000001db710641LL, 0x00000001f7011641LL);
+    r  = _mm_clmulepi64_si128(_mm_and_si128(x3, mask32), barrett, 0x00);
+    r  = _mm_clmulepi64_si128(_mm_and_si128(r, mask32), barrett, 0x10);
+    x3 = _mm_xor_si128(x3, r);
+    uint32_t crc = (uint32_t)_mm_extract_epi32(x3, 1);
+
+    if (len > 0) {
+        return simd_crc32_ieee_slicing8(~crc, buf, len);
+    }
+    return ~crc;
+}
+
 /* =========================================================================
 /* =========================================================================
  * 5. SHA-1: Pure Software Baseline & Intel SHA-NI Hardware (J4125 & N100!)
  * 5. SHA-1: Pure Software Baseline & Intel SHA-NI Hardware (J4125 & N100!)
  * ========================================================================= */
  * ========================================================================= */

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1273 - 894
native/stl_accel/src/actors.rs


+ 439 - 96
native/stl_accel/src/api.rs

@@ -3,8 +3,8 @@
 //          Closed-Loop Thermal Pre-Start Interlock, Excel `.xlsx` Alarm Export & Live Push
 //          Closed-Loop Thermal Pre-Start Interlock, Excel `.xlsx` Alarm Export & Live Push
 
 
 use crate::actors::{
 use crate::actors::{
-    spawn_station_actor, DirtyStationSet, IpmiJob, PushBroadcaster, RingReadReply, StationHandle,
-    StationMsg, StationPublishedView,
+    DirtyStationSet, IpmiJob, PushBroadcaster, RingReadReply, StationHandle, StationMsg,
+    StationPublishedView, StationReactorPool,
 };
 };
 use crate::commands::{AuditRecordDraft, StationCmdExec};
 use crate::commands::{AuditRecordDraft, StationCmdExec};
 use crate::config::{load_config_json, ServerArgs};
 use crate::config::{load_config_json, ServerArgs};
@@ -16,7 +16,8 @@ use crate::results::{now_ms, patch_timing_fields, StationState};
 use crate::storage::{
 use crate::storage::{
     append_debug_log_path, append_system_debug_log, load_audit_logs, load_pxe_state,
     append_debug_log_path, append_system_debug_log, load_audit_logs, load_pxe_state,
     load_station_settings, load_stations_roster, load_web_auth_password, record_audit_log,
     load_station_settings, load_stations_roster, load_web_auth_password, record_audit_log,
-    save_stations_roster, save_web_auth_password, strip_secrets_recursive, unix_ms_to_utc_string,
+    save_station_settings, save_stations_roster, save_web_auth_password, strip_secrets_recursive,
+    unix_ms_to_utc8_string,
 };
 };
 use std::collections::{BTreeMap, HashMap};
 use std::collections::{BTreeMap, HashMap};
 use std::env;
 use std::env;
@@ -62,6 +63,8 @@ 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 reactor_pool: Arc<StationReactorPool>,
+    pub pxe_dhcp_hub: Arc<crate::pxe_dhcp::PxeDhcpHub>,
     pub thermal_hub: Arc<crate::thermal_mcu::ThermalMcuHub>,
     pub thermal_hub: Arc<crate::thermal_mcu::ThermalMcuHub>,
     pub trace_hub: Arc<crate::trace::TraceHub>,
     pub trace_hub: Arc<crate::trace::TraceHub>,
     pub web_password: RwLock<Option<String>>,
     pub web_password: RwLock<Option<String>>,
@@ -81,16 +84,51 @@ impl AppHub {
         let _ = fs::create_dir_all(args.data_dir.join("station-controls"));
         let _ = fs::create_dir_all(args.data_dir.join("station-controls"));
         let pxe_tftp_dir = args.data_dir.join("pxe_tftp");
         let pxe_tftp_dir = args.data_dir.join("pxe_tftp");
         let _ = fs::create_dir_all(&pxe_tftp_dir);
         let _ = fs::create_dir_all(&pxe_tftp_dir);
-        let raw_ring_bytes = args.raw_ring_mb.max(2) * 1024 * 1024;
-        let clean_ring_bytes = args.clean_ring_mb.max(2) * 1024 * 1024;
+
+        // Determine station roster count first so we can auto-scale per-station ring buffers
+        // when scaling to 16..500+ stations on cheap memory-constrained lab hosts.
+        let roster_opt = load_stations_roster(&args.data_dir);
+        let has_authoritative_roster = roster_opt.is_some();
+        let cfg_json_opt = if !has_authoritative_roster {
+            load_config_json(&args.config_path)
+        } else {
+            None
+        };
+        let estimated_stations = if let Some(ref r) = roster_opt {
+            r.len()
+        } else {
+            cfg_json_opt
+                .as_ref()
+                .and_then(|c| c.get_arr("stations"))
+                .map(|a| a.len().max(4))
+                .unwrap_or(4)
+        };
+        let eff_raw_mb = if !args.raw_ring_explicit && estimated_stations >= 16 {
+            2usize
+        } else {
+            args.raw_ring_mb.max(1)
+        };
+        let eff_clean_mb = if !args.clean_ring_explicit && estimated_stations >= 16 {
+            1usize
+        } else {
+            args.clean_ring_mb.max(1)
+        };
+        let raw_ring_bytes = eff_raw_mb * 1024 * 1024;
+        let clean_ring_bytes = eff_clean_mb * 1024 * 1024;
+
+        let cfg_has_explicit_fleet = cfg_json_opt
+            .as_ref()
+            .and_then(|c| c.get_arr("stations"))
+            .map(|a| a.len() >= 4)
+            .unwrap_or(false);
 
 
         let mut raw_stations = BTreeMap::new();
         let mut raw_stations = BTreeMap::new();
-        if let Some(roster) = load_stations_roster(&args.data_dir) {
-            for (sid, name, cpus) in roster {
+        if let Some(roster) = roster_opt {
+            for (sid, name, cpus, bmc_host) in roster {
                 let mut st = StationState::new_with_rings(
                 let mut st = StationState::new_with_rings(
                     &sid,
                     &sid,
                     &name,
                     &name,
-                    "",
+                    &bmc_host,
                     "",
                     "",
                     raw_ring_bytes,
                     raw_ring_bytes,
                     clean_ring_bytes,
                     clean_ring_bytes,
@@ -98,7 +136,7 @@ impl AppHub {
                 st.cpu_count = cpus.max(1);
                 st.cpu_count = cpus.max(1);
                 raw_stations.insert(sid, st);
                 raw_stations.insert(sid, st);
             }
             }
-        } else {
+        } else if !cfg_has_explicit_fleet {
             for (sid, default_name) in [
             for (sid, default_name) in [
                 ("S1", "工位 001"),
                 ("S1", "工位 001"),
                 ("S2", "工位 002"),
                 ("S2", "工位 002"),
@@ -119,7 +157,9 @@ impl AppHub {
             }
             }
         }
         }
 
 
-        if let Some(cfg_json) = load_config_json(&args.config_path) {
+        // Only merge static config file stations when no authoritative dynamic roster exists yet
+        // (prevents deleted stations from resurrecting after restart).
+        if let Some(cfg_json) = cfg_json_opt {
             if let Some(arr) = cfg_json.get_arr("stations") {
             if let Some(arr) = cfg_json.get_arr("stations") {
                 for st_j in arr {
                 for st_j in arr {
                     let sid = st_j.get_str_or("station_id", "");
                     let sid = st_j.get_str_or("station_id", "");
@@ -229,19 +269,66 @@ impl AppHub {
             Arc::clone(&push_hub),
             Arc::clone(&push_hub),
         );
         );
 
 
+        let mut pxe_dhcp_cfg = crate::pxe_dhcp::PxeDhcpConfig::default_with_ports(
+            args.web_listen_port(),
+            args.pxe_dhcp_port,
+            args.pxe_proxy_port,
+        );
+        let state_pxe_mode = pxe_state.get_str_or("pxe_mode", "");
+        pxe_dhcp_cfg.mode = if !args.pxe_mode.is_empty() && args.pxe_mode != "proxy" {
+            crate::pxe_dhcp::PxeBootMode::parse(&args.pxe_mode)
+        } else if !state_pxe_mode.is_empty() {
+            crate::pxe_dhcp::PxeBootMode::parse(&state_pxe_mode)
+        } else {
+            crate::pxe_dhcp::PxeBootMode::parse(&args.pxe_mode)
+        };
+        let state_iface = pxe_state.get_str_or("pxe_iface", "");
+        pxe_dhcp_cfg.iface = if !args.pxe_iface.is_empty() {
+            args.pxe_iface.clone()
+        } else {
+            state_iface
+        };
+        let state_sip = pxe_state.get_str_or("pxe_server_ip", "");
+        if !state_sip.is_empty() && state_sip != "auto" {
+            pxe_dhcp_cfg.server_ip = state_sip;
+        }
+        let state_mask = pxe_state.get_str_or("pxe_subnet_mask", "");
+        if !state_mask.is_empty() {
+            pxe_dhcp_cfg.netmask = state_mask;
+        }
+        let state_rs = pxe_state.get_str_or("pxe_dhcp_range_start", "");
+        if !state_rs.is_empty() {
+            pxe_dhcp_cfg.range_start = state_rs;
+        }
+        let state_re = pxe_state.get_str_or("pxe_dhcp_range_end", "");
+        if !state_re.is_empty() {
+            pxe_dhcp_cfg.range_end = state_re;
+        }
+        if let Some(wl) = pxe_state.get("pxe_mac_whitelist") {
+            pxe_dhcp_cfg.mac_whitelist = crate::pxe_dhcp::parse_mac_whitelist(wl);
+        }
+        let pxe_dhcp_hub = crate::pxe_dhcp::PxeDhcpHub::init(
+            pxe_dhcp_cfg,
+            args.data_dir.clone(),
+            pxe_tftp_dir.clone(),
+            Arc::clone(&trace_hub),
+            enable_hw_bg_probes,
+        );
+
+        let reactor_pool = StationReactorPool::new(
+            args.batch_window_ms,
+            Arc::clone(&contract),
+            args.data_dir.clone(),
+            pxe_tftp_dir.clone(),
+            Arc::clone(&dirty_set),
+            Arc::clone(&push_hub),
+            Arc::clone(&trace_hub),
+            enable_hw_bg_probes,
+        );
+
         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() {
-            let handle = spawn_station_actor(
-                idx,
-                st,
-                Arc::clone(&contract),
-                args.data_dir.clone(),
-                pxe_tftp_dir.clone(),
-                Arc::clone(&dirty_set),
-                Arc::clone(&push_hub),
-                Arc::clone(&trace_hub),
-                enable_hw_bg_probes,
-            );
+            let handle = reactor_pool.register_station(idx, st);
             stations_map.insert(sid, handle);
             stations_map.insert(sid, handle);
         }
         }
 
 
@@ -284,6 +371,8 @@ 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),
+            reactor_pool,
+            pxe_dhcp_hub,
             thermal_hub,
             thermal_hub,
             trace_hub,
             trace_hub,
             web_password: RwLock::new(effective_web_password),
             web_password: RwLock::new(effective_web_password),
@@ -404,6 +493,21 @@ impl AppHub {
             if let Some(tgt) = th.target_c {
             if let Some(tgt) = th.target_c {
                 entry.set("thermal_target_c", JsonVal::Num(tgt as f64));
                 entry.set("thermal_target_c", JsonVal::Num(tgt as f64));
             }
             }
+            // TEMP-1: Fuse live 6400 MCU 0x82 per-DIMM temperatures onto ListStations `dimm_states`
+            if th.online {
+                if let Some(JsonVal::Arr(ref mut dimms)) =
+                    entry.as_obj_mut().and_then(|m| m.get_mut("dimm_states"))
+                {
+                    for (i, dm) in dimms.iter_mut().take(24).enumerate() {
+                        if dm.get_bool("present") == Some(false) {
+                            continue;
+                        }
+                        if let Some(mcu_t) = th.mcu_bmc_temps[i] {
+                            dm.set("temp_c", JsonVal::Num(mcu_t as f64));
+                        }
+                    }
+                }
+            }
         } else {
         } else {
             entry.set("thermal_online", JsonVal::Bool(false));
             entry.set("thermal_online", JsonVal::Bool(false));
             entry.set("thermal_mode", JsonVal::Str("disconnected".to_string()));
             entry.set("thermal_mode", JsonVal::Str("disconnected".to_string()));
@@ -469,29 +573,27 @@ impl AppHub {
         tmp_map.insert(clean_sid.clone(), st);
         tmp_map.insert(clean_sid.clone(), st);
         load_station_settings(&self.data_dir, &mut tmp_map);
         load_station_settings(&self.data_dir, &mut tmp_map);
         let st = tmp_map.remove(&clean_sid).unwrap();
         let st = tmp_map.remove(&clean_sid).unwrap();
+        // Persist initial station settings (including bmc_host) immediately so restarts keep it!
+        save_station_settings(&self.data_dir, &st);
         let actor_idx = map.len();
         let actor_idx = map.len();
-        let handle = spawn_station_actor(
-            actor_idx,
-            st,
-            Arc::clone(&self.contract),
-            self.data_dir.clone(),
-            self.pxe_tftp_dir.clone(),
-            Arc::clone(&self.dirty_set),
-            Arc::clone(&self.push_hub),
-            Arc::clone(&self.trace_hub),
-            self.enable_hw_bg_probes,
-        );
+        let handle = self.reactor_pool.register_station(actor_idx, st);
         self.thermal_hub.add_station(clean_sid.clone(), handle.clone());
         self.thermal_hub.add_station(clean_sid.clone(), handle.clone());
         map.insert(clean_sid.clone(), handle);
         map.insert(clean_sid.clone(), handle);
-        let roster: Vec<(String, String, usize)> = map
+        let roster: Vec<(String, String, usize, String)> = map
             .iter()
             .iter()
             .map(|(k, h)| {
             .map(|(k, h)| {
-                let (nm, cpus) = h
+                let (nm, cpus, bmc) = h
                     .view
                     .view
                     .read()
                     .read()
-                    .map(|v| (v.list_summary.get_str_or("name", k), 2usize))
-                    .unwrap_or_else(|_| (k.clone(), 2usize));
-                (k.clone(), nm, cpus)
+                    .map(|v| {
+                        (
+                            v.list_summary.get_str_or("name", k),
+                            v.cpu_count.max(1),
+                            v.bmc_host.clone(),
+                        )
+                    })
+                    .unwrap_or_else(|_| (k.clone(), 2usize, String::new()));
+                (k.clone(), nm, cpus, bmc)
             })
             })
             .collect();
             .collect();
         drop(map);
         drop(map);
@@ -514,15 +616,21 @@ impl AppHub {
         };
         };
         let _ = handle.send(StationMsg::Shutdown);
         let _ = handle.send(StationMsg::Shutdown);
         self.thermal_hub.remove_station(sid);
         self.thermal_hub.remove_station(sid);
-        let roster: Vec<(String, String, usize)> = map
+        let roster: Vec<(String, String, usize, String)> = map
             .iter()
             .iter()
             .map(|(k, h)| {
             .map(|(k, h)| {
-                let nm = h
+                let (nm, cpus, bmc) = h
                     .view
                     .view
                     .read()
                     .read()
-                    .map(|v| v.list_summary.get_str_or("name", k))
-                    .unwrap_or_else(|_| k.clone());
-                (k.clone(), nm, 2usize)
+                    .map(|v| {
+                        (
+                            v.list_summary.get_str_or("name", k),
+                            v.cpu_count.max(1),
+                            v.bmc_host.clone(),
+                        )
+                    })
+                    .unwrap_or_else(|_| (k.clone(), 2usize, String::new()));
+                (k.clone(), nm, cpus, bmc)
             })
             })
             .collect();
             .collect();
         drop(map);
         drop(map);
@@ -648,17 +756,60 @@ impl AppHub {
             Vec::new()
             Vec::new()
         };
         };
         out.set("audit_logs", JsonVal::Arr(recent_audits));
         out.set("audit_logs", JsonVal::Arr(recent_audits));
-        let pxe_snap = if let Ok(pxe) = self.pxe_state.read() {
+        let mut pxe_snap = if let Ok(pxe) = self.pxe_state.read() {
             build_pxe_snapshot(&pxe)
             build_pxe_snapshot(&pxe)
         } else {
         } else {
             JsonVal::obj()
             JsonVal::obj()
         };
         };
+        let dhcp_live = self.pxe_dhcp_hub.build_status_json();
+        if let JsonVal::Obj(map) = dhcp_live {
+            for (k, v) in map {
+                pxe_snap.set(&k, v);
+            }
+        }
         out.set("pxe_control", pxe_snap);
         out.set("pxe_control", pxe_snap);
         out.set("native_engine", lib::hardware_status_json());
         out.set("native_engine", lib::hardware_status_json());
         patch_timing_fields(&mut out, view.run_started_unix_ms, view.run_ended_unix_ms, now_ms());
         patch_timing_fields(&mut out, view.run_started_unix_ms, view.run_ended_unix_ms, now_ms());
         Ok(out)
         Ok(out)
     }
     }
 
 
+    pub fn get_pxe_status_json(&self) -> JsonVal {
+        let mut snap = if let Ok(pxe) = self.pxe_state.read() {
+            build_pxe_snapshot(&pxe)
+        } else {
+            JsonVal::obj()
+        };
+        let dhcp_live = self.pxe_dhcp_hub.build_status_json();
+        if let JsonVal::Obj(map) = dhcp_live {
+            for (k, v) in map {
+                snap.set(&k, v);
+            }
+        }
+        snap
+    }
+
+    pub fn get_dimm_curve_with_fallback(&self, sid: &str, slot: usize) -> Result<JsonVal, String> {
+        if let Ok(th_curve) = self.thermal_hub.get_dimm_curve(sid, slot) {
+            let has_pts = th_curve
+                .get_arr("points")
+                .map(|a| !a.is_empty())
+                .unwrap_or(false);
+            if has_pts {
+                return Ok(th_curve);
+            }
+        }
+        let Some(handle) = self.get_station_handle(sid) else {
+            return Err(format!("未知工位: {}", sid));
+        };
+        let (tx, rx) = mpsc::channel();
+        if handle.send(StationMsg::GetDimmCurveFallback { slot, reply_tx: tx }) {
+            if let Ok(fb) = rx.recv_timeout(Duration::from_secs(3)) {
+                return Ok(fb);
+            }
+        }
+        self.thermal_hub.get_dimm_curve(sid, slot)
+    }
+
     pub fn export_station_alarms_xlsx(&self, sid: &str) -> Result<(String, Vec<u8>), (String, String)> {
     pub fn export_station_alarms_xlsx(&self, sid: &str) -> Result<(String, Vec<u8>), (String, String)> {
         let view = self.read_station_view(sid)?;
         let view = self.read_station_view(sid)?;
         let mut rows: Vec<crate::xlsx::AlarmXlsxRow> = Vec::new();
         let mut rows: Vec<crate::xlsx::AlarmXlsxRow> = Vec::new();
@@ -669,7 +820,7 @@ impl AppHub {
                 .or_else(|| rec.get_i64("observed_unix_ms"))
                 .or_else(|| rec.get_i64("observed_unix_ms"))
                 .unwrap_or(0);
                 .unwrap_or(0);
             let time_str = if ts > 0 {
             let time_str = if ts > 0 {
-                unix_ms_to_utc_string(ts)
+                unix_ms_to_utc8_string(ts)
             } else {
             } else {
                 String::new()
                 String::new()
             };
             };
@@ -942,6 +1093,9 @@ impl AppHub {
             .map_err(|_| format!("工位 {} Actor 响应超时", sid))?;
             .map_err(|_| format!("工位 {} Actor 响应超时", sid))?;
 
 
         if let Some(new_pxe) = pxe_changed {
         if let Some(new_pxe) = pxe_changed {
+            if method == "ConfigurePxe" {
+                let _ = self.pxe_dhcp_hub.reconfigure(&new_pxe);
+            }
             if let Ok(mut guard) = self.pxe_state.write() {
             if let Ok(mut guard) = self.pxe_state.write() {
                 *guard = new_pxe;
                 *guard = new_pxe;
             }
             }
@@ -986,18 +1140,17 @@ impl AppHub {
                 pass,
                 pass,
             } => {
             } => {
                 let (ipmi_reply_tx, ipmi_reply_rx) = mpsc::channel();
                 let (ipmi_reply_tx, ipmi_reply_rx) = mpsc::channel();
-                handle
-                    .ipmi_tx
-                    .send(IpmiJob::ExplicitCmd {
-                        host,
-                        user,
-                        pass,
-                        kind: kind.clone(),
-                        sub_action: sub_action.clone(),
-                        operator: operator.to_string(),
-                        reply_tx: ipmi_reply_tx,
-                    })
-                    .map_err(|_| format!("工位 {} IPMI Worker 不可用", sid))?;
+                if !handle.send_ipmi(IpmiJob::ExplicitCmd {
+                    host,
+                    user,
+                    pass,
+                    kind: kind.clone(),
+                    sub_action: sub_action.clone(),
+                    operator: operator.to_string(),
+                    reply_tx: ipmi_reply_tx,
+                }) {
+                    return Err(format!("工位 {} IPMI Worker 不可用", sid));
+                }
                 let ipmi_res = ipmi_reply_rx
                 let ipmi_res = ipmi_reply_rx
                     .recv_timeout(Duration::from_secs(20))
                     .recv_timeout(Duration::from_secs(20))
                     .map_err(|_| format!("工位 {} BMC IPMI 操作超时", sid))?;
                     .map_err(|_| format!("工位 {} BMC IPMI 操作超时", sid))?;
@@ -1189,8 +1342,59 @@ impl AppHub {
                 info.set("mode", JsonVal::Str("hardware".to_string()));
                 info.set("mode", JsonVal::Str("hardware".to_string()));
                 info.set("started_unix_ms", JsonVal::Str(self.started_ms.to_string()));
                 info.set("started_unix_ms", JsonVal::Str(self.started_ms.to_string()));
                 info.set("web_auth_enabled", JsonVal::Bool(self.has_web_password()));
                 info.set("web_auth_enabled", JsonVal::Bool(self.has_web_password()));
+                info.set("reactor_shards", JsonVal::Num(self.reactor_pool.shard_count() as f64));
+                info.set("ipmi_workers", JsonVal::Num(self.reactor_pool.ipmi_worker_count() as f64));
                 Ok(info)
                 Ok(info)
             }
             }
+            "GetPxeStatus" => Ok(self.get_pxe_status_json()),
+            "ProbePxeNetwork" => {
+                let iface = params.get_str_or("pxe_iface", &params.get_str_or("iface", ""));
+                let timeout_ms = params.get_i64("timeout_ms").unwrap_or(1500).clamp(300, 3000) as u64;
+                let dhcp_hub = Arc::clone(&self.pxe_dhcp_hub);
+                let (tx, rx) = mpsc::channel();
+                let _ = thread::Builder::new()
+                    .name("stl-pxe-probe".to_string())
+                    .spawn(move || {
+                        let _ = tx.send(dhcp_hub.probe_lan_pxe_environment(&iface, timeout_ms));
+                    });
+                match rx.recv_timeout(Duration::from_secs(6)) {
+                    Ok(res) => Ok(res),
+                    Err(_) => Err(("INTERNAL".to_string(), "局域网 DHCP/PXE 环境探测超时".to_string())),
+                }
+            }
+            "ConfigurePxe" => {
+                let mut pxe_guard = self.pxe_state.write().unwrap_or_else(|e| e.into_inner());
+                let res = crate::pxe::apply_pxe_configuration(
+                    &mut pxe_guard,
+                    params,
+                    &self.data_dir,
+                    &self.pxe_tftp_dir,
+                );
+                drop(pxe_guard);
+                match res {
+                    Ok(snap) => {
+                        let _ = self.pxe_dhcp_hub.reconfigure(&snap);
+                        let merged = self.get_pxe_status_json();
+                        self.commit_audit(
+                            "PXE",
+                            "web",
+                            AuditRecordDraft {
+                                category: "pxe_mt86".to_string(),
+                                action: "configure_pxe".to_string(),
+                                summary: format!(
+                                    "更新内置 PXE 引导服务: mode={} iface={} server_ip={}",
+                                    merged.get_str_or("pxe_mode", "proxy"),
+                                    merged.get_str_or("active_iface", "auto"),
+                                    merged.get_str_or("effective_server_ip", "")
+                                ),
+                                details: merged.clone(),
+                            },
+                        );
+                        Ok(merged)
+                    }
+                    Err(e) => Err(("INVALID_ARGUMENT".to_string(), e)),
+                }
+            }
             "ListStations" => {
             "ListStations" => {
                 let mut out = JsonVal::obj();
                 let mut out = JsonVal::obj();
                 out.set("stations", self.build_stations_list_json());
                 out.set("stations", self.build_stations_list_json());
@@ -1278,8 +1482,7 @@ impl AppHub {
             "GetDimmCurve" => {
             "GetDimmCurve" => {
                 let sid = params.get_str_or("station_id", "S1");
                 let sid = params.get_str_or("station_id", "S1");
                 let slot = params.get_i64("slot").unwrap_or(0).max(0) as usize;
                 let slot = params.get_i64("slot").unwrap_or(0).max(0) as usize;
-                self.thermal_hub
-                    .get_dimm_curve(&sid, slot)
+                self.get_dimm_curve_with_fallback(&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()),
             "GetTraceConfig" => Ok(self.trace_hub.get_config().to_json()),
@@ -1475,44 +1678,91 @@ impl AppHub {
                     .cloned()
                     .cloned()
                     .unwrap_or_else(JsonVal::obj);
                     .unwrap_or_else(JsonVal::obj);
 
 
-                // Pre-start 6400 thermal hood online interlock:
-                // Enforced in Production mode when thermal auto-heat is configured; Engineering mode may pass `skip_thermal_check: true`.
+                // Pre-start 6400 thermal hood online interlock (CL-6):
+                // Covers ControlBootPlan(start|restart), SubmitTaskBatch(profiles|tasks), and ControlTaskBatch(start|resume).
                 let is_run_start = (sub_method == "ControlBootPlan"
                 let is_run_start = (sub_method == "ControlBootPlan"
                     && matches!(
                     && matches!(
                         sub_args.get_str_or("action", "").as_str(),
                         sub_args.get_str_or("action", "").as_str(),
                         "start" | "restart"
                         "start" | "restart"
                     ))
                     ))
+                    || (sub_method == "ControlTaskBatch"
+                        && matches!(
+                            sub_args.get_str_or("action", "").as_str(),
+                            "start" | "resume"
+                        ))
                     || (sub_method == "SubmitTaskBatch"
                     || (sub_method == "SubmitTaskBatch"
                         && sub_args.get_bool("auto_start").unwrap_or(true));
                         && sub_args.get_bool("auto_start").unwrap_or(true));
                 if is_run_start && sub_args.get_bool("skip_thermal_check") != Some(true) {
                 if is_run_start && sub_args.get_bool("skip_thermal_check") != Some(true) {
                     if let Ok(view) = self.read_station_view(&sid) {
                     if let Ok(view) = self.read_station_view(&sid) {
-                        let first_prof = sub_args
+                        let mut check_items: Vec<JsonVal> = Vec::new();
+                        if let Some(arr) = sub_args
                             .get_arr("profiles")
                             .get_arr("profiles")
-                            .and_then(|a| a.first());
-                        let eff_auto = sub_args
-                            .get_bool("thermal_auto_enabled")
-                            .or_else(|| first_prof.and_then(|p| p.get_bool("thermal_auto_enabled")))
-                            .unwrap_or(view.thermal_auto_enabled);
-                        let eff_tgt = sub_args
-                            .get_i64("target_temp_c")
-                            .or_else(|| first_prof.and_then(|p| p.get_i64("target_temp_c")))
-                            .unwrap_or(view.thermal_target_c as i64);
-                        let eff_req = sub_args
-                            .get_bool("require_thermal_online")
-                            .or_else(|| first_prof.and_then(|p| p.get_bool("require_thermal_online")))
-                            .unwrap_or(view.thermal_require_online);
-                        if eff_auto
-                            && eff_tgt > 0
-                            && eff_req
-                            && !self.thermal_hub.is_station_online(&sid)
+                            .or_else(|| sub_args.get_arr("tasks"))
                         {
                         {
-                            return Err((
-                                "THERMAL_OFFLINE".to_string(),
-                                format!(
-                                    "工位 {} 已配置高温目标 {}°C,但 6400 高温罩未连接。产线模式下禁止开测,请先连接高温罩或在工程视图勾选跳过校验。",
-                                    sid, eff_tgt
-                                ),
-                            ));
+                            check_items.extend(arr.iter().cloned());
+                        } else if sub_method == "ControlTaskBatch" {
+                            if let Some(arr) = view.task_batch.get_arr("profiles") {
+                                check_items.extend(arr.iter().cloned());
+                            }
+                        }
+                        let mut need_online_tgt: Option<i64> = None;
+                        if check_items.is_empty() {
+                            let tp = sub_args.get("thermal_policy");
+                            let eff_tgt = sub_args
+                                .get_i64("target_temp_c")
+                                .or_else(|| tp.and_then(|t| t.get_i64("target_temp_c")))
+                                .unwrap_or(view.thermal_target_c as i64);
+                            let eff_auto = sub_args
+                                .get_bool("thermal_auto_enabled")
+                                .or_else(|| tp.and_then(|t| t.get_bool("auto_enabled")))
+                                .unwrap_or(view.thermal_auto_enabled);
+                            let eff_req = sub_args
+                                .get_bool("require_thermal_online")
+                                .or_else(|| tp.and_then(|t| t.get_bool("require_online")))
+                                .unwrap_or(view.thermal_require_online);
+                            if eff_auto && eff_tgt > 0 && eff_req {
+                                need_online_tgt = Some(eff_tgt);
+                            }
+                        } else {
+                            for p in &check_items {
+                                let tp = p.get("thermal_policy");
+                                let p_tgt = p
+                                    .get_i64("target_temp_c")
+                                    .or_else(|| tp.and_then(|t| t.get_i64("target_temp_c")))
+                                    .or_else(|| sub_args.get_i64("target_temp_c"))
+                                    .unwrap_or(view.thermal_target_c as i64);
+                                let p_auto = p
+                                    .get_bool("thermal_auto_enabled")
+                                    .or_else(|| tp.and_then(|t| t.get_bool("auto_enabled")))
+                                    .or_else(|| sub_args.get_bool("thermal_auto_enabled"))
+                                    .unwrap_or(if p.get_i64("target_temp_c").is_some()
+                                        || tp.and_then(|t| t.get_i64("target_temp_c")).is_some()
+                                    {
+                                        p_tgt > 0
+                                    } else {
+                                        view.thermal_auto_enabled
+                                    });
+                                let p_req = p
+                                    .get_bool("require_thermal_online")
+                                    .or_else(|| tp.and_then(|t| t.get_bool("require_online")))
+                                    .or_else(|| sub_args.get_bool("require_thermal_online"))
+                                    .unwrap_or(view.thermal_require_online);
+                                if p_auto && p_tgt > 0 && p_req {
+                                    need_online_tgt = Some(p_tgt);
+                                    break;
+                                }
+                            }
+                        }
+                        if let Some(eff_tgt) = need_online_tgt {
+                            if !self.thermal_hub.is_station_online(&sid) {
+                                return Err((
+                                    "THERMAL_OFFLINE".to_string(),
+                                    format!(
+                                        "工位 {} 已配置高温目标 {}°C,但 6400 高温罩未连接。产线模式下禁止开测,请先连接高温罩或在工程视图勾选跳过校验。",
+                                        sid, eff_tgt
+                                    ),
+                                ));
+                            }
                         }
                         }
                     }
                     }
                 }
                 }
@@ -1721,11 +1971,12 @@ impl AppHub {
     }
     }
 }
 }
 
 
-fn read_ws_frame(stream: &mut TcpStream) -> Option<(u8, Vec<u8>)> {
+fn read_single_ws_frame(stream: &mut TcpStream) -> Option<(bool, u8, Vec<u8>)> {
     let mut hdr = [0u8; 2];
     let mut hdr = [0u8; 2];
     if stream.read_exact(&mut hdr).is_err() {
     if stream.read_exact(&mut hdr).is_err() {
         return None;
         return None;
     }
     }
+    let fin = (hdr[0] & 0x80) != 0;
     let opcode = hdr[0] & 0x0f;
     let opcode = hdr[0] & 0x0f;
     let masked = (hdr[1] & 0x80) != 0;
     let masked = (hdr[1] & 0x80) != 0;
     let mut payload_len = (hdr[1] & 0x7f) as usize;
     let mut payload_len = (hdr[1] & 0x7f) as usize;
@@ -1758,7 +2009,35 @@ fn read_ws_frame(stream: &mut TcpStream) -> Option<(u8, Vec<u8>)> {
             *b ^= mask_key[i & 3];
             *b ^= mask_key[i & 3];
         }
         }
     }
     }
-    Some((opcode, payload))
+    Some((fin, opcode, payload))
+}
+
+/// RFC 6455 WebSocket frame reader supporting fragmented messages (`FIN=0` + `0x0` continuation frames).
+fn read_ws_frame(stream: &mut TcpStream) -> Option<(u8, Vec<u8>)> {
+    let (fin, opcode, mut acc) = read_single_ws_frame(stream)?;
+    if fin || (opcode & 0x08) != 0 {
+        return Some((opcode, acc));
+    }
+    loop {
+        let (next_fin, next_op, chunk) = read_single_ws_frame(stream)?;
+        if (next_op & 0x08) != 0 {
+            // Interleaved control frame (e.g. close/ping/pong): handle close immediately, otherwise skip
+            if next_op == 0x8 {
+                return Some((0x8, chunk));
+            }
+            continue;
+        }
+        if next_op != 0x0 {
+            return None;
+        }
+        if acc.len().saturating_add(chunk.len()) > 8 * 1024 * 1024 {
+            return None;
+        }
+        acc.extend_from_slice(&chunk);
+        if next_fin {
+            return Some((opcode, acc));
+        }
+    }
 }
 }
 
 
 /// Zero-copy WebSocket frame sender using `stl_ws_writev2` (`writev` header + payload)
 /// Zero-copy WebSocket frame sender using `stl_ws_writev2` (`writev` header + payload)
@@ -2034,6 +2313,9 @@ impl AppHub {
     }
     }
 
 
     pub fn change_web_password(&self, current: &str, new_pw: &str) -> Result<(), String> {
     pub fn change_web_password(&self, current: &str, new_pw: &str) -> Result<(), String> {
+        if !self.has_web_password() {
+            return Err("当前已关闭登录认证 (--web-password disabled),无需修改管理密码".to_string());
+        }
         if new_pw.trim().len() < 4 {
         if new_pw.trim().len() < 4 {
             return Err("新密码长度至少为 4 位".to_string());
             return Err("新密码长度至少为 4 位".to_string());
         }
         }
@@ -2042,8 +2324,14 @@ impl AppHub {
         }
         }
         save_web_auth_password(&self.data_dir, new_pw)
         save_web_auth_password(&self.data_dir, new_pw)
             .map_err(|e| format!("保存密码文件失败: {}", e))?;
             .map_err(|e| format!("保存密码文件失败: {}", e))?;
-        let mut guard = self.web_password.write().unwrap_or_else(|e| e.into_inner());
-        *guard = Some(new_pw.to_string());
+        {
+            let mut guard = self.web_password.write().unwrap_or_else(|e| e.into_inner());
+            *guard = Some(new_pw.to_string());
+        }
+        // Invalidate all prior sessions immediately so old cookies cannot persist after password rotation
+        if let Ok(mut sessions) = self.web_sessions.lock() {
+            sessions.clear();
+        }
         Ok(())
         Ok(())
     }
     }
 
 
@@ -2268,6 +2556,56 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
         }
         }
     }
     }
 
 
+    let http_t0_us = unsafe { lib::stl_mono_us() };
+
+    // Unauthenticated read-only UEFI HTTP Boot & per-MAC mt86.cfg route (`GET|HEAD /pxe/<filename>`):
+    // Allows diskless UEFI firmware (HTTPClient / arch 16) to boot `118.efi` and pull per-station `mt86.cfg` over TCP HTTP!
+    if (method == "GET" || method == "HEAD") && path_only.starts_with("/pxe/") {
+        let req_name = path_only.trim_start_matches("/pxe/");
+        let peer_ip = stream
+            .peer_addr()
+            .map(|a| a.ip().to_string())
+            .unwrap_or_default();
+        let local_ip = stream
+            .local_addr()
+            .map(|a| a.ip().to_string())
+            .unwrap_or_default();
+        let dur_us = unsafe { lib::stl_mono_us() }.saturating_sub(http_t0_us);
+        match crate::pxe::resolve_pxe_payload(&hub, req_name, &peer_ip, &local_ip) {
+            Some(bytes) => {
+                let ctype = if req_name.to_ascii_lowercase().ends_with(".cfg") {
+                    "text/plain; charset=utf-8"
+                } else {
+                    "application/octet-stream"
+                };
+                let hdr = format!(
+                    "HTTP/1.1 200 OK\r\nContent-Type: {}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
+                    ctype,
+                    bytes.len()
+                );
+                let _ = stream.write_all(hdr.as_bytes());
+                if method == "GET" {
+                    let _ = stream.write_all(&bytes);
+                }
+                let _ = stream.flush();
+                hub.trace_hub.record_http_event(method, path_only, 200, dur_us);
+                hub.trace_hub.record_hardware_event(
+                    "PXE",
+                    "http_boot",
+                    "serve_file",
+                    &format!("peer={} file={} bytes={}", peer_ip, req_name, bytes.len()),
+                );
+            }
+            None => {
+                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());
+                let _ = stream.flush();
+                hub.trace_hub.record_http_event(method, path_only, 404, dur_us);
+            }
+        }
+        return;
+    }
+
     if method == "POST" && path_only == "/api/auth/login" {
     if method == "POST" && path_only == "/api/auth/login" {
         if content_length > 4096 {
         if content_length > 4096 {
             let body = r#"{"ok":false,"error":{"code":"INVALID_ARGUMENT","message":"请求体过大"}}"#;
             let body = r#"{"ok":false,"error":{"code":"INVALID_ARGUMENT","message":"请求体过大"}}"#;
@@ -2641,18 +2979,19 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
     if path_only == "/api/trace/bundle" {
     if path_only == "/api/trace/bundle" {
         let sid = parse_query_param(raw_target, "station_id");
         let sid = parse_query_param(raw_target, "station_id");
         let day = parse_query_param(raw_target, "day");
         let day = parse_query_param(raw_target, "day");
-        match hub.trace_hub.build_diagnostic_bundle_tar(&sid, &day) {
-            Ok((fname, bytes)) => {
+        match hub.trace_hub.prepare_diagnostic_bundle_plan(&sid, &day) {
+            Ok((fname, total_sz, plan)) => {
                 let hdr = format!(
                 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",
                     "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(),
+                    total_sz,
                     fname
                     fname
                 );
                 );
-                let _ = stream.write_all(hdr.as_bytes());
-                if method == "GET" {
-                    let _ = stream.write_all(&bytes);
+                if stream.write_all(hdr.as_bytes()).is_ok() && method == "GET" {
+                    let _ = crate::trace::TraceHub::stream_diagnostic_bundle_tar(&plan, &mut stream);
                 }
                 }
                 let _ = stream.flush();
                 let _ = stream.flush();
+                let dur_us = unsafe { lib::stl_mono_us() }.saturating_sub(http_t0_us);
+                hub.trace_hub.record_http_event(method, path_only, 200, dur_us);
                 return;
                 return;
             }
             }
             Err(msg) => {
             Err(msg) => {
@@ -2666,6 +3005,8 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
                     let _ = stream.write_all(&body);
                     let _ = stream.write_all(&body);
                 }
                 }
                 let _ = stream.flush();
                 let _ = stream.flush();
+                let dur_us = unsafe { lib::stl_mono_us() }.saturating_sub(http_t0_us);
+                hub.trace_hub.record_http_event(method, path_only, 500, dur_us);
                 return;
                 return;
             }
             }
         }
         }
@@ -2716,7 +3057,7 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
             let slot_idx = parse_query_param(raw_target, "slot")
             let slot_idx = parse_query_param(raw_target, "slot")
                 .parse::<usize>()
                 .parse::<usize>()
                 .unwrap_or(0);
                 .unwrap_or(0);
-            match hub.thermal_hub.get_dimm_curve(&sid, slot_idx) {
+            match hub.get_dimm_curve_with_fallback(&sid, slot_idx) {
                 Ok(data) => {
                 Ok(data) => {
                     let body = data.to_json().into_bytes();
                     let body = data.to_json().into_bytes();
                     let hdr = format!(
                     let hdr = format!(
@@ -2909,4 +3250,6 @@ pub fn handle_http_client(mut stream: TcpStream, hub: Arc<AppHub>) {
         let _ = stream.write_all(&body);
         let _ = stream.write_all(&body);
     }
     }
     let _ = stream.flush();
     let _ = stream.flush();
+    let dur_us = unsafe { lib::stl_mono_us() }.saturating_sub(http_t0_us);
+    hub.trace_hub.record_http_event(method, path_only, 200, dur_us);
 }
 }

+ 41 - 9
native/stl_accel/src/commands.rs

@@ -7,7 +7,6 @@ use crate::json::JsonVal;
 use crate::lib;
 use crate::lib;
 use crate::pxe::{
 use crate::pxe::{
     apply_pxe_configuration, render_mt86_cfg_text, sync_mt86_cfg_all_candidates,
     apply_pxe_configuration, render_mt86_cfg_text, sync_mt86_cfg_all_candidates,
-    STAGE1_PXE_COMMANDS,
 };
 };
 use crate::results::{now_ms, AsyncScriptStep, StationState};
 use crate::results::{now_ms, AsyncScriptStep, StationState};
 use crate::storage::save_station_settings;
 use crate::storage::save_station_settings;
@@ -919,6 +918,18 @@ pub fn handle_station_command_nonblocking(
             });
             });
             let mut meta = JsonVal::obj();
             let mut meta = JsonVal::obj();
             meta.set("test_command", JsonVal::Str(test_cmd));
             meta.set("test_command", JsonVal::Str(test_cmd));
+            if st.task_batch.get_str_or("state", "idle") != "running" {
+                st.single_run_active = true;
+                if st.single_run_id.is_empty() {
+                    st.single_run_id = format!("RUN-{}-{}", st.station_id, now_ms());
+                }
+                if st.run_started_unix_ms <= 0 {
+                    st.start_run_timing(now_ms(), "StartAmt");
+                } else {
+                    st.run_ended_unix_ms = 0;
+                }
+                st.task_status = "running".to_string();
+            }
             let timeout_ms = (steps.len() as u64) * 5000 + 2000;
             let timeout_ms = (steps.len() as u64) * 5000 + 2000;
             let (tx, rx) = mpsc::channel();
             let (tx, rx) = mpsc::channel();
             start_async_script(
             start_async_script(
@@ -1027,6 +1038,13 @@ pub fn handle_station_command_nonblocking(
                     ("interactive_start_mt", mt_steps, true, m, true)
                     ("interactive_start_mt", mt_steps, true, m, true)
                 };
                 };
             meta.set("command", JsonVal::Str(raw_path));
             meta.set("command", JsonVal::Str(raw_path));
+            if st.task_batch.get_str_or("state", "idle") != "running" {
+                st.single_run_active = true;
+                if st.single_run_id.is_empty() {
+                    st.single_run_id = format!("RUN-{}-{}", st.station_id, now_ms());
+                }
+                st.task_status = "running".to_string();
+            }
             if st.run_started_unix_ms <= 0 {
             if st.run_started_unix_ms <= 0 {
                 st.start_run_timing(now_ms(), "StartMt");
                 st.start_run_timing(now_ms(), "StartMt");
             } else {
             } else {
@@ -1164,20 +1182,23 @@ pub fn handle_station_command_nonblocking(
         }
         }
         "ConfigureThermalPolicy" => {
         "ConfigureThermalPolicy" => {
             let patch = args.get("thermal_policy").unwrap_or(args);
             let patch = args.get("thermal_policy").unwrap_or(args);
-            if let Some(en) = patch
+            let explicit_auto = patch
                 .get_bool("auto_enabled")
                 .get_bool("auto_enabled")
-                .or_else(|| patch.get_bool("thermal_auto_enabled"))
-            {
-                st.thermal_auto_enabled = en;
-            }
+                .or_else(|| patch.get_bool("thermal_auto_enabled"));
             if let Some(tc) = patch
             if let Some(tc) = patch
                 .get_i64("target_temp_c")
                 .get_i64("target_temp_c")
                 .or_else(|| patch.get_i64("target_temp"))
                 .or_else(|| patch.get_i64("target_temp"))
             {
             {
                 if (0..=254).contains(&tc) {
                 if (0..=254).contains(&tc) {
                     st.thermal_target_c = tc as u8;
                     st.thermal_target_c = tc as u8;
+                    if explicit_auto.is_none() {
+                        st.thermal_auto_enabled = tc > 0;
+                    }
                 }
                 }
             }
             }
+            if let Some(en) = explicit_auto {
+                st.thermal_auto_enabled = en;
+            }
             if let Some(req) = patch
             if let Some(req) = patch
                 .get_bool("require_online")
                 .get_bool("require_online")
                 .or_else(|| patch.get_bool("require_thermal_online"))
                 .or_else(|| patch.get_bool("require_thermal_online"))
@@ -1712,13 +1733,24 @@ 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");
+                let eff_sip = pxe_snap.get_str_or("pxe_server_ip", "");
+                if !eff_sip.is_empty() {
+                    st.pxe_server_ip = eff_sip.clone();
+                }
                 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 "));
                     if pxe_snap.get_bool("stage1_pxe_enabled").unwrap_or(false) {
                     if pxe_snap.get_bool("stage1_pxe_enabled").unwrap_or(false) {
-                        for cmd in STAGE1_PXE_COMMANDS {
-                            st.uip_raw_commands.push(cmd.to_string());
+                        let sip = if eff_sip.is_empty() {
+                            st.pxe_server_ip.as_str()
+                        } else {
+                            eff_sip.as_str()
+                        };
+                        let mask = pxe_snap.get_str_or("pxe_subnet_mask", "255.255.255.0");
+                        let cip = pxe_snap.get_str_or("pxe_client_ip", "192.168.0.160");
+                        let efi = pxe_snap.get_str_or("active_efi", crate::pxe::PXE_EFI_FILENAME);
+                        for cmd in crate::pxe::build_stage1_pxe_commands(sip, &mask, &cip, &efi) {
+                            st.uip_raw_commands.push(cmd);
                         }
                         }
                     }
                     }
                     st.clear_batch_workspace();
                     st.clear_batch_workspace();

+ 87 - 9
native/stl_accel/src/config.rs

@@ -38,7 +38,14 @@ pub struct ServerArgs {
     pub web_password: Option<String>,
     pub web_password: Option<String>,
     pub raw_ring_mb: usize,
     pub raw_ring_mb: usize,
     pub clean_ring_mb: usize,
     pub clean_ring_mb: usize,
+    pub raw_ring_explicit: bool,
+    pub clean_ring_explicit: bool,
     pub detail_log_cli: Option<bool>,
     pub detail_log_cli: Option<bool>,
+    pub pxe_mode: String,
+    pub pxe_iface: String,
+    pub pxe_dhcp_port: u16,
+    pub pxe_proxy_port: u16,
+    pub batch_window_ms: u64,
     pub version: String,
     pub version: String,
     pub commit: String,
     pub commit: String,
 }
 }
@@ -53,16 +60,18 @@ impl ServerArgs {
         let mut web_dir = PathBuf::from("web");
         let mut web_dir = PathBuf::from("web");
         let mut contracts_path = PathBuf::from("contracts/firmware-vd012.json");
         let mut contracts_path = PathBuf::from("contracts/firmware-vd012.json");
         let mut web_password_cli: Option<String> = None;
         let mut web_password_cli: Option<String> = None;
-        let mut raw_ring_mb: usize = env::var("STL_RAW_RING_MB")
+        let raw_env = env::var("STL_RAW_RING_MB")
             .ok()
             .ok()
             .and_then(|s| s.trim().parse::<usize>().ok())
             .and_then(|s| s.trim().parse::<usize>().ok())
-            .filter(|&v| v >= 2)
-            .unwrap_or(16);
-        let mut clean_ring_mb: usize = env::var("STL_CLEAN_RING_MB")
+            .filter(|&v| v >= 1);
+        let clean_env = env::var("STL_CLEAN_RING_MB")
             .ok()
             .ok()
             .and_then(|s| s.trim().parse::<usize>().ok())
             .and_then(|s| s.trim().parse::<usize>().ok())
-            .filter(|&v| v >= 2)
-            .unwrap_or(8);
+            .filter(|&v| v >= 1);
+        let mut raw_ring_explicit = raw_env.is_some();
+        let mut clean_ring_explicit = clean_env.is_some();
+        let mut raw_ring_mb: usize = raw_env.unwrap_or(16);
+        let mut clean_ring_mb: usize = clean_env.unwrap_or(8);
         let mut detail_log_cli: Option<bool> = env::var("STL_DETAIL_LOG").ok().and_then(|v| {
         let mut detail_log_cli: Option<bool> = env::var("STL_DETAIL_LOG").ok().and_then(|v| {
             match v.trim().to_ascii_lowercase().as_str() {
             match v.trim().to_ascii_lowercase().as_str() {
                 "1" | "true" | "on" | "yes" => Some(true),
                 "1" | "true" | "on" | "yes" => Some(true),
@@ -70,6 +79,24 @@ impl ServerArgs {
                 _ => None,
                 _ => None,
             }
             }
         });
         });
+        let mut pxe_mode = env::var("STL_PXE_MODE")
+            .ok()
+            .filter(|s| !s.trim().is_empty())
+            .unwrap_or_else(|| "proxy".to_string());
+        let mut pxe_iface = env::var("STL_PXE_IFACE").unwrap_or_default();
+        let mut pxe_dhcp_port: u16 = env::var("STL_PXE_DHCP_PORT")
+            .ok()
+            .and_then(|s| s.trim().parse::<u16>().ok())
+            .unwrap_or(67);
+        let mut pxe_proxy_port: u16 = env::var("STL_PXE_PROXY_PORT")
+            .ok()
+            .and_then(|s| s.trim().parse::<u16>().ok())
+            .unwrap_or(4011);
+        let mut batch_window_ms: u64 = env::var("STL_BATCH_WINDOW_MS")
+            .ok()
+            .and_then(|s| s.trim().parse::<u64>().ok())
+            .map(|v| v.clamp(10, 500))
+            .unwrap_or(100);
 
 
         let mut i = 1;
         let mut i = 1;
         while i < args.len() {
         while i < args.len() {
@@ -106,14 +133,16 @@ impl ServerArgs {
                     let v = args[i + 1]
                     let v = args[i + 1]
                         .parse::<usize>()
                         .parse::<usize>()
                         .map_err(|_| format!("无效 --raw-ring-mb 参数: {}", args[i + 1]))?;
                         .map_err(|_| format!("无效 --raw-ring-mb 参数: {}", args[i + 1]))?;
-                    raw_ring_mb = v.max(2);
+                    raw_ring_mb = v.max(1);
+                    raw_ring_explicit = true;
                     i += 2;
                     i += 2;
                 }
                 }
                 "--clean-ring-mb" if i + 1 < args.len() => {
                 "--clean-ring-mb" if i + 1 < args.len() => {
                     let v = args[i + 1]
                     let v = args[i + 1]
                         .parse::<usize>()
                         .parse::<usize>()
                         .map_err(|_| format!("无效 --clean-ring-mb 参数: {}", args[i + 1]))?;
                         .map_err(|_| format!("无效 --clean-ring-mb 参数: {}", args[i + 1]))?;
-                    clean_ring_mb = v.max(2);
+                    clean_ring_mb = v.max(1);
+                    clean_ring_explicit = true;
                     i += 2;
                     i += 2;
                 }
                 }
                 "--detail-log" if i + 1 < args.len() => {
                 "--detail-log" if i + 1 < args.len() => {
@@ -129,9 +158,43 @@ impl ServerArgs {
                     };
                     };
                     i += 2;
                     i += 2;
                 }
                 }
+                "--pxe-mode" if i + 1 < args.len() => {
+                    let m = args[i + 1].trim().to_ascii_lowercase();
+                    if !matches!(m.as_str(), "proxy" | "isolated" | "disabled") {
+                        return Err(format!(
+                            "无效 --pxe-mode 参数 '{}',仅支持 proxy|isolated|disabled",
+                            m
+                        ));
+                    }
+                    pxe_mode = m;
+                    i += 2;
+                }
+                "--pxe-iface" if i + 1 < args.len() => {
+                    pxe_iface = args[i + 1].trim().to_string();
+                    i += 2;
+                }
+                "--pxe-dhcp-port" if i + 1 < args.len() => {
+                    pxe_dhcp_port = args[i + 1]
+                        .parse::<u16>()
+                        .map_err(|_| format!("无效 --pxe-dhcp-port 参数: {}", args[i + 1]))?;
+                    i += 2;
+                }
+                "--pxe-proxy-port" if i + 1 < args.len() => {
+                    pxe_proxy_port = args[i + 1]
+                        .parse::<u16>()
+                        .map_err(|_| format!("无效 --pxe-proxy-port 参数: {}", args[i + 1]))?;
+                    i += 2;
+                }
+                "--batch-window-ms" if i + 1 < args.len() => {
+                    let v = args[i + 1]
+                        .parse::<u64>()
+                        .map_err(|_| format!("无效 --batch-window-ms 参数: {}", args[i + 1]))?;
+                    batch_window_ms = v.clamp(10, 500);
+                    i += 2;
+                }
                 other => {
                 other => {
                     return Err(format!(
                     return Err(format!(
-                        "未知命令行参数 '{}'。支持参数: --config <path> --data-dir <dir> --web-listen <addr> --tftp-listen <udp_addr|disabled> --web-dir <dir> --contracts <path> --web-password <pass|disabled> --raw-ring-mb <MB> --clean-ring-mb <MB> --detail-log <on|off>",
+                        "未知命令行参数 '{}'。支持参数: --config <path> --data-dir <dir> --web-listen <addr> --tftp-listen <udp_addr|disabled> --web-dir <dir> --contracts <path> --web-password <pass|disabled> --raw-ring-mb <MB> --clean-ring-mb <MB> --detail-log <on|off> --pxe-mode <proxy|isolated|disabled> --pxe-iface <name> --pxe-dhcp-port <u16> --pxe-proxy-port <u16> --batch-window-ms <ms>",
                         other
                         other
                     ));
                     ));
                 }
                 }
@@ -162,11 +225,26 @@ impl ServerArgs {
             web_password,
             web_password,
             raw_ring_mb,
             raw_ring_mb,
             clean_ring_mb,
             clean_ring_mb,
+            raw_ring_explicit,
+            clean_ring_explicit,
             detail_log_cli,
             detail_log_cli,
+            pxe_mode,
+            pxe_iface,
+            pxe_dhcp_port,
+            pxe_proxy_port,
+            batch_window_ms,
             version,
             version,
             commit,
             commit,
         })
         })
     }
     }
+
+    pub fn web_listen_port(&self) -> u16 {
+        self.web_listen
+            .rsplit(':')
+            .next()
+            .and_then(|s| s.parse::<u16>().ok())
+            .unwrap_or(8080)
+    }
 }
 }
 
 
 pub fn load_config_json(path: &Path) -> Option<JsonVal> {
 pub fn load_config_json(path: &Path) -> Option<JsonVal> {

+ 112 - 35
native/stl_accel/src/devices.rs

@@ -104,14 +104,6 @@ pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), St
         } else {
         } else {
             "/dev/ttyUSB0"
             "/dev/ttyUSB0"
         };
         };
-        // Hardware safety boundary: NEVER open /dev/ttyUSB1 (reserved for unrelated thermal/FPGA project)
-        if dev_path.contains("ttyUSB1") {
-            st.diag_state = "error".to_string();
-            st.console_online = false;
-            st.hot.console_online = false;
-            st.diag_last_error = "禁止访问 /dev/ttyUSB1,仅允许 /dev/ttyUSB0 或其他授权串口".to_string();
-            return Err(st.diag_last_error.clone());
-        }
         let dev_c = format!("{}\0", dev_path);
         let dev_c = format!("{}\0", dev_path);
         mfd = unsafe { lib::c_pty_open_serial_115200(dev_c.as_ptr()) };
         mfd = unsafe { lib::c_pty_open_serial_115200(dev_c.as_ptr()) };
         cpid = 0;
         cpid = 0;
@@ -625,12 +617,23 @@ fn exec_freeipmi_op(handle: i32, args: &[&str]) -> Result<String, (bool, String)
                 Err((true, "BMC warm reset 指令失败".to_string()))
                 Err((true, "BMC warm reset 指令失败".to_string()))
             }
             }
         }
         }
-        ["mc", "info"] | ["lan", "print"] | ["sel", "elist"] | ["fru", "print"] => {
-            let kind = match args[0] {
-                "mc" => "mc\0",
-                "lan" => "lan\0",
-                "sel" => "sel\0",
-                "fru" => "fru\0",
+        ["mc", "info"]
+        | ["lan", "print"]
+        | ["sel", "elist"]
+        | ["fru", "print"]
+        | ["sol", "info"]
+        | ["session", "info"]
+        | ["sel", "info"]
+        | ["fan", "mode"] => {
+            let kind = match (args[0], args[1]) {
+                ("mc", _) => "mc\0",
+                ("lan", _) => "lan\0",
+                ("sel", "info") => "events\0",
+                ("sel", _) => "sel\0",
+                ("fru", _) => "fru\0",
+                ("sol", _) => "sol\0",
+                ("session", _) => "sessions\0",
+                ("fan", _) => "fan_mode\0",
                 _ => "mc\0",
                 _ => "mc\0",
             };
             };
             let mut buf = vec![0u8; 131_072];
             let mut buf = vec![0u8; 131_072];
@@ -773,9 +776,9 @@ pub fn run_ipmi_cmd(host: &str, user: &str, pass: &str, args: &[&str]) -> Result
     run_ipmi_with_session(None, host, user, pass, args).map(|(_, out)| out)
     run_ipmi_with_session(None, host, user, pass, args).map(|(_, out)| out)
 }
 }
 
 
-/// Accurately parse both 3-column `ipmitool sdr list` (`DIMM_CPU0_A_Temp | 34.40 degrees C | ok`)
-/// and 5-column `ipmitool sdr elist` (`DIMM_CPU0_A_Temp | 50h | ok | 32.0 | 34.40 degrees C`)
-/// across all 24 DDR5 slots (`CPU0 A..L` = `0..11`, `CPU1 A..L` or `DIMM M..X` = `12..23`).
+/// Accurately parse ALL BMC SDR sensors (temperatures, voltages, fan RPMs, current/power, and discrete states)
+/// into `st.bmc_sensors` + timestamped `st.bmc_sensor_history`, AND update all 24 DDR5 DIMM slot temperatures,
+/// presence flags, and per-slot 24-channel fallback temperature curves (`st.dimm_temp_curves`).
 /// Never writes to `st.chamber_current_c`!
 /// Never writes to `st.chamber_current_c`!
 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();
@@ -784,16 +787,27 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
     let mut seen_discrete_present = [false; 24];
     let mut seen_discrete_present = [false; 24];
     let mut seen_discrete_absent = [false; 24];
     let mut seen_discrete_absent = [false; 24];
     let mut seen_discrete_disabled = [false; 24];
     let mut seen_discrete_disabled = [false; 24];
+    let mut all_sensors: Vec<crate::results::BmcSensorReading> = Vec::new();
 
 
     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 raw_name = parts[0].trim();
+        if raw_name.is_empty() {
+            continue;
+        }
+        let sensor_name = raw_name.to_ascii_uppercase();
         let mut parsed_discrete_mem: Option<u16> = None;
         let mut parsed_discrete_mem: Option<u16> = None;
         let mut parsed_discrete_pres: Option<u16> = None;
         let mut parsed_discrete_pres: Option<u16> = None;
         let mut parsed_discrete_devpres: Option<u16> = None;
         let mut parsed_discrete_devpres: Option<u16> = None;
+        let mut parsed_discrete_generic: Option<u16> = None;
+        let mut parsed_sensor_type = String::new();
+        let mut parsed_val: Option<f64> = None;
+        let mut parsed_unit = String::new();
+        let mut parsed_status = "ok".to_string();
+
         for col in &parts[1..] {
         for col in &parts[1..] {
             let lower = col.to_ascii_lowercase();
             let lower = col.to_ascii_lowercase();
             if let Some(pos) = lower.find("discrete_mem=0x") {
             if let Some(pos) = lower.find("discrete_mem=0x") {
@@ -814,7 +828,77 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
                 if let Ok(v) = u16::from_str_radix(&tok, 16) {
                 if let Ok(v) = u16::from_str_radix(&tok, 16) {
                     parsed_discrete_devpres = Some(v);
                     parsed_discrete_devpres = Some(v);
                 }
                 }
+            } else if let Some(pos) = lower.find("discrete_state=0x") {
+                let hex = &lower[pos + "discrete_state=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_generic = Some(v);
+                }
+            } else if let Some(pos) = lower.find("type=0x") {
+                let hex = &lower[pos + "type=0x".len()..];
+                let tok: String = hex.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
+                if !tok.is_empty() {
+                    parsed_sensor_type = format!("0x{}", tok.to_ascii_uppercase());
+                }
+            } else if parsed_val.is_none() {
+                for (pat, unit_lbl) in [
+                    ("degrees c", "C"),
+                    ("degrees f", "F"),
+                    ("degrees", "C"),
+                    ("volts", "V"),
+                    ("amps", "A"),
+                    ("watts", "W"),
+                    ("rpm", "RPM"),
+                    ("%", "%"),
+                    ("hz", "Hz"),
+                ] {
+                    if let Some(p) = lower.find(pat) {
+                        if let Ok(v) = col[..p].trim().parse::<f64>() {
+                            if v.is_finite() {
+                                parsed_val = Some(v);
+                                parsed_unit = unit_lbl.to_string();
+                                break;
+                            }
+                        }
+                    }
+                }
             }
             }
+            if matches!(lower.as_str(), "ok" | "ns" | "nc" | "cr" | "nr" | "lnc" | "lcr" | "unc" | "ucr" | "na" | "discrete") {
+                parsed_status = lower;
+            }
+        }
+
+        // Record EVERY parsed BMC sensor (Temp / Voltage / Fan / Current / Power / Discrete) for telemetry & post-analysis
+        let disc_bits = parsed_discrete_mem
+            .or(parsed_discrete_pres)
+            .or(parsed_discrete_devpres)
+            .or(parsed_discrete_generic);
+        let category = if parsed_unit == "C" || parsed_unit == "F" {
+            "temp"
+        } else if parsed_unit == "V" {
+            "voltage"
+        } else if parsed_unit == "RPM" {
+            "fan"
+        } else if parsed_unit == "A" {
+            "current"
+        } else if parsed_unit == "W" {
+            "power"
+        } else if disc_bits.is_some() {
+            "discrete"
+        } else {
+            "other"
+        };
+        if parsed_val.is_some() || disc_bits.is_some() {
+            all_sensors.push(crate::results::BmcSensorReading {
+                name: raw_name.to_string(),
+                category: category.to_string(),
+                value: parsed_val,
+                unit: parsed_unit.clone(),
+                status: parsed_status,
+                raw_hex: disc_bits.map(|b| format!("0x{:04X}", b)).unwrap_or_default(),
+                sensor_type: parsed_sensor_type,
+                updated_ms: now,
+            });
         }
         }
 
 
         if parsed_discrete_mem.is_some()
         if parsed_discrete_mem.is_some()
@@ -826,9 +910,6 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
             };
             };
             if slot_idx < 24 {
             if slot_idx < 24 {
                 if let Some(v) = parsed_discrete_mem {
                 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 {
                     if (v & 0x0040) != 0 {
                         seen_discrete_present[slot_idx] = true;
                         seen_discrete_present[slot_idx] = true;
                     }
                     }
@@ -837,7 +918,6 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
                     }
                     }
                 }
                 }
                 if let Some(v) = parsed_discrete_pres {
                 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 {
                     if (v & 0x0001) != 0 {
                         seen_discrete_present[slot_idx] = true;
                         seen_discrete_present[slot_idx] = true;
                     } else if (v & 0x0002) != 0 || v == 0 {
                     } else if (v & 0x0002) != 0 || v == 0 {
@@ -848,7 +928,6 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
                     }
                     }
                 }
                 }
                 if let Some(v) = parsed_discrete_devpres {
                 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 {
                     if (v & 0x0002) != 0 {
                         seen_discrete_present[slot_idx] = true;
                         seen_discrete_present[slot_idx] = true;
                     } else if (v & 0x0001) != 0 || v == 0 {
                     } else if (v & 0x0001) != 0 || v == 0 {
@@ -865,23 +944,17 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
         if slot_idx < 24 {
         if slot_idx < 24 {
             seen_temp_sensor[slot_idx] = true;
             seen_temp_sensor[slot_idx] = true;
         }
         }
-        let mut parsed_temp: Option<f64> = None;
-        for col in &parts[1..] {
-            let lower = col.to_ascii_lowercase();
-            if let Some(deg_pos) = lower.find("degrees") {
-                if let Ok(v) = col[..deg_pos].trim().parse::<f64>() {
-                    if (-40.0..=150.0).contains(&v) {
-                        parsed_temp = Some(v);
-                        break;
-                    }
-                }
-            }
-        }
+        let parsed_temp = if matches!(parsed_unit.as_str(), "C" | "F") {
+            parsed_val.filter(|&v| (-40.0..=150.0).contains(&v))
+        } else {
+            None
+        };
         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.had_bmc_sdr[slot_idx] = true;
                 st.sdr_absent_streak[slot_idx] = 0;
                 st.sdr_absent_streak[slot_idx] = 0;
+                st.record_dimm_temp_sample(slot_idx, now, temp_c);
             }
             }
             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);
@@ -898,6 +971,10 @@ pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
         }
         }
     }
     }
 
 
+    if !all_sensors.is_empty() {
+        st.update_bmc_sensors_snapshot(all_sensors, now);
+    }
+
     let any_valid_temp = seen_valid.iter().any(|&v| v);
     let any_valid_temp = seen_valid.iter().any(|&v| v);
     let any_discrete_present = seen_discrete_present.iter().any(|&v| v);
     let any_discrete_present = seen_discrete_present.iter().any(|&v| v);
 
 

+ 3 - 0
native/stl_accel/src/json.rs

@@ -183,6 +183,9 @@ pub fn parse_json(input: &str) -> Result<JsonVal, String> {
     let mut pos = 0;
     let mut pos = 0;
     let val = parse_value(bytes, &mut pos, 0)?;
     let val = parse_value(bytes, &mut pos, 0)?;
     skip_ws(bytes, &mut pos);
     skip_ws(bytes, &mut pos);
+    if pos != bytes.len() {
+        return Err(format!("Unexpected trailing characters in JSON at byte {}", pos));
+    }
     Ok(val)
     Ok(val)
 }
 }
 
 

+ 103 - 35
native/stl_accel/src/lib.rs

@@ -213,23 +213,8 @@ extern "C" {
         ev: *mut StlRe2cEvent,
         ev: *mut StlRe2cEvent,
     ) -> i32;
     ) -> i32;
 
 
-    pub fn c_dispatch_scan_special(
-        buf: *const u8,
-        len: usize,
-        out_newlines: *mut u64,
-        out_specials: *mut u64,
-    ) -> usize;
-
-    pub fn zig_clean_terminal_fast(
-        src_ptr: *const u8,
-        src_len: usize,
-        dst_ptr: *mut u8,
-        first_ctrl_hint: usize,
-    ) -> usize;
     pub fn zig_ws_accept_key(key_ptr: *const u8, key_len: usize, out_ptr: *mut u8) -> usize;
     pub fn zig_ws_accept_key(key_ptr: *const u8, key_len: usize, out_ptr: *mut u8) -> usize;
-    pub fn zig_base64_encode(src_ptr: *const u8, src_len: usize, dst_ptr: *mut u8, dst_cap: usize) -> usize;
     pub fn zig_base64_decode(src_ptr: *const u8, src_len: usize, dst_ptr: *mut u8, dst_cap: usize) -> usize;
     pub fn zig_base64_decode(src_ptr: *const u8, src_len: usize, dst_ptr: *mut u8, dst_cap: usize) -> usize;
-    pub fn zig_crc16_ccitt_false(data_ptr: *const u8, len: usize) -> u16;
 
 
     pub fn stl_epoll_create() -> i32;
     pub fn stl_epoll_create() -> i32;
     pub fn stl_epoll_ctl_fd(epfd: i32, op: i32, fd: i32, events: u32, token: u64) -> i32;
     pub fn stl_epoll_ctl_fd(epfd: i32, op: i32, fd: i32, events: u32, token: u64) -> i32;
@@ -397,6 +382,109 @@ extern "C" {
     pub fn stl_ws_accept_key(key_ptr: *const u8, key_len: usize, out28: *mut u8) -> usize;
     pub fn stl_ws_accept_key(key_ptr: *const u8, key_len: usize, out28: *mut u8) -> usize;
     pub fn stl_mono_us() -> u64;
     pub fn stl_mono_us() -> u64;
     pub fn stl_mem_diff_64b_mask(a: *const u8, b: *const u8, len: usize) -> u64;
     pub fn stl_mem_diff_64b_mask(a: *const u8, b: *const u8, len: usize) -> u64;
+    pub fn stl_batch_mem_diff_64b_masks(
+        prev_base: *const u8,
+        cur_base: *const u8,
+        stride: usize,
+        item_len: usize,
+        count: usize,
+        out_masks: *mut u64,
+    );
+    pub fn c_list_ipv4_ifaces(out_list: *mut StlNetIface, max_count: i32) -> i32;
+    pub fn c_udp_bind_dhcp_socket(iface: *const u8, port: i32, reuse_port: i32) -> i32;
+    pub fn c_udp_recv_pktinfo(
+        fd: i32,
+        buf: *mut u8,
+        cap: usize,
+        out_peer_ip_be: *mut u32,
+        out_peer_port: *mut u16,
+        out_local_ip_be: *mut u32,
+        out_ifindex: *mut u32,
+    ) -> isize;
+    pub fn c_udp_send_pktinfo(
+        fd: i32,
+        buf: *const u8,
+        len: usize,
+        dst_ip_be: u32,
+        dst_port: u16,
+        src_ip_be: u32,
+        ifindex: u32,
+    ) -> isize;
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct StlNetIface {
+    pub name: [u8; 32],
+    pub ip_be: u32,
+    pub mask_be: u32,
+    pub bcast_be: u32,
+    pub ifindex: u32,
+    pub mac: [u8; 6],
+    pub is_up: u8,
+    pub is_loopback: u8,
+}
+
+#[derive(Clone, Debug)]
+pub struct NetIfaceInfo {
+    pub name: String,
+    pub ip: [u8; 4],
+    pub mask: [u8; 4],
+    pub bcast: [u8; 4],
+    pub ifindex: u32,
+    pub mac: [u8; 6],
+    pub is_up: bool,
+    pub is_loopback: bool,
+}
+
+impl NetIfaceInfo {
+    pub fn ip_string(&self) -> String {
+        format!("{}.{}.{}.{}", self.ip[0], self.ip[1], self.ip[2], self.ip[3])
+    }
+    pub fn mask_string(&self) -> String {
+        format!("{}.{}.{}.{}", self.mask[0], self.mask[1], self.mask[2], self.mask[3])
+    }
+    pub fn mac_string(&self) -> String {
+        format!(
+            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
+            self.mac[0], self.mac[1], self.mac[2], self.mac[3], self.mac[4], self.mac[5]
+        )
+    }
+}
+
+pub fn list_ipv4_ifaces() -> Vec<NetIfaceInfo> {
+    let mut raw = [StlNetIface {
+        name: [0; 32],
+        ip_be: 0,
+        mask_be: 0,
+        bcast_be: 0,
+        ifindex: 0,
+        mac: [0; 6],
+        is_up: 0,
+        is_loopback: 0,
+    }; 64];
+    let n = unsafe { c_list_ipv4_ifaces(raw.as_mut_ptr(), raw.len() as i32) };
+    let mut out = Vec::new();
+    if n <= 0 {
+        return out;
+    }
+    for item in raw.iter().take((n as usize).min(raw.len())) {
+        let name = cstr_to_string(&item.name);
+        if name.is_empty() {
+            continue;
+        }
+        out.push(NetIfaceInfo {
+            name,
+            ip: item.ip_be.to_ne_bytes(),
+            mask: item.mask_be.to_ne_bytes(),
+            bcast: item.bcast_be.to_ne_bytes(),
+            ifindex: item.ifindex,
+            mac: item.mac,
+            is_up: item.is_up != 0,
+            is_loopback: item.is_loopback != 0,
+        });
+    }
+    out
 }
 }
 
 
 /// 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).
@@ -589,18 +677,6 @@ pub fn init_hardware() {
     }
     }
 }
 }
 
 
-pub fn scan_serial_chunk(slice: &[u8]) -> (u64, u64, usize) {
-    if slice.is_empty() {
-        return (0, 0, 0);
-    }
-    let mut nl: u64 = 0;
-    let mut sp: u64 = 0;
-    let first_ctrl = unsafe {
-        c_dispatch_scan_special(slice.as_ptr(), slice.len(), &mut nl, &mut sp)
-    };
-    (nl, sp, first_ctrl)
-}
-
 pub fn clean_terminal_bytes(raw: &[u8]) -> String {
 pub fn clean_terminal_bytes(raw: &[u8]) -> String {
     if raw.is_empty() {
     if raw.is_empty() {
         return String::new();
         return String::new();
@@ -736,14 +812,6 @@ pub fn batch_hex_encode(data: &[u8]) -> (String, bool) {
     (unsafe { String::from_utf8_unchecked(out) }, used_gpu != 0)
     (unsafe { String::from_utf8_unchecked(out) }, used_gpu != 0)
 }
 }
 
 
-#[inline]
-pub fn crc16_ccitt_false(data: &[u8]) -> u16 {
-    if data.is_empty() {
-        return 0xFFFF;
-    }
-    unsafe { zig_crc16_ccitt_false(data.as_ptr(), data.len()) }
-}
-
 fn cstr_to_string(buf: &[u8]) -> String {
 fn cstr_to_string(buf: &[u8]) -> String {
     let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
     let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
     String::from_utf8_lossy(&buf[..end]).trim().to_string()
     String::from_utf8_lossy(&buf[..end]).trim().to_string()

+ 475 - 12
native/stl_accel/src/main.rs

@@ -1,4 +1,4 @@
-// main.rs — Entrypoint for stl_native_server (v0.8.1.19)
+// main.rs — Entrypoint for stl_native_server
 #![allow(special_module_name)]
 #![allow(special_module_name)]
 #![allow(dead_code)]
 #![allow(dead_code)]
 
 
@@ -12,6 +12,7 @@ mod json;
 mod lib;
 mod lib;
 mod n540;
 mod n540;
 mod pxe;
 mod pxe;
+mod pxe_dhcp;
 mod results;
 mod results;
 mod storage;
 mod storage;
 mod thermal_mcu;
 mod thermal_mcu;
@@ -24,6 +25,7 @@ use config::ServerArgs;
 use std::net::TcpListener;
 use std::net::TcpListener;
 use std::path::PathBuf;
 use std::path::PathBuf;
 use std::process;
 use std::process;
+use std::sync::atomic::{AtomicUsize, Ordering};
 use std::sync::Arc;
 use std::sync::Arc;
 use std::thread;
 use std::thread;
 
 
@@ -34,19 +36,27 @@ fn main() {
     if let Some(pos) = raw_args.iter().position(|a| a == "--replay-trace") {
     if let Some(pos) = raw_args.iter().position(|a| a == "--replay-trace") {
         let dir = raw_args
         let dir = raw_args
             .get(pos + 1)
             .get(pos + 1)
+            .filter(|a| !a.starts_with("--"))
             .map(PathBuf::from)
             .map(PathBuf::from)
             .unwrap_or_else(|| PathBuf::from("data/trace"));
             .unwrap_or_else(|| PathBuf::from("data/trace"));
         let mut station: Option<String> = None;
         let mut station: Option<String> = None;
-        let mut at_ms: i64 = i64::MAX;
+        let mut at_ms: i64 = -1;
         let mut idx = 1;
         let mut idx = 1;
         while idx < raw_args.len() {
         while idx < raw_args.len() {
             match raw_args[idx].as_str() {
             match raw_args[idx].as_str() {
+                "--replay-trace" => {
+                    idx += if raw_args.get(idx + 1).map(|a| !a.starts_with("--")).unwrap_or(false) {
+                        2
+                    } else {
+                        1
+                    };
+                }
                 "--station" if idx + 1 < raw_args.len() => {
                 "--station" if idx + 1 < raw_args.len() => {
                     station = Some(raw_args[idx + 1].clone());
                     station = Some(raw_args[idx + 1].clone());
                     idx += 2;
                     idx += 2;
                 }
                 }
                 "--at-ms" if idx + 1 < raw_args.len() => {
                 "--at-ms" if idx + 1 < raw_args.len() => {
-                    at_ms = raw_args[idx + 1].parse::<i64>().unwrap_or(i64::MAX);
+                    at_ms = raw_args[idx + 1].parse::<i64>().unwrap_or(-1);
                     idx += 2;
                     idx += 2;
                 }
                 }
                 _ => idx += 1,
                 _ => idx += 1,
@@ -78,17 +88,35 @@ fn main() {
 
 
     let listener = TcpListener::bind(&args.web_listen).expect("Failed to bind web-listen port");
     let listener = TcpListener::bind(&args.web_listen).expect("Failed to bind web-listen port");
     eprintln!(
     eprintln!(
-        "[stl_native_server] v{} ({}) HTTP+WebSocket listening on http://{} (web_dir={})",
+        "[stl_native_server] v{} ({}) HTTP+WebSocket listening on http://{} (web_dir={}, shards={}, ipmi_workers={}, pxe_mode={})",
         args.version,
         args.version,
         args.commit,
         args.commit,
         args.web_listen,
         args.web_listen,
-        args.web_dir.display()
+        args.web_dir.display(),
+        hub.reactor_pool.shard_count(),
+        hub.reactor_pool.ipmi_worker_count(),
+        hub.pxe_dhcp_hub.get_config().mode.as_str()
     );
     );
 
 
+    const MAX_HTTP_CONNS: usize = 128;
+    let active_http = Arc::new(AtomicUsize::new(0));
     for stream in listener.incoming() {
     for stream in listener.incoming() {
-        if let Ok(s) = stream {
+        if let Ok(mut s) = stream {
+            let prev = active_http.fetch_add(1, Ordering::AcqRel);
+            if prev >= MAX_HTTP_CONNS {
+                active_http.fetch_sub(1, Ordering::AcqRel);
+                use std::io::Write;
+                let _ = s.write_all(
+                    b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 11\r\nConnection: close\r\n\r\nServer Busy",
+                );
+                continue;
+            }
             let h = Arc::clone(&hub);
             let h = Arc::clone(&hub);
-            thread::spawn(move || handle_http_client(s, h));
+            let cnt = Arc::clone(&active_http);
+            thread::spawn(move || {
+                handle_http_client(s, h);
+                cnt.fetch_sub(1, Ordering::AcqRel);
+            });
         }
         }
     }
     }
 }
 }
@@ -341,6 +369,13 @@ mod tests {
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.19".to_string(),
             version: "0.8.1.19".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -634,6 +669,13 @@ mod tests {
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.19".to_string(),
             version: "0.8.1.19".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -812,6 +854,13 @@ mod tests {
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.19".to_string(),
             version: "0.8.1.19".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -873,6 +922,13 @@ mod tests {
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.19".to_string(),
             version: "0.8.1.19".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -2128,6 +2184,13 @@ Finished pass #1 (of 1) (Cumulative error count: 9, buffer full count: 0)\r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.24".to_string(),
             version: "0.8.1.24".to_string(),
             commit: "test".to_string(),
             commit: "test".to_string(),
@@ -2328,6 +2391,13 @@ Finished pass #1 (of 1) (Cumulative error count: 9, buffer full count: 0)\r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.24".to_string(),
             version: "0.8.1.24".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -2475,6 +2545,13 @@ Finished pass #1 (of 1) (Cumulative error count: 9, buffer full count: 0)\r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.24".to_string(),
             version: "0.8.1.24".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -2586,6 +2663,13 @@ Finished pass #1 (of 1) (Cumulative error count: 9, buffer full count: 0)\r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.24".to_string(),
             version: "0.8.1.24".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -2766,6 +2850,13 @@ N1.C11.D0: FPT: DisableDIMM()\r\n\
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.24".to_string(),
             version: "0.8.1.24".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -2931,7 +3022,7 @@ Reset Type: Warm Reset\r\n\
         }
         }
         assert_eq!(s167_st.dimms[0].presence, "present");
         assert_eq!(s167_st.dimms[0].presence, "present");
 
 
-        // 10. load_station_settings clears persisted failed/running task_batch on backend startup
+        // 10. load_station_settings preserves failed task_batch history and marks persisted running task_batch as interrupted
         let mut saved_st = StationState::new("S2", "Station 2", "192.168.2.165", "");
         let mut saved_st = StationState::new("S2", "Station 2", "192.168.2.165", "");
         saved_st.task_batch.set("state", JsonVal::Str("failed".to_string()));
         saved_st.task_batch.set("state", JsonVal::Str("failed".to_string()));
         saved_st.task_batch.set("batch_id", JsonVal::Str("TB-OLD".to_string()));
         saved_st.task_batch.set("batch_id", JsonVal::Str("TB-OLD".to_string()));
@@ -2940,8 +3031,19 @@ Reset Type: Warm Reset\r\n\
         loaded_map.insert("S2".to_string(), StationState::new("S2", "Station 2", "", ""));
         loaded_map.insert("S2".to_string(), StationState::new("S2", "Station 2", "", ""));
         crate::storage::load_station_settings(&tmp_dir, &mut loaded_map);
         crate::storage::load_station_settings(&tmp_dir, &mut loaded_map);
         let loaded_tb = &loaded_map.get("S2").unwrap().task_batch;
         let loaded_tb = &loaded_map.get("S2").unwrap().task_batch;
-        assert_eq!(loaded_tb.get_str_or("state", ""), "idle");
-        assert_eq!(loaded_tb.get_str_or("batch_id", ""), "");
+        assert_eq!(loaded_tb.get_str_or("state", ""), "failed");
+        assert_eq!(loaded_tb.get_str_or("batch_id", ""), "TB-OLD");
+
+        saved_st.task_batch.set("state", JsonVal::Str("running".to_string()));
+        saved_st.task_batch.set("batch_id", JsonVal::Str("TB-RUN".to_string()));
+        crate::storage::save_station_settings(&tmp_dir, &saved_st);
+        let mut loaded_map2 = std::collections::BTreeMap::new();
+        loaded_map2.insert("S2".to_string(), StationState::new("S2", "Station 2", "", ""));
+        crate::storage::load_station_settings(&tmp_dir, &mut loaded_map2);
+        let loaded_tb2 = &loaded_map2.get("S2").unwrap().task_batch;
+        assert_eq!(loaded_tb2.get_str_or("state", ""), "interrupted");
+        assert_eq!(loaded_tb2.get_str_or("halt_reason", ""), "server_restarted");
+        assert_eq!(loaded_tb2.get_str_or("batch_id", ""), "TB-RUN");
 
 
         let _ = std::fs::remove_dir_all(&tmp_dir);
         let _ = std::fs::remove_dir_all(&tmp_dir);
     }
     }
@@ -2970,6 +3072,13 @@ Reset Type: Warm Reset\r\n\
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.24".to_string(),
             version: "0.8.1.24".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -3120,6 +3229,13 @@ UEFI Interactive Shell v2.2\r\nFS0:\\EFI\\> \r\n\
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.25".to_string(),
             version: "0.8.1.25".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -3323,6 +3439,13 @@ Please press ENTER to start UIP\r\n\
             web_password: Some("xjkj123456!".to_string()),
             web_password: Some("xjkj123456!".to_string()),
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.27".to_string(),
             version: "0.8.1.27".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -3544,6 +3667,13 @@ Please press ENTER to start UIP\r\n\
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.27".to_string(),
             version: "0.8.1.27".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -3704,6 +3834,13 @@ FS0:\\EFI\\> \r\n",
             web_password: Some("xjkj123456!".to_string()),
             web_password: Some("xjkj123456!".to_string()),
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.28".to_string(),
             version: "0.8.1.28".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -3919,6 +4056,13 @@ FS0:\\EFI\\> \r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.29".to_string(),
             version: "0.8.1.29".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -4315,6 +4459,13 @@ FS0:\\EFI\\> \r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.30".to_string(),
             version: "0.8.1.30".to_string(),
             commit: "unit-test".to_string(),
             commit: "unit-test".to_string(),
@@ -4421,14 +4572,14 @@ FS0:\\EFI\\> \r\n",
         st_l2.observed_unix_ms = t_r1;
         st_l2.observed_unix_ms = t_r1;
         st_l2.hot.last_rx_unix_ms = t_r1;
         st_l2.hot.last_rx_unix_ms = t_r1;
 
 
-        // Hang #1 at t_r1 + 6s -> should auto-advance to R2 and queue `smart_restart`!
+        // Hang #1 at t_r1 + 6s -> retries unfinished R1 (`retry_current_task`) and queues `smart_restart`!
         assert!(evaluate_stage_watchdog(&mut st_l2, t_r1 + 6_000));
         assert!(evaluate_stage_watchdog(&mut st_l2, t_r1 + 6_000));
         assert_eq!(st_l2.consecutive_hang_count, 1);
         assert_eq!(st_l2.consecutive_hang_count, 1);
         assert!(!st_l2.hang_scene_preserved);
         assert!(!st_l2.hang_scene_preserved);
         step_boot_plan(&mut st_l2, &contract);
         step_boot_plan(&mut st_l2, &contract);
         step_task_batch(&mut st_l2, &contract, &mut pxe_l2, &tmp_dir, &tmp_dir);
         step_task_batch(&mut st_l2, &contract, &mut pxe_l2, &tmp_dir, &tmp_dir);
         assert_eq!(st_l2.task_batch.get_str_or("state", ""), "running");
         assert_eq!(st_l2.task_batch.get_str_or("state", ""), "running");
-        assert_eq!(st_l2.task_batch.get_i64("current_repeat"), Some(2));
+        assert_eq!(st_l2.task_batch.get_i64("current_repeat"), Some(1));
         assert_eq!(
         assert_eq!(
             st_l2.pending_bmc_power_action.take().as_deref(),
             st_l2.pending_bmc_power_action.take().as_deref(),
             Some("smart_restart"),
             Some("smart_restart"),
@@ -4498,6 +4649,13 @@ FS0:\\EFI\\> \r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.8.1.30".to_string(),
             version: "0.8.1.30".to_string(),
             commit: "phase0-test".to_string(),
             commit: "phase0-test".to_string(),
@@ -4652,6 +4810,13 @@ FS0:\\EFI\\> \r\n",
             web_password: Some("xjkj123456!".to_string()),
             web_password: Some("xjkj123456!".to_string()),
             raw_ring_mb: 4,
             raw_ring_mb: 4,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(false),
             detail_log_cli: Some(false),
             version: "0.9.0.0".to_string(),
             version: "0.9.0.0".to_string(),
             commit: "phase1-test".to_string(),
             commit: "phase1-test".to_string(),
@@ -4853,6 +5018,13 @@ FS0:\\EFI\\> \r\n",
             web_password: None,
             web_password: None,
             raw_ring_mb: 2,
             raw_ring_mb: 2,
             clean_ring_mb: 2,
             clean_ring_mb: 2,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
             detail_log_cli: Some(true),
             detail_log_cli: Some(true),
             version: "0.9.1.0".to_string(),
             version: "0.9.1.0".to_string(),
             commit: "phase2-test".to_string(),
             commit: "phase2-test".to_string(),
@@ -5070,4 +5242,295 @@ FS0:\\EFI\\> \r\n",
         assert_eq!(hw_json.get_bool("available"), Some(true));
         assert_eq!(hw_json.get_bool("available"), Some(true));
         assert!(hw_json.get("opencl_igpu").is_some());
         assert!(hw_json.get("opencl_igpu").is_some());
     }
     }
+
+    #[test]
+    fn test_phase4_pxe_proxy_rmt_hang3_bmc_thermal_trace_and_200_stations() {
+        use std::net::Ipv4Addr;
+
+        let tmp_dir = env::temp_dir().join(format!(
+            "stl-phase4-{}-{}",
+            std::process::id(),
+            now_ms()
+        ));
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+        std::fs::create_dir_all(&tmp_dir).unwrap();
+
+        // 1. JSON parser rejects trailing non-whitespace garbage
+        assert!(parse_json(r#"{"a":1}"#).is_ok());
+        assert!(parse_json(r#"{"a":1}   "#).is_ok());
+        assert!(parse_json(r#"{"a":1} garbage"#).is_err());
+
+        // 2. Built-in ProxyDHCP (UDP 67/4011), UEFI HTTP Boot, MAC whitelist & Isolated DHCP pool
+        let trace_dummy = crate::trace::TraceHub::init(
+            &tmp_dir,
+            Some(false),
+            std::sync::Arc::new(crate::actors::PushBroadcaster::new()),
+        );
+        let mut pxe_cfg = crate::pxe_dhcp::PxeDhcpConfig::default_with_ports(8080, 0, 0);
+        pxe_cfg.mode = crate::pxe_dhcp::PxeBootMode::Proxy;
+        pxe_cfg.server_ip = "192.168.2.68".to_string();
+        let pxe_hub = crate::pxe_dhcp::PxeDhcpHub::init(
+            pxe_cfg,
+            tmp_dir.clone(),
+            tmp_dir.join("pxe"),
+            trace_dummy,
+            false,
+        );
+
+        let build_dhcp_req = |msg_type: u8, mac: [u8; 6], vendor: Option<&[u8]>, arch: Option<u16>, ciaddr: Ipv4Addr| -> Vec<u8> {
+            let mut pkt = vec![0u8; 240];
+            pkt[0] = crate::pxe_dhcp::DHCP_OP_BOOTREQUEST;
+            pkt[1] = 1;
+            pkt[2] = 6;
+            pkt[4..8].copy_from_slice(&[0x11, 0x22, 0x33, 0x44]);
+            pkt[10..12].copy_from_slice(&0x8000u16.to_be_bytes());
+            pkt[12..16].copy_from_slice(&ciaddr.octets());
+            pkt[28..34].copy_from_slice(&mac);
+            pkt[236..240].copy_from_slice(&crate::pxe_dhcp::DHCP_MAGIC_COOKIE);
+            pkt.extend_from_slice(&[53, 1, msg_type]);
+            if let Some(v) = vendor {
+                pkt.push(60);
+                pkt.push(v.len() as u8);
+                pkt.extend_from_slice(v);
+            }
+            if let Some(a) = arch {
+                pkt.extend_from_slice(&[93, 2, (a >> 8) as u8, (a & 0xff) as u8]);
+            }
+            pkt.push(255);
+            if pkt.len() < 300 { pkt.resize(300, 0); }
+            pkt
+        };
+
+        let srv_ip = Ipv4Addr::new(192, 168, 2, 68);
+        // 2a. Non-PXE office PC DISCOVER MUST be ignored in proxy mode
+        let office_pkt = build_dhcp_req(crate::pxe_dhcp::DHCP_MSG_DISCOVER, [0xaa, 0xbb, 0xcc, 0x00, 0x00, 0x01], Some(b"MSFT 5.0"), None, Ipv4Addr::UNSPECIFIED);
+        assert!(pxe_hub.process_dhcp_packet(&office_pkt, Ipv4Addr::UNSPECIFIED, 68, srv_ip, false).is_none());
+        assert_eq!(pxe_hub.build_status_json().get_i64("packets_ignored_non_pxe"), Some(1));
+
+        // 2b. UEFI x64 PXEClient DISCOVER on UDP 67 -> Proxy DHCPOFFER (yiaddr=0.0.0.0, siaddr=server_ip, file=118.efi)
+        let pxe_disc = build_dhcp_req(crate::pxe_dhcp::DHCP_MSG_DISCOVER, [0x52, 0x54, 0x00, 0x12, 0x34, 0x56], Some(b"PXEClient:Arch:00007:UNDI:003016"), Some(7), Ipv4Addr::UNSPECIFIED);
+        let offer = pxe_hub.process_dhcp_packet(&pxe_disc, Ipv4Addr::UNSPECIFIED, 68, srv_ip, false).expect("ProxyDHCP must reply OFFER to UEFI PXEClient");
+        let parsed_offer = crate::pxe_dhcp::parse_dhcp_packet(&offer.packet).unwrap();
+        assert_eq!(parsed_offer.msg_type, crate::pxe_dhcp::DHCP_MSG_OFFER);
+        assert_eq!(parsed_offer.yiaddr, Ipv4Addr::UNSPECIFIED, "ProxyDHCP must NEVER assign client IP");
+        assert_eq!(parsed_offer.siaddr, srv_ip);
+        assert_eq!(parsed_offer.file_field, "118.efi");
+
+        // 2c. Proxy UDP 67 REQUEST -> None (router handles IP lease), UDP 4011 REQUEST -> DHCPACK with 118.efi
+        let pxe_req = build_dhcp_req(crate::pxe_dhcp::DHCP_MSG_REQUEST, [0x52, 0x54, 0x00, 0x12, 0x34, 0x56], Some(b"PXEClient:Arch:00007:UNDI:003016"), Some(7), Ipv4Addr::new(192, 168, 2, 180));
+        assert!(pxe_hub.process_dhcp_packet(&pxe_req, Ipv4Addr::new(192, 168, 2, 180), 68, srv_ip, false).is_none());
+        let ack4011 = pxe_hub.process_dhcp_packet(&pxe_req, Ipv4Addr::new(192, 168, 2, 180), 4011, srv_ip, true).expect("ProxyDHCP UDP 4011 must ACK bootfile");
+        let parsed_ack = crate::pxe_dhcp::parse_dhcp_packet(&ack4011.packet).unwrap();
+        assert_eq!(parsed_ack.msg_type, crate::pxe_dhcp::DHCP_MSG_ACK);
+        assert_eq!(parsed_ack.file_field, "118.efi");
+        assert_eq!(pxe_hub.lookup_mac_by_ip("192.168.2.180").as_deref(), Some("52:54:00:12:34:56"));
+
+        // 2d. UEFI HTTP Boot (arch 16 / HTTPClient) -> http://192.168.2.68:8080/pxe/118.efi
+        let http_disc = build_dhcp_req(crate::pxe_dhcp::DHCP_MSG_DISCOVER, [0x52, 0x54, 0x00, 0x12, 0x34, 0x77], Some(b"HTTPClient:Arch:00016:UNDI:003001"), Some(16), Ipv4Addr::UNSPECIFIED);
+        let http_offer = pxe_hub.process_dhcp_packet(&http_disc, Ipv4Addr::UNSPECIFIED, 68, srv_ip, false).expect("HTTPClient must receive UEFI HTTP Boot offer");
+        let parsed_http = crate::pxe_dhcp::parse_dhcp_packet(&http_offer.packet).unwrap();
+        assert_eq!(parsed_http.file_field, "http://192.168.2.68:8080/pxe/118.efi");
+        assert_eq!(parsed_http.vendor_class, "HTTPClient");
+
+        // 2e. MAC whitelist + Isolated DHCP IP assignment
+        let _ = pxe_hub.reconfigure(&parse_json(r#"{"pxe_mode":"isolated","pxe_dhcp_range_start":"10.88.0.100","pxe_dhcp_range_end":"10.88.0.110","pxe_mac_whitelist":["52:54:00:12:34:56"]}"#).unwrap());
+        let blocked_disc = build_dhcp_req(crate::pxe_dhcp::DHCP_MSG_DISCOVER, [0x52, 0x54, 0x00, 0x99, 0x99, 0x99], Some(b"PXEClient:Arch:00007"), Some(7), Ipv4Addr::UNSPECIFIED);
+        assert!(pxe_hub.process_dhcp_packet(&blocked_disc, Ipv4Addr::UNSPECIFIED, 68, Ipv4Addr::new(10, 88, 0, 1), false).is_none());
+        let iso_offer = pxe_hub.process_dhcp_packet(&pxe_disc, Ipv4Addr::UNSPECIFIED, 68, Ipv4Addr::new(10, 88, 0, 1), false).expect("Whitelisted MAC in isolated mode gets IP lease");
+        let parsed_iso = crate::pxe_dhcp::parse_dhcp_packet(&iso_offer.packet).unwrap();
+        assert_eq!(parsed_iso.yiaddr, Ipv4Addr::new(10, 88, 0, 100));
+
+        // 3. RMT stage calibration: `...` never enters RMT; Skipped / Disabled / unrequested Time=0 -> rmt_status="skipped", rmt_complete=false
+        let mut st = StationState::new("S1", "Station 1", "192.168.2.166", "");
+        let t = now_ms();
+        st.observe_serial_chunk(b"[HS_BIOS]Version:108_VD012\r\n[0][Hovsee]Current stage is 1\r\n...\r\n");
+        assert_ne!(st.observed_phase, "rmt", "Progress dots must never jump into RMT phase");
+
+        st.observe_serial_chunk(b"[HS_BIOS][Training][ScktId: 0][48]Rank Margin Tool -- Skipped,Time=0 ms\r\n");
+        assert_eq!(st.rmt_status, "skipped");
+        assert!(!st.hot.rmt_complete);
+        assert!(!st.observed_stages.contains("rmt"));
+
+        // Unrequested RMT (default uip_overrides without rmt enable) + Time=18 ms with 0 rows -> skipped (NOT completed!)
+        let mut st2 = StationState::new("S2", "Station 2", "192.168.2.165", "");
+        st2.observe_serial_chunk(b"[HS_BIOS]Version:108_VD012\r\n[HS_BIOS][Training][ScktId: 0][48]Rank Margin Tool -- SUCCEEDED,Time=18 ms\r\n");
+        assert_eq!(st2.rmt_status, "skipped");
+        assert!(!st2.hot.rmt_complete);
+
+        // Real RMT measurement row -> completed + RX & TX margins populated!
+        st2.uip_overrides.push(parse_json(r#"{"id":"rmt","mode":"override","value":"enable"}"#).unwrap());
+        st2.observe_serial_chunk(b"[HS_BIOS][Training][ScktId: 0][48]Rank Margin Tool\r\nN0.C0.D0.R0 : -14 16 -12 14\r\n[HS_BIOS][Training][ScktId: 0][48]Rank Margin Tool -- SUCCEEDED,Time=4200 ms\r\n");
+        assert_eq!(st2.rmt_status, "completed");
+        assert!(st2.hot.rmt_complete);
+        assert_eq!(st2.rmt_results.values().map(|r| r.measurement_rows).sum::<usize>(), 1);
+        assert_eq!(st2.dimm_soa.rmt_rx_dq_lo[0], -14);
+        assert_eq!(st2.dimm_soa.rmt_tx_dq_hi[0], 14);
+
+        // 4. Full BMC sensors (Temp/Voltage/Fan/Current/Power/Discrete) + DIMM curve fallback (TEMP-2)
+        let s_temp = crate::results::BmcSensorReading { name: "DIMM_A0 Temp".into(), sensor_type: "Temperature".into(), category: "temp".into(), value: Some(58.5), unit: "C".into(), status: "OK".into(), raw_hex: String::new(), updated_ms: t };
+        let s_volt = crate::results::BmcSensorReading { name: "P12V".into(), sensor_type: "Voltage".into(), category: "voltage".into(), value: Some(12.04), unit: "V".into(), status: "OK".into(), raw_hex: String::new(), updated_ms: t };
+        let s_fan = crate::results::BmcSensorReading { name: "FAN1".into(), sensor_type: "Fan".into(), category: "fan".into(), value: Some(5400.0), unit: "RPM".into(), status: "OK".into(), raw_hex: String::new(), updated_ms: t };
+        let s_pwr = crate::results::BmcSensorReading { name: "PSU1_PIN".into(), sensor_type: "Current".into(), category: "power".into(), value: Some(312.0), unit: "W".into(), status: "OK".into(), raw_hex: String::new(), updated_ms: t };
+        let s_disc = crate::results::BmcSensorReading { name: "PSU1 Status".into(), sensor_type: "Power Supply".into(), category: "discrete".into(), value: None, unit: "".into(), status: "Presence detected".into(), raw_hex: "0x01".into(), updated_ms: t };
+        st2.update_bmc_sensors_snapshot(vec![s_temp, s_volt, s_fan, s_pwr, s_disc], t);
+        st2.record_dimm_temp_sample(0, t, 58.5);
+        st2.record_dimm_temp_sample(0, t + 5000, 61.0);
+        assert_eq!(st2.bmc_sensors.len(), 5);
+        assert_eq!(st2.bmc_sensor_history.len(), 1);
+        let fallback_curve = st2.build_dimm_curve_fallback_json(0);
+        assert_eq!(fallback_curve.get_arr("points").unwrap().len(), 2);
+
+        // 5. 3-Mode Hang Recovery (stop / retry_current_task / restart_full_plan) + Thermal CL-3
+        use crate::workflow::{evaluate_stage_watchdog, step_boot_plan, step_task_batch, submit_task_batch};
+        assert_eq!(std::mem::size_of::<crate::trace::StationCoreBinary>(), 320);
+        let contract = FirmwareContract::load(Path::new("contracts/firmware-vd012.json"));
+        let mut st_h = StationState::new("S1", "Station 1", "192.168.2.166", "");
+        let mut pxe_dummy = JsonVal::obj();
+        st_h.bmc_state = "online".to_string();
+        st_h.server_power = "on".to_string();
+        st_h.console_online = true;
+        st_h.diag_state = "online".to_string();
+        st_h.watchdog.dense_stage_silence_timeout_ms = 5_000;
+        st_h.watchdog.hang_action = "retry_current_task".to_string();
+        st_h.watchdog.reboot_on_hang = true;
+        st_h.watchdog.max_consecutive_hangs = 0; // unlimited!
+        let batch_args = parse_json(r#"{"stop_on_fail":false,"hang_action":"retry_current_task","max_consecutive_hangs":0,"auto_start":true,"profiles":[{"name":"P1","repeat":1,"run_amt":false,"run_mt":false,"thermal_auto_enabled":false},{"name":"P2","repeat":2,"run_amt":false,"run_mt":false,"thermal_auto_enabled":false}]}"#).unwrap();
+        let _ = submit_task_batch(
+            &mut st_h,
+            &batch_args,
+            &contract,
+            &mut pxe_dummy,
+            &tmp_dir,
+            &tmp_dir,
+        ).unwrap();
+        // Complete P1 Round 1 -> advances to P2 Round 1
+        st_h.power_seq_in_progress = false;
+        st_h.observe_serial_chunk(b"[HS_BIOS]Version:108_VD012\r\nUEFI Interactive Shell v2.2\r\nFS0:\\EFI\\> ");
+        step_boot_plan(&mut st_h, &contract);
+        step_task_batch(&mut st_h, &contract, &mut pxe_dummy, &tmp_dir, &tmp_dir);
+        assert_eq!(st_h.task_batch.get_i64("current_profile_index"), Some(1));
+        assert_eq!(st_h.task_batch.get_i64("current_repeat"), Some(1));
+        // Complete P2 Round 1 -> advances to P2 Round 2
+        st_h.power_seq_in_progress = false;
+        st_h.observe_serial_chunk(b"[HS_BIOS]Version:108_VD012\r\nUEFI Interactive Shell v2.2\r\nFS0:\\EFI\\> ");
+        step_boot_plan(&mut st_h, &contract);
+        step_task_batch(&mut st_h, &contract, &mut pxe_dummy, &tmp_dir, &tmp_dir);
+        assert_eq!(st_h.task_batch.get_i64("current_profile_index"), Some(1));
+        assert_eq!(st_h.task_batch.get_i64("current_repeat"), Some(2));
+        // Trigger hang silence on P2 Round 2 -> retry_current_task MUST keep (1, 2) and request reboot!
+        st_h.power_seq_in_progress = false;
+        st_h.observe_serial_chunk(b"[HS_BIOS]Version:108_VD012\r\n[HS_BIOS][Training][ScktId: 0][10]Wait\r\n");
+        let hang_ts = st_h.last_activity_anchor_ms() + 10_000;
+        assert!(evaluate_stage_watchdog(&mut st_h, hang_ts));
+        step_task_batch(&mut st_h, &contract, &mut pxe_dummy, &tmp_dir, &tmp_dir);
+        assert_eq!(st_h.task_batch.get_str_or("state", ""), "running", "retry_current_task must keep batch running");
+        assert_eq!(st_h.task_batch.get_i64("current_profile_index"), Some(1), "retry_current_task must stay on Profile 2");
+        assert_eq!(st_h.task_batch.get_i64("current_repeat"), Some(2), "retry_current_task must redo unfinished Round 2");
+
+        // Switch to restart_full_plan -> hang resets to Profile 1 Round 1!
+        st_h.watchdog.hang_action = "restart_full_plan".to_string();
+        st_h.task_batch.set("hang_action", JsonVal::Str("restart_full_plan".to_string()));
+        st_h.power_seq_in_progress = false;
+        st_h.observe_serial_chunk(b"[HS_BIOS]Version:108_VD012\r\n[HS_BIOS][Training][ScktId: 0][11]Wait\r\n");
+        let hang_ts2 = st_h.last_activity_anchor_ms() + 10_000;
+        assert!(evaluate_stage_watchdog(&mut st_h, hang_ts2));
+        step_task_batch(&mut st_h, &contract, &mut pxe_dummy, &tmp_dir, &tmp_dir);
+        assert_eq!(st_h.task_batch.get_str_or("state", ""), "running");
+        assert_eq!(st_h.task_batch.get_i64("current_profile_index"), Some(0), "restart_full_plan must reset to Profile 1");
+        assert_eq!(st_h.task_batch.get_i64("current_repeat"), Some(1), "restart_full_plan must reset to Round 1");
+        assert_eq!(st_h.task_batch.get_i64("total_runs_completed"), Some(0));
+
+        // 5c. CL-3: ControlTaskBatch("stop") triggers cooling purge on online hood
+        let args = ServerArgs {
+            config_path: tmp_dir.join("missing.json"),
+            data_dir: tmp_dir.clone(),
+            web_listen: "127.0.0.1:0".to_string(),
+            tftp_listen: "disabled".to_string(),
+            web_dir: std::path::PathBuf::from("web"),
+            contracts_path: std::path::PathBuf::from("contracts/firmware-vd012.json"),
+            web_password: Some("xjkj123456!".to_string()),
+            raw_ring_mb: 2,
+            clean_ring_mb: 1,
+            raw_ring_explicit: true,
+            clean_ring_explicit: true,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 20,
+            detail_log_cli: Some(true),
+            version: "0.9.5-preview.1".to_string(),
+            commit: "phase4-test".to_string(),
+        };
+        let hub = AppHub::init_for_test(&args);
+        let _ = hub.dispatch_rpc("ThermalAction", &parse_json(r#"{"station_id":"S2","action":"connect","mode":"mock"}"#).unwrap()).unwrap();
+        std::thread::sleep(Duration::from_millis(80));
+        let _ = hub.dispatch_rpc("ThermalAction", &parse_json(r#"{"station_id":"S2","action":"set_temp","target_c":75}"#).unwrap()).unwrap();
+        std::thread::sleep(Duration::from_millis(80));
+        let _ = hub.dispatch_rpc("EnqueueCommand", &parse_json(r#"{"command_id":"p4-cl3","station_id":"S2","method":"ControlTaskBatch","arguments":{"action":"stop"}}"#).unwrap()).unwrap();
+        std::thread::sleep(Duration::from_millis(120));
+        assert_eq!(hub.thermal_hub.get_live_summary("S2").unwrap().mcu_mode, "cooling_purge", "CL-3: ControlTaskBatch stop must cool hood");
+
+        // 6. 200-station scale test: Sharded Reactor Pool boots 200 stations on <= 8 shards + <= 8 IPMI workers with auto-scaled rings!
+        let tmp_200 = env::temp_dir().join(format!("stl-scale200-{}-{}", std::process::id(), now_ms()));
+        let _ = std::fs::remove_dir_all(&tmp_200);
+        std::fs::create_dir_all(&tmp_200).unwrap();
+        let mut cfg_stations = Vec::with_capacity(200);
+        for i in 1..=200 {
+            let mut s = JsonVal::obj();
+            s.set("station_id", JsonVal::Str(format!("S{:03}", i)));
+            s.set("name", JsonVal::Str(format!("Station {:03}", i)));
+            s.set("bmc_host", JsonVal::Str(format!("10.200.{}.{}", i / 250, (i % 250) + 1)));
+            s.set("console_enabled", JsonVal::Bool(false));
+            s.set("bmc_enabled", JsonVal::Bool(false));
+            cfg_stations.push(s);
+        }
+        let mut cfg_root = JsonVal::obj();
+        cfg_root.set("stations", JsonVal::Arr(cfg_stations));
+        let cfg_200_path = tmp_200.join("stations200.json");
+        std::fs::write(&cfg_200_path, cfg_root.to_json()).unwrap();
+
+        let args_200 = ServerArgs {
+            config_path: cfg_200_path,
+            data_dir: tmp_200.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: 16,
+            clean_ring_mb: 8,
+            raw_ring_explicit: false,
+            clean_ring_explicit: false,
+            pxe_mode: "disabled".to_string(),
+            pxe_iface: String::new(),
+            pxe_dhcp_port: 0,
+            pxe_proxy_port: 0,
+            batch_window_ms: 100,
+            detail_log_cli: Some(false),
+            version: "0.9.5-preview.1".to_string(),
+            commit: "scale200".to_string(),
+        };
+        let hub_200 = AppHub::init_for_test(&args_200);
+        let list_200 = hub_200.dispatch_rpc("ListStations", &JsonVal::obj()).unwrap();
+        assert_eq!(list_200.get_arr("stations").unwrap().len(), 200);
+        assert!(hub_200.reactor_pool.shard_count() <= 8, "200 stations must share <= 8 reactor shards");
+        assert!(hub_200.reactor_pool.ipmi_worker_count() <= 8, "200 stations must share <= 8 IPMI workers");
+
+        // Batch SIMD 64B diff masks over 200 structs
+        let prev_buf = vec![0x11u8; 200 * 320];
+        let mut cur_buf = prev_buf.clone();
+        cur_buf[0] ^= 0xFF;
+        cur_buf[199 * 320 + 64 * 4 + 3] ^= 0x01;
+        let mut out_masks = vec![0u64; 200];
+        unsafe {
+            lib::stl_batch_mem_diff_64b_masks(prev_buf.as_ptr(), cur_buf.as_ptr(), 320, 320, 200, out_masks.as_mut_ptr());
+        }
+        assert_eq!(out_masks[0], 1);
+        assert_eq!(out_masks[1], 0);
+        assert_eq!(out_masks[199], 1u64 << 4);
+
+        let _ = std::fs::remove_dir_all(&tmp_dir);
+        let _ = std::fs::remove_dir_all(&tmp_200);
+    }
 }
 }

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

@@ -31,6 +31,52 @@ pub const STAGE1_PXE_COMMANDS: [&str; 6] = [
     "pxe serverip 192.168.0.10",
     "pxe serverip 192.168.0.10",
 ];
 ];
 
 
+pub fn build_stage1_pxe_commands(
+    server_ip: &str,
+    subnet_mask: &str,
+    client_ip: &str,
+    efi_name: &str,
+) -> Vec<String> {
+    let sip = if server_ip.trim().is_empty() {
+        "192.168.0.10"
+    } else {
+        server_ip.trim()
+    };
+    let mask = if subnet_mask.trim().is_empty() {
+        "255.255.255.0"
+    } else {
+        subnet_mask.trim()
+    };
+    let cip = if client_ip.trim().is_empty() {
+        "192.168.0.160"
+    } else {
+        client_ip.trim()
+    };
+    let efi = if efi_name.trim().is_empty() {
+        PXE_EFI_FILENAME
+    } else {
+        efi_name.trim()
+    };
+    vec![
+        format!("pxe umemdiag {}", efi),
+        "pxe umemdiagcfg mt86.cfg".to_string(),
+        format!("pxe clientip {}", cip),
+        format!("pxe subnetmaskip {}", mask),
+        format!("pxe gatewayip {}", sip),
+        format!("pxe serverip {}", sip),
+    ]
+}
+
+fn pxe_ssh_credentials() -> Option<(String, String)> {
+    let user = std::env::var("STL_PXE_SSH_USER").ok()?;
+    let pass = std::env::var("STL_PXE_SSH_PASS").ok()?;
+    if user.trim().is_empty() {
+        None
+    } else {
+        Some((user.trim().to_string(), pass))
+    }
+}
+
 /// Local candidate filenames written alongside `mt86.cfg`
 /// Local candidate filenames written alongside `mt86.cfg`
 pub const LOCAL_CFG_CANDIDATES: [&str; 7] = [
 pub const LOCAL_CFG_CANDIDATES: [&str; 7] = [
     "mt86.cfg",
     "mt86.cfg",
@@ -79,10 +125,15 @@ pub fn default_pxe_state() -> JsonVal {
     let mut st = JsonVal::obj();
     let mut st = JsonVal::obj();
     st.set("active_efi", JsonVal::Str(PXE_EFI_FILENAME.to_string()));
     st.set("active_efi", JsonVal::Str(PXE_EFI_FILENAME.to_string()));
     st.set("stage1_pxe_enabled", JsonVal::Bool(false));
     st.set("stage1_pxe_enabled", JsonVal::Bool(false));
+    st.set("pxe_mode", JsonVal::Str("proxy".to_string()));
+    st.set("pxe_iface", JsonVal::Str(String::new()));
     st.set("pxe_host", JsonVal::Str(String::new()));
     st.set("pxe_host", JsonVal::Str(String::new()));
-    st.set("pxe_server_ip", JsonVal::Str("192.168.0.10".to_string()));
+    st.set("pxe_server_ip", JsonVal::Str(String::new()));
     st.set("pxe_subnet_mask", JsonVal::Str("255.255.255.0".to_string()));
     st.set("pxe_subnet_mask", JsonVal::Str("255.255.255.0".to_string()));
     st.set("pxe_client_ip", JsonVal::Str("192.168.0.160".to_string()));
     st.set("pxe_client_ip", JsonVal::Str("192.168.0.160".to_string()));
+    st.set("pxe_dhcp_range_start", JsonVal::Str("192.168.0.100".to_string()));
+    st.set("pxe_dhcp_range_end", JsonVal::Str("192.168.0.220".to_string()));
+    st.set("pxe_mac_whitelist", JsonVal::Arr(Vec::new()));
     st.set("mt86_cfg", cfg);
     st.set("mt86_cfg", cfg);
     st.set("recent_reports", JsonVal::Arr(Vec::new()));
     st.set("recent_reports", JsonVal::Arr(Vec::new()));
     st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
     st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
@@ -100,11 +151,29 @@ pub fn build_pxe_snapshot(pxe_state: &JsonVal) -> JsonVal {
         JsonVal::Str(PXE_EFI_DESCRIPTION.to_string()),
         JsonVal::Str(PXE_EFI_DESCRIPTION.to_string()),
     );
     );
     snap.set("stage1_pxe_enabled", JsonVal::Bool(stage1_en));
     snap.set("stage1_pxe_enabled", JsonVal::Bool(stage1_en));
+    snap.set("pxe_mode", JsonVal::Str(pxe_state.get_str_or("pxe_mode", "proxy")));
+    snap.set("pxe_iface", JsonVal::Str(pxe_state.get_str_or("pxe_iface", "")));
     let pxe_host = pxe_state.get_str_or("pxe_host", "");
     let pxe_host = pxe_state.get_str_or("pxe_host", "");
     snap.set("local_all_in_one", JsonVal::Bool(is_local_pxe_host(&pxe_host)));
     snap.set("local_all_in_one", JsonVal::Bool(is_local_pxe_host(&pxe_host)));
     snap.set("pxe_host", JsonVal::Str(pxe_host));
     snap.set("pxe_host", JsonVal::Str(pxe_host));
-    snap.set("pxe_server_ip", JsonVal::Str(pxe_state.get_str_or("pxe_server_ip", "192.168.0.10")));
+    snap.set("pxe_server_ip", JsonVal::Str(pxe_state.get_str_or("pxe_server_ip", "")));
+    snap.set("pxe_subnet_mask", JsonVal::Str(pxe_state.get_str_or("pxe_subnet_mask", "255.255.255.0")));
     snap.set("pxe_client_ip", JsonVal::Str(pxe_state.get_str_or("pxe_client_ip", "192.168.0.160")));
     snap.set("pxe_client_ip", JsonVal::Str(pxe_state.get_str_or("pxe_client_ip", "192.168.0.160")));
+    snap.set(
+        "pxe_dhcp_range_start",
+        JsonVal::Str(pxe_state.get_str_or("pxe_dhcp_range_start", "192.168.0.100")),
+    );
+    snap.set(
+        "pxe_dhcp_range_end",
+        JsonVal::Str(pxe_state.get_str_or("pxe_dhcp_range_end", "192.168.0.220")),
+    );
+    snap.set(
+        "pxe_mac_whitelist",
+        pxe_state
+            .get("pxe_mac_whitelist")
+            .cloned()
+            .unwrap_or_else(|| JsonVal::Arr(Vec::new())),
+    );
     if let Some(cfg) = pxe_state.get("mt86_cfg") {
     if let Some(cfg) = pxe_state.get("mt86_cfg") {
         snap.set("mt86_cfg", cfg.clone());
         snap.set("mt86_cfg", cfg.clone());
     }
     }
@@ -403,13 +472,13 @@ pub fn write_local_mt86_candidates(pxe_tftp_dir: &Path, cfg_text: &str) -> PathB
     let _ = fs::create_dir_all(pxe_tftp_dir);
     let _ = fs::create_dir_all(pxe_tftp_dir);
     let main_path = pxe_tftp_dir.join("mt86.cfg");
     let main_path = pxe_tftp_dir.join("mt86.cfg");
     for cand in LOCAL_CFG_CANDIDATES {
     for cand in LOCAL_CFG_CANDIDATES {
-        let _ = fs::write(pxe_tftp_dir.join(cand), cfg_text.as_bytes());
+        let _ = crate::storage::atomic_write_bytes(&pxe_tftp_dir.join(cand), cfg_text.as_bytes());
     }
     }
     if let Ok(entries) = fs::read_dir(pxe_tftp_dir) {
     if let Ok(entries) = fs::read_dir(pxe_tftp_dir) {
         for entry in entries.flatten() {
         for entry in entries.flatten() {
             let fname = entry.file_name().to_string_lossy().to_string();
             let fname = entry.file_name().to_string_lossy().to_string();
             if fname.ends_with("-mt86.cfg") {
             if fname.ends_with("-mt86.cfg") {
-                let _ = fs::write(entry.path(), cfg_text.as_bytes());
+                let _ = crate::storage::atomic_write_bytes(&entry.path(), cfg_text.as_bytes());
             }
             }
         }
         }
     }
     }
@@ -434,14 +503,23 @@ pub fn sync_mt86_cfg_to_pxe_host(
             "已写入本地内置 TFTP 目录 (单机一体化 PXE 模式,无需同步外部主机)".to_string(),
             "已写入本地内置 TFTP 目录 (单机一体化 PXE 模式,无需同步外部主机)".to_string(),
         );
         );
     }
     }
+    let Some((ssh_user, ssh_pass)) = pxe_ssh_credentials() else {
+        return (
+            false,
+            format!(
+                "本地候选已写入(未配置 STL_PXE_SSH_USER/STL_PXE_SSH_PASS,跳过外部 PXE 主机 {} SSH 同步)",
+                pxe_host
+            ),
+        );
+    };
     if !probe_pxe_ssh(pxe_host, 250) {
     if !probe_pxe_ssh(pxe_host, 250) {
         return (false, format!("本地候选已全量写入(PXE 主机 {} 当前离线)", pxe_host));
         return (false, format!("本地候选已全量写入(PXE 主机 {} 当前离线)", pxe_host));
     }
     }
     let sftp_ok = match lib::ssh_sftp_put_file(
     let sftp_ok = match lib::ssh_sftp_put_file(
         pxe_host,
         pxe_host,
         22,
         22,
-        "xjkj",
-        "123456",
+        &ssh_user,
+        &ssh_pass,
         cfg_path,
         cfg_path,
         "/opt/pxe-server/tftp/mt86.cfg",
         "/opt/pxe-server/tftp/mt86.cfg",
         3000,
         3000,
@@ -451,16 +529,16 @@ pub fn sync_mt86_cfg_to_pxe_host(
             let _ = lib::ssh_exec_capture(
             let _ = lib::ssh_exec_capture(
                 pxe_host,
                 pxe_host,
                 22,
                 22,
-                "xjkj",
-                "123456",
+                &ssh_user,
+                &ssh_pass,
                 "mkdir -p /opt/pxe-server/tftp",
                 "mkdir -p /opt/pxe-server/tftp",
                 2000,
                 2000,
             );
             );
             lib::ssh_sftp_put_file(
             lib::ssh_sftp_put_file(
                 pxe_host,
                 pxe_host,
                 22,
                 22,
-                "xjkj",
-                "123456",
+                &ssh_user,
+                &ssh_pass,
                 cfg_path,
                 cfg_path,
                 "/opt/pxe-server/tftp/mt86.cfg",
                 "/opt/pxe-server/tftp/mt86.cfg",
                 3000,
                 3000,
@@ -484,7 +562,7 @@ pub fn sync_mt86_cfg_to_pxe_host(
              cp -f mt86.cfg memtest86.cfg; \
              cp -f mt86.cfg memtest86.cfg; \
            fi; \
            fi; \
          done";
          done";
-    let ssh_ok = lib::ssh_exec_capture(pxe_host, 22, "xjkj", "123456", remote_cmd, 4000)
+    let ssh_ok = lib::ssh_exec_capture(pxe_host, 22, &ssh_user, &ssh_pass, remote_cmd, 4000)
         .map(|(exit_code, _)| exit_code == 0)
         .map(|(exit_code, _)| exit_code == 0)
         .unwrap_or(false);
         .unwrap_or(false);
 
 
@@ -531,12 +609,32 @@ pub fn apply_pxe_configuration(
     pxe_state.remove("active_variant");
     pxe_state.remove("active_variant");
     pxe_state.set("active_efi", JsonVal::Str(PXE_EFI_FILENAME.to_string()));
     pxe_state.set("active_efi", JsonVal::Str(PXE_EFI_FILENAME.to_string()));
     pxe_state.set("stage1_pxe_enabled", JsonVal::Bool(stage1_en));
     pxe_state.set("stage1_pxe_enabled", JsonVal::Bool(stage1_en));
+    if let Some(m) = args.get_str("pxe_mode").or_else(|| args.get_str("mode")) {
+        pxe_state.set(
+            "pxe_mode",
+            JsonVal::Str(crate::pxe_dhcp::PxeBootMode::parse(m).as_str().to_string()),
+        );
+    }
+    if let Some(iface) = args.get_str("pxe_iface").or_else(|| args.get_str("iface")) {
+        pxe_state.set("pxe_iface", JsonVal::Str(iface.trim().to_string()));
+    }
     if let Some(h) = args.get_str("pxe_host") {
     if let Some(h) = args.get_str("pxe_host") {
         pxe_state.set("pxe_host", JsonVal::Str(h.trim().to_string()));
         pxe_state.set("pxe_host", JsonVal::Str(h.trim().to_string()));
     }
     }
     if let Some(ip) = args.get_str("pxe_server_ip") {
     if let Some(ip) = args.get_str("pxe_server_ip") {
-        if !ip.trim().is_empty() {
-            pxe_state.set("pxe_server_ip", JsonVal::Str(ip.trim().to_string()));
+        let trimmed = ip.trim();
+        if trimmed.eq_ignore_ascii_case("auto") {
+            pxe_state.set("pxe_server_ip", JsonVal::Str(String::new()));
+        } else {
+            pxe_state.set("pxe_server_ip", JsonVal::Str(trimmed.to_string()));
+        }
+    }
+    if let Some(mask) = args
+        .get_str("pxe_subnet_mask")
+        .or_else(|| args.get_str("pxe_netmask"))
+    {
+        if !mask.trim().is_empty() {
+            pxe_state.set("pxe_subnet_mask", JsonVal::Str(mask.trim().to_string()));
         }
         }
     }
     }
     if let Some(ip) = args.get_str("pxe_client_ip") {
     if let Some(ip) = args.get_str("pxe_client_ip") {
@@ -544,6 +642,23 @@ pub fn apply_pxe_configuration(
             pxe_state.set("pxe_client_ip", JsonVal::Str(ip.trim().to_string()));
             pxe_state.set("pxe_client_ip", JsonVal::Str(ip.trim().to_string()));
         }
         }
     }
     }
+    if let Some(rs) = args.get_str("pxe_dhcp_range_start") {
+        if !rs.trim().is_empty() {
+            pxe_state.set("pxe_dhcp_range_start", JsonVal::Str(rs.trim().to_string()));
+        }
+    }
+    if let Some(re) = args.get_str("pxe_dhcp_range_end") {
+        if !re.trim().is_empty() {
+            pxe_state.set("pxe_dhcp_range_end", JsonVal::Str(re.trim().to_string()));
+        }
+    }
+    if let Some(wl) = args.get("pxe_mac_whitelist") {
+        let parsed = crate::pxe_dhcp::parse_mac_whitelist(wl);
+        pxe_state.set(
+            "pxe_mac_whitelist",
+            JsonVal::Arr(parsed.into_iter().map(JsonVal::Str).collect()),
+        );
+    }
     let cfg_obj = args
     let cfg_obj = args
         .get("mt86_cfg")
         .get("mt86_cfg")
         .cloned()
         .cloned()
@@ -1589,15 +1704,35 @@ fn is_mt86_cfg_name(base_lower: &str) -> bool {
     ) || base_lower.ends_with("-mt86.cfg")
     ) || base_lower.ends_with("-mt86.cfg")
 }
 }
 
 
-fn resolve_tftp_rrq_bytes(hub: &crate::api::AppHub, raw_name: &str) -> Option<Vec<u8>> {
-    let rel = sanitize_tftp_rel_path(raw_name)?;
-    let fname = rel.file_name()?.to_string_lossy().to_string();
+fn extract_mac_prefix_from_cfg_name(base_lower: &str) -> Option<String> {
+    let prefix = base_lower.strip_suffix("-mt86.cfg")?;
+    crate::pxe_dhcp::normalize_mac(prefix)
+}
+
+/// Shared payload resolver for both built-in UDP :69 TFTP RRQ and HTTP `/pxe/<filename>` UEFI HTTP Boot.
+/// Dynamically generates per-station `mt86.cfg` in memory keyed by client MAC (`<mac>-mt86.cfg`,
+/// ProxyDHCP IP->MAC table, or Linux ARP table) so concurrent stations never clobber one another!
+pub fn resolve_pxe_payload(
+    hub: &crate::api::AppHub,
+    filename: &str,
+    peer_ip: &str,
+    local_ip_hint: &str,
+) -> Option<Vec<u8>> {
+    let rel = sanitize_tftp_rel_path(filename)?;
+    let fname = rel.file_name()?.to_str()?.to_string();
     let base_lower = fname.to_ascii_lowercase();
     let base_lower = fname.to_ascii_lowercase();
 
 
     if base_lower == "pxe_sync.efi" {
     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 exe_fallback = std::env::current_exe()
+            .ok()
+            .and_then(|p| p.parent().map(|d| d.join("pxe_sync.efi")));
+        let tpl_path = if hub.pxe_tftp_dir.join("pxe_sync.efi").is_file() {
+            Some(hub.pxe_tftp_dir.join("pxe_sync.efi"))
+        } else {
+            exe_fallback.filter(|p| p.is_file())
+        };
+        if let Some(tpl_p) = tpl_path {
+            if let Ok(tpl) = fs::read(&tpl_p) {
                 let active_name = hub
                 let active_name = hub
                     .pxe_state
                     .pxe_state
                     .read()
                     .read()
@@ -1630,6 +1765,50 @@ fn resolve_tftp_rrq_bytes(hub: &crate::api::AppHub, raw_name: &str) -> Option<Ve
     }
     }
 
 
     if is_mt86_cfg_name(&base_lower) {
     if is_mt86_cfg_name(&base_lower) {
+        let effective_tftp_ip = if !local_ip_hint.trim().is_empty()
+            && local_ip_hint.trim() != "0.0.0.0"
+            && local_ip_hint.trim() != "127.0.0.1"
+        {
+            local_ip_hint.trim().to_string()
+        } else {
+            let from_state = hub
+                .pxe_state
+                .read()
+                .ok()
+                .map(|st| st.get_str_or("pxe_server_ip", ""))
+                .unwrap_or_default();
+            if !from_state.trim().is_empty() && from_state.trim() != "auto" {
+                from_state
+            } else {
+                hub.pxe_dhcp_hub.effective_server_ip()
+            }
+        };
+
+        // 1. Per-station dynamic rendering by client MAC (zero file race across hundreds of machines!)
+        let peer_mac = extract_mac_prefix_from_cfg_name(&base_lower)
+            .or_else(|| hub.pxe_dhcp_hub.lookup_mac_by_ip(peer_ip))
+            .or_else(|| lookup_arp_mac_for_ip(peer_ip));
+        if let Some(ref mac) = peer_mac {
+            for (_sid, handle) in hub.stations_snapshot() {
+                if let Ok(view) = handle.view.read() {
+                    if let Some(st_mac) = crate::pxe_dhcp::normalize_mac(&view.os_mac) {
+                        if st_mac == *mac {
+                            let mt_sel = view
+                                .control_base
+                                .get("firmware_settings")
+                                .and_then(|f| f.get("mt_selection"))
+                                .cloned()
+                                .unwrap_or_else(JsonVal::obj);
+                            return Some(
+                                render_mt86_cfg_text(&mt_sel, &effective_tftp_ip).into_bytes(),
+                            );
+                        }
+                    }
+                }
+            }
+        }
+
+        // 2. Global on-disk candidate or pxe_state fallback
         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() {
                 if let Ok(b) = fs::read(&cand) {
                 if let Ok(b) = fs::read(&cand) {
@@ -1644,8 +1823,7 @@ fn resolve_tftp_rrq_bytes(hub: &crate::api::AppHub, raw_name: &str) -> Option<Ve
                 .get("mt86_cfg")
                 .get("mt86_cfg")
                 .cloned()
                 .cloned()
                 .unwrap_or_else(JsonVal::obj);
                 .unwrap_or_else(JsonVal::obj);
-            let tftp_ip = st.get_str_or("pxe_server_ip", "192.168.0.10");
-            return Some(render_mt86_cfg_text(&cfg_val, &tftp_ip).into_bytes());
+            return Some(render_mt86_cfg_text(&cfg_val, &effective_tftp_ip).into_bytes());
         }
         }
     }
     }
 
 
@@ -1681,6 +1859,10 @@ fn resolve_tftp_rrq_bytes(hub: &crate::api::AppHub, raw_name: &str) -> Option<Ve
     None
     None
 }
 }
 
 
+fn resolve_tftp_rrq_bytes(hub: &crate::api::AppHub, filename: &str, peer: SocketAddr) -> Option<Vec<u8>> {
+    resolve_pxe_payload(hub, filename, &peer.ip().to_string(), "")
+}
+
 fn negotiate_tftp_options(
 fn negotiate_tftp_options(
     opts: &[(String, String)],
     opts: &[(String, String)],
     file_size_for_rrq: Option<usize>,
     file_size_for_rrq: Option<usize>,
@@ -1749,7 +1931,7 @@ fn handle_tftp_rrq(
     let Ok(sock) = UdpSocket::bind("0.0.0.0:0") else {
     let Ok(sock) = UdpSocket::bind("0.0.0.0:0") else {
         return;
         return;
     };
     };
-    let Some(data) = resolve_tftp_rrq_bytes(&hub, &filename) else {
+    let Some(data) = resolve_tftp_rrq_bytes(&hub, &filename, peer) else {
         append_system_debug_log(
         append_system_debug_log(
             &hub.data_dir,
             &hub.data_dir,
             "PXE",
             "PXE",
@@ -1850,7 +2032,8 @@ fn lookup_arp_mac_for_ip(ip_str: &str) -> Option<String> {
     let txt = fs::read_to_string("/proc/net/arp").ok()?;
     let txt = fs::read_to_string("/proc/net/arp").ok()?;
     for line in txt.lines().skip(1) {
     for line in txt.lines().skip(1) {
         let cols: Vec<&str> = line.split_whitespace().collect();
         let cols: Vec<&str> = line.split_whitespace().collect();
-        if cols.len() >= 4 && cols[0] == ip_str {
+        // Skip incomplete ARP entries (Flags == 0x0)
+        if cols.len() >= 4 && cols[0] == ip_str && cols[2] != "0x0" {
             let mac = cols[3].trim().to_ascii_lowercase();
             let mac = cols[3].trim().to_ascii_lowercase();
             if mac.len() == 17 && mac != "00:00:00:00:00:00" {
             if mac.len() == 17 && mac != "00:00:00:00:00:00" {
                 return Some(mac);
                 return Some(mac);
@@ -2033,6 +2216,7 @@ fn handle_tftp_wrq(
             .cloned()
             .cloned()
             .unwrap_or_default();
             .unwrap_or_default();
         rpts.insert(0, report.clone());
         rpts.insert(0, report.clone());
+        rpts.truncate(50);
         pxe_st.set("recent_reports", JsonVal::Arr(rpts));
         pxe_st.set("recent_reports", JsonVal::Arr(rpts));
         pxe_st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
         pxe_st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
         if let Err(e) = crate::storage::atomic_write_bytes(
         if let Err(e) = crate::storage::atomic_write_bytes(
@@ -2048,13 +2232,18 @@ fn handle_tftp_wrq(
     }
     }
 
 
     // Deliver HTML/XML report strictly to the originating station:
     // Deliver HTML/XML report strictly to the originating station:
-    // Tier 0: same-LAN ARP peer MAC == station.os_mac
+    // Tier 0: same-LAN ProxyDHCP or ARP peer MAC == normalized station.os_mac
     // Tier 1: exact expected_mt_report_name
     // Tier 1: exact expected_mt_report_name
     // Tier 2: DIMM serial number found inside report
     // Tier 2: DIMM serial number found inside report
-    // Tier 3: active mt/uefi phase using 118.efi
+    // Tier 3: sole active mt/uefi phase using 118.efi (never broadcast to multiple stations!)
     // Tier 4: sole online/running station
     // Tier 4: sole online/running station
     let full_path_str = dest_path.to_string_lossy().to_string();
     let full_path_str = dest_path.to_string_lossy().to_string();
-    let peer_mac = lookup_arp_mac_for_ip(&peer.ip().to_string()).unwrap_or_default();
+    let peer_ip_str = peer.ip().to_string();
+    let peer_mac = hub
+        .pxe_dhcp_hub
+        .lookup_mac_by_ip(&peer_ip_str)
+        .or_else(|| lookup_arp_mac_for_ip(&peer_ip_str))
+        .unwrap_or_default();
     let mut mac_match_targets: Vec<String> = Vec::new();
     let mut mac_match_targets: Vec<String> = Vec::new();
     let mut exact_name_targets: Vec<String> = Vec::new();
     let mut exact_name_targets: Vec<String> = Vec::new();
     let mut sn_match_targets: Vec<String> = Vec::new();
     let mut sn_match_targets: Vec<String> = Vec::new();
@@ -2065,9 +2254,13 @@ fn handle_tftp_wrq(
     let stations_snap = hub.stations_snapshot();
     let stations_snap = hub.stations_snapshot();
     for (sid, handle) in &stations_snap {
     for (sid, handle) in &stations_snap {
         if let Ok(v) = handle.view.read() {
         if let Ok(v) = handle.view.read() {
-            if !peer_mac.is_empty() && !v.os_mac.is_empty() && v.os_mac.eq_ignore_ascii_case(&peer_mac) {
-                mac_match_targets.push(sid.clone());
-                continue;
+            if !peer_mac.is_empty() {
+                if let Some(st_mac) = crate::pxe_dhcp::normalize_mac(&v.os_mac) {
+                    if st_mac == peer_mac {
+                        mac_match_targets.push(sid.clone());
+                        continue;
+                    }
+                }
             }
             }
             let exp_base = Path::new(v.expected_mt_report_name.trim())
             let exp_base = Path::new(v.expected_mt_report_name.trim())
                 .file_name()
                 .file_name()
@@ -2110,7 +2303,7 @@ fn handle_tftp_wrq(
         exact_name_targets
         exact_name_targets
     } else if !sn_match_targets.is_empty() {
     } else if !sn_match_targets.is_empty() {
         sn_match_targets
         sn_match_targets
-    } else if !mt_or_uefi_targets.is_empty() {
+    } else if mt_or_uefi_targets.len() == 1 {
         mt_or_uefi_targets
         mt_or_uefi_targets
     } else if online_targets.len() == 1 {
     } else if online_targets.len() == 1 {
         online_targets
         online_targets
@@ -2324,6 +2517,7 @@ pub fn sync_remote_pxe_report_async(
             }
             }
             let host_trimmed = pxe_host.trim().to_string();
             let host_trimmed = pxe_host.trim().to_string();
             if !sent_report && !is_local_pxe_host(&host_trimmed) {
             if !sent_report && !is_local_pxe_host(&host_trimmed) {
+                if let Some((ssh_user, ssh_pass)) = pxe_ssh_credentials() {
                 let min_epoch = ((min_unix_ms.saturating_sub(5_000)) / 1000).max(0);
                 let min_epoch = ((min_unix_ms.saturating_sub(5_000)) / 1000).max(0);
                 let clean_expected = sanitize_report_basename(&expected_filename);
                 let clean_expected = sanitize_report_basename(&expected_filename);
                 let latest_cmd = "ls -1t /opt/pxe-server/tftp/MemTest86-Report-*.html /srv/tftp/MemTest86-Report-*.html /opt/pxe-server/tftp/Clients/*.TestResult.xml /srv/tftp/Clients/*.TestResult.xml 2>/dev/null | head -n 1 | while read f; do [ -n \"$f\" ] && echo \"LATEST|$(stat -c '%Y|%s|%n' \"$f\")\"; done";
                 let latest_cmd = "ls -1t /opt/pxe-server/tftp/MemTest86-Report-*.html /srv/tftp/MemTest86-Report-*.html /opt/pxe-server/tftp/Clients/*.TestResult.xml /srv/tftp/Clients/*.TestResult.xml 2>/dev/null | head -n 1 | while read f; do [ -n \"$f\" ] && echo \"LATEST|$(stat -c '%Y|%s|%n' \"$f\")\"; done";
@@ -2351,8 +2545,8 @@ pub fn sync_remote_pxe_report_async(
                     if let Ok((exit_code, stdout)) = lib::ssh_exec_capture(
                     if let Ok((exit_code, stdout)) = lib::ssh_exec_capture(
                         &host_trimmed,
                         &host_trimmed,
                         22,
                         22,
-                        "xjkj",
-                        "123456",
+                        &ssh_user,
+                        &ssh_pass,
                         &remote_cmd,
                         &remote_cmd,
                         3000,
                         3000,
                     ) {
                     ) {
@@ -2383,8 +2577,8 @@ pub fn sync_remote_pxe_report_async(
                                     if lib::ssh_sftp_get_file(
                                     if lib::ssh_sftp_get_file(
                                         &host_trimmed,
                                         &host_trimmed,
                                         22,
                                         22,
-                                        "xjkj",
-                                        "123456",
+                                        &ssh_user,
+                                        &ssh_pass,
                                         rp,
                                         rp,
                                         &dest_path,
                                         &dest_path,
                                         4000,
                                         4000,
@@ -2428,6 +2622,7 @@ pub fn sync_remote_pxe_report_async(
                         thread::sleep(Duration::from_millis(850));
                         thread::sleep(Duration::from_millis(850));
                     }
                     }
                 }
                 }
+                }
             }
             }
             let _ = actor_tx.send(StationMsg::MtReportSyncDone { fetched: sent_report });
             let _ = actor_tx.send(StationMsg::MtReportSyncDone { fetched: sent_report });
             inflight.store(false, Ordering::Release);
             inflight.store(false, Ordering::Release);
@@ -2442,11 +2637,13 @@ pub fn sync_remote_pxe_report_async(
 pub fn spawn_tftp_server(listen_addr: &str, hub: Arc<crate::api::AppHub>) -> Option<SocketAddr> {
 pub fn spawn_tftp_server(listen_addr: &str, hub: Arc<crate::api::AppHub>) -> Option<SocketAddr> {
     let trimmed = listen_addr.trim();
     let trimmed = listen_addr.trim();
     if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("disabled") {
     if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("disabled") {
+        hub.pxe_dhcp_hub.set_tftp_bound(false);
         return None;
         return None;
     }
     }
     let sock = match UdpSocket::bind(trimmed) {
     let sock = match UdpSocket::bind(trimmed) {
         Ok(s) => s,
         Ok(s) => s,
         Err(e) => {
         Err(e) => {
+            hub.pxe_dhcp_hub.set_tftp_bound(false);
             eprintln!(
             eprintln!(
                 "[stl_native_server] Warning: failed to bind TFTP {}: {} (skipping built-in TFTP)",
                 "[stl_native_server] Warning: failed to bind TFTP {}: {} (skipping built-in TFTP)",
                 trimmed, e
                 trimmed, e
@@ -2454,6 +2651,7 @@ pub fn spawn_tftp_server(listen_addr: &str, hub: Arc<crate::api::AppHub>) -> Opt
             return None;
             return None;
         }
         }
     };
     };
+    hub.pxe_dhcp_hub.set_tftp_bound(true);
     let bound_addr = sock.local_addr().ok();
     let bound_addr = sock.local_addr().ok();
     eprintln!(
     eprintln!(
         "[stl_native_server] Built-in UDP TFTP server listening on {} (dir={})",
         "[stl_native_server] Built-in UDP TFTP server listening on {} (dir={})",
@@ -2463,6 +2661,8 @@ pub fn spawn_tftp_server(listen_addr: &str, hub: Arc<crate::api::AppHub>) -> Opt
         hub.pxe_tftp_dir.display()
         hub.pxe_tftp_dir.display()
     );
     );
 
 
+    const MAX_TFTP_WORKERS: usize = 32;
+    let active_workers = Arc::new(std::sync::atomic::AtomicUsize::new(0));
     thread::Builder::new()
     thread::Builder::new()
         .name("stl-tftp".to_string())
         .name("stl-tftp".to_string())
         .spawn(move || {
         .spawn(move || {
@@ -2471,13 +2671,21 @@ pub fn spawn_tftp_server(listen_addr: &str, hub: Arc<crate::api::AppHub>) -> Opt
                 match sock.recv_from(&mut buf) {
                 match sock.recv_from(&mut buf) {
                     Ok((n, peer)) => {
                     Ok((n, peer)) => {
                         if let Some((op, filename, _mode, opts)) = parse_tftp_request(&buf[..n]) {
                         if let Some((op, filename, _mode, opts)) = parse_tftp_request(&buf[..n]) {
+                            let prev = active_workers.fetch_add(1, Ordering::AcqRel);
+                            if prev >= MAX_TFTP_WORKERS {
+                                active_workers.fetch_sub(1, Ordering::AcqRel);
+                                send_tftp_error(&sock, peer, 0, "TFTP server busy");
+                                continue;
+                            }
                             let h = Arc::clone(&hub);
                             let h = Arc::clone(&hub);
+                            let counter = Arc::clone(&active_workers);
                             thread::spawn(move || {
                             thread::spawn(move || {
                                 if op == 1 {
                                 if op == 1 {
                                     handle_tftp_rrq(h, peer, filename, opts);
                                     handle_tftp_rrq(h, peer, filename, opts);
                                 } else if op == 2 {
                                 } else if op == 2 {
                                     handle_tftp_wrq(h, peer, filename, opts);
                                     handle_tftp_wrq(h, peer, filename, opts);
                                 }
                                 }
+                                counter.fetch_sub(1, Ordering::AcqRel);
                             });
                             });
                         }
                         }
                     }
                     }

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1485 - 0
native/stl_accel/src/pxe_dhcp.rs


+ 323 - 25
native/stl_accel/src/results.rs

@@ -175,8 +175,12 @@ pub struct DimmSoA24 {
     pub stage_mt: [u8; 24],       // 0=idle, 1=pass, 2=fail
     pub stage_mt: [u8; 24],       // 0=idle, 1=pass, 2=fail
     pub rmt_rx_dq_lo: [i16; 24],
     pub rmt_rx_dq_lo: [i16; 24],
     pub rmt_rx_dq_hi: [i16; 24],
     pub rmt_rx_dq_hi: [i16; 24],
+    pub rmt_tx_dq_lo: [i16; 24],
+    pub rmt_tx_dq_hi: [i16; 24],
     pub rmt_rx_vref_lo: [i16; 24],
     pub rmt_rx_vref_lo: [i16; 24],
     pub rmt_rx_vref_hi: [i16; 24],
     pub rmt_rx_vref_hi: [i16; 24],
+    pub rmt_tx_vref_lo: [i16; 24],
+    pub rmt_tx_vref_hi: [i16; 24],
 }
 }
 
 
 impl Default for DimmSoA24 {
 impl Default for DimmSoA24 {
@@ -192,8 +196,12 @@ impl Default for DimmSoA24 {
             stage_mt: [0; 24],
             stage_mt: [0; 24],
             rmt_rx_dq_lo: [0; 24],
             rmt_rx_dq_lo: [0; 24],
             rmt_rx_dq_hi: [0; 24],
             rmt_rx_dq_hi: [0; 24],
+            rmt_tx_dq_lo: [0; 24],
+            rmt_tx_dq_hi: [0; 24],
             rmt_rx_vref_lo: [0; 24],
             rmt_rx_vref_lo: [0; 24],
             rmt_rx_vref_hi: [0; 24],
             rmt_rx_vref_hi: [0; 24],
+            rmt_tx_vref_lo: [0; 24],
+            rmt_tx_vref_hi: [0; 24],
         }
         }
     }
     }
 }
 }
@@ -206,8 +214,12 @@ impl DimmSoA24 {
         self.stage_mt = [0; 24];
         self.stage_mt = [0; 24];
         self.rmt_rx_dq_lo = [0; 24];
         self.rmt_rx_dq_lo = [0; 24];
         self.rmt_rx_dq_hi = [0; 24];
         self.rmt_rx_dq_hi = [0; 24];
+        self.rmt_tx_dq_lo = [0; 24];
+        self.rmt_tx_dq_hi = [0; 24];
         self.rmt_rx_vref_lo = [0; 24];
         self.rmt_rx_vref_lo = [0; 24];
         self.rmt_rx_vref_hi = [0; 24];
         self.rmt_rx_vref_hi = [0; 24];
+        self.rmt_tx_vref_lo = [0; 24];
+        self.rmt_tx_vref_hi = [0; 24];
         for e in &mut self.enabled {
         for e in &mut self.enabled {
             if *e == 2 {
             if *e == 2 {
                 *e = 0;
                 *e = 0;
@@ -222,16 +234,51 @@ impl DimmSoA24 {
             let base = i * 8;
             let base = i * 8;
             out[base] = self.rmt_rx_dq_lo[i] as f32;
             out[base] = self.rmt_rx_dq_lo[i] as f32;
             out[base + 1] = self.rmt_rx_dq_hi[i] as f32;
             out[base + 1] = self.rmt_rx_dq_hi[i] as f32;
-            out[base + 2] = self.rmt_rx_dq_lo[i] as f32;
-            out[base + 3] = self.rmt_rx_dq_hi[i] as f32;
+            out[base + 2] = self.rmt_tx_dq_lo[i] as f32;
+            out[base + 3] = self.rmt_tx_dq_hi[i] as f32;
             out[base + 4] = self.rmt_rx_vref_lo[i] as f32;
             out[base + 4] = self.rmt_rx_vref_lo[i] as f32;
             out[base + 5] = self.rmt_rx_vref_hi[i] as f32;
             out[base + 5] = self.rmt_rx_vref_hi[i] as f32;
-            out[base + 6] = self.rmt_rx_vref_lo[i] as f32;
-            out[base + 7] = self.rmt_rx_vref_hi[i] as f32;
+            out[base + 6] = self.rmt_tx_vref_lo[i] as f32;
+            out[base + 7] = self.rmt_tx_vref_hi[i] as f32;
         }
         }
     }
     }
 }
 }
 
 
+#[derive(Clone, Debug)]
+pub struct BmcSensorReading {
+    pub name: String,
+    pub category: String, // "temp" | "voltage" | "fan" | "current" | "power" | "discrete" | "other"
+    pub value: Option<f64>,
+    pub unit: String,
+    pub status: String,
+    pub raw_hex: String,
+    pub sensor_type: String,
+    pub updated_ms: i64,
+}
+
+impl BmcSensorReading {
+    pub fn to_json(&self) -> JsonVal {
+        let mut o = JsonVal::obj();
+        o.set("name", JsonVal::Str(self.name.clone()));
+        o.set("category", JsonVal::Str(self.category.clone()));
+        if let Some(v) = self.value {
+            o.set("value", JsonVal::Num(v));
+        } else {
+            o.set("value", JsonVal::Null);
+        }
+        o.set("unit", JsonVal::Str(self.unit.clone()));
+        o.set("status", JsonVal::Str(self.status.clone()));
+        if !self.raw_hex.is_empty() {
+            o.set("raw_hex", JsonVal::Str(self.raw_hex.clone()));
+        }
+        if !self.sensor_type.is_empty() {
+            o.set("sensor_type", JsonVal::Str(self.sensor_type.clone()));
+        }
+        o.set("updated_ms", JsonVal::Num(self.updated_ms as f64));
+        o
+    }
+}
+
 #[derive(Clone, Debug)]
 #[derive(Clone, Debug)]
 pub struct DimmSlot {
 pub struct DimmSlot {
     pub value_c: Option<f64>,
     pub value_c: Option<f64>,
@@ -396,7 +443,13 @@ pub struct WatchdogConfig {
     pub amt_max_duration_ms: i64,
     pub amt_max_duration_ms: i64,
     pub mt_silence_timeout_ms: i64,
     pub mt_silence_timeout_ms: i64,
     pub mt_max_duration_ms: i64,
     pub mt_max_duration_ms: i64,
+    /// Hang handling policy:
+    /// - `"stop"`: freeze timer, preserve hang scene, cool hood, do not reboot.
+    /// - `"retry_current_task"`: archive hung attempt, reboot via BMC, redo the same unfinished task/round.
+    /// - `"restart_full_plan"`: archive hung attempt, reboot via BMC, restart the entire plan/batch from Profile 1 Round 1.
+    pub hang_action: String,
     pub reboot_on_hang: bool,
     pub reboot_on_hang: bool,
+    /// 0 = unlimited retries; >=1 = stop and preserve hang scene after this many consecutive hangs.
     pub max_consecutive_hangs: u32,
     pub max_consecutive_hangs: u32,
     pub reconnect_prompt_probe_delay_ms: i64,
     pub reconnect_prompt_probe_delay_ms: i64,
 }
 }
@@ -411,14 +464,34 @@ impl Default for WatchdogConfig {
             amt_max_duration_ms: 3_600_000,          // 60 min total AMT stage cap
             amt_max_duration_ms: 3_600_000,          // 60 min total AMT stage cap
             mt_silence_timeout_ms: 480_000,          // 8 min (5~10 min for MemTest86 block silence)
             mt_silence_timeout_ms: 480_000,          // 8 min (5~10 min for MemTest86 block silence)
             mt_max_duration_ms: 3_600_000,           // 60 min total MemTest86 stage cap
             mt_max_duration_ms: 3_600_000,           // 60 min total MemTest86 stage cap
-            reboot_on_hang: false,                   // Level-1 default: preserve hang scene!
-            max_consecutive_hangs: 2,                // Circuit breaker for unattended reboot_on_hang
+            hang_action: "stop".to_string(),         // Default: preserve hang scene!
+            reboot_on_hang: false,
+            max_consecutive_hangs: 2,                // 0 = unlimited
             reconnect_prompt_probe_delay_ms: 1_500,  // 1.5s silent delay before probing prompt with CR
             reconnect_prompt_probe_delay_ms: 1_500,  // 1.5s silent delay before probing prompt with CR
         }
         }
     }
     }
 }
 }
 
 
+pub fn normalize_hang_action(raw: &str) -> &'static str {
+    match raw.trim().to_ascii_lowercase().as_str() {
+        "retry_current_task" | "retry_task" | "retry_round" | "retry" => "retry_current_task",
+        "restart_full_plan" | "restart_plan" | "restart_all" | "restart_batch" => "restart_full_plan",
+        _ => "stop",
+    }
+}
+
 impl WatchdogConfig {
 impl WatchdogConfig {
+    pub fn effective_hang_action(&self) -> &'static str {
+        let norm = normalize_hang_action(&self.hang_action);
+        if norm != "stop" {
+            norm
+        } else if self.reboot_on_hang {
+            "retry_current_task"
+        } else {
+            "stop"
+        }
+    }
+
     pub fn to_json(&self) -> JsonVal {
     pub fn to_json(&self) -> JsonVal {
         let mut o = JsonVal::obj();
         let mut o = JsonVal::obj();
         o.set("enabled", JsonVal::Bool(self.enabled));
         o.set("enabled", JsonVal::Bool(self.enabled));
@@ -470,7 +543,9 @@ impl WatchdogConfig {
             "mt_max_duration_s",
             "mt_max_duration_s",
             JsonVal::Num((self.mt_max_duration_ms / 1000) as f64),
             JsonVal::Num((self.mt_max_duration_ms / 1000) as f64),
         );
         );
-        o.set("reboot_on_hang", JsonVal::Bool(self.reboot_on_hang));
+        let eff_action = self.effective_hang_action();
+        o.set("hang_action", JsonVal::Str(eff_action.to_string()));
+        o.set("reboot_on_hang", JsonVal::Bool(eff_action != "stop"));
         o.set(
         o.set(
             "max_consecutive_hangs",
             "max_consecutive_hangs",
             JsonVal::Num(self.max_consecutive_hangs as f64),
             JsonVal::Num(self.max_consecutive_hangs as f64),
@@ -516,11 +591,20 @@ impl WatchdogConfig {
         } else if let Some(sec) = raw.get_i64("mt_max_duration_s") {
         } else if let Some(sec) = raw.get_i64("mt_max_duration_s") {
             self.mt_max_duration_ms = (sec.saturating_mul(1000)).max(0);
             self.mt_max_duration_ms = (sec.saturating_mul(1000)).max(0);
         }
         }
-        if let Some(roh) = raw.get_bool("reboot_on_hang") {
+        if let Some(ha) = raw.get_str("hang_action") {
+            let norm = normalize_hang_action(ha);
+            self.hang_action = norm.to_string();
+            self.reboot_on_hang = norm != "stop";
+        } else if let Some(roh) = raw.get_bool("reboot_on_hang") {
             self.reboot_on_hang = roh;
             self.reboot_on_hang = roh;
+            if !roh {
+                self.hang_action = "stop".to_string();
+            } else if self.hang_action == "stop" {
+                self.hang_action = "retry_current_task".to_string();
+            }
         }
         }
         if let Some(mch) = raw.get_i64("max_consecutive_hangs") {
         if let Some(mch) = raw.get_i64("max_consecutive_hangs") {
-            self.max_consecutive_hangs = mch.max(1) as u32;
+            self.max_consecutive_hangs = mch.clamp(0, 100) as u32;
         }
         }
         if let Some(pms) = raw.get_i64("reconnect_prompt_probe_delay_ms") {
         if let Some(pms) = raw.get_i64("reconnect_prompt_probe_delay_ms") {
             self.reconnect_prompt_probe_delay_ms = pms.max(100);
             self.reconnect_prompt_probe_delay_ms = pms.max(100);
@@ -602,6 +686,12 @@ pub struct StationState {
     pub observed_stages: BTreeSet<String>,
     pub observed_stages: BTreeSet<String>,
     pub stage_step_counts: BTreeMap<String, usize>,
     pub stage_step_counts: BTreeMap<String, usize>,
     pub dimms: Vec<DimmSlot>,
     pub dimms: Vec<DimmSlot>,
+    pub bmc_sensors: Vec<BmcSensorReading>,
+    pub bmc_sensors_updated_ms: i64,
+    pub bmc_sensor_history: VecDeque<JsonVal>,
+    pub last_bmc_history_ms: i64,
+    pub dimm_temp_curves: Vec<VecDeque<(i64, f64)>>,
+    pub rmt_status: String, // "unobserved" | "running" | "completed" | "skipped"
     pub rmt_results: BTreeMap<i64, RmtCpuResult>,
     pub rmt_results: BTreeMap<i64, RmtCpuResult>,
     pub amt_results: BTreeMap<i64, AmtCpuResult>,
     pub amt_results: BTreeMap<i64, AmtCpuResult>,
     pub active_amt_cpus: BTreeSet<i64>,
     pub active_amt_cpus: BTreeSet<i64>,
@@ -814,8 +904,8 @@ impl StationState {
             tcp_listener_port: 0,
             tcp_listener_port: 0,
             pty_open_gen: 0,
             pty_open_gen: 0,
             next_reconnect_probe_ms: 0,
             next_reconnect_probe_ms: 0,
-            raw_ring: lib::MonotonicRingBuffer::new(raw_ring_bytes.max(2 * 1024 * 1024)),
-            clean_ring: lib::MonotonicRingBuffer::new(clean_ring_bytes.max(2 * 1024 * 1024)),
+            raw_ring: lib::MonotonicRingBuffer::new(raw_ring_bytes.max(256 * 1024)),
+            clean_ring: lib::MonotonicRingBuffer::new(clean_ring_bytes.max(256 * 1024)),
             cleaner: lib::NativeStreamCleaner::new(),
             cleaner: lib::NativeStreamCleaner::new(),
             tx_pacer: NonBlockingTxPacer::default(),
             tx_pacer: NonBlockingTxPacer::default(),
             async_script: AsyncCommandScript::default(),
             async_script: AsyncCommandScript::default(),
@@ -839,6 +929,12 @@ impl StationState {
             observed_stages: BTreeSet::new(),
             observed_stages: BTreeSet::new(),
             stage_step_counts: BTreeMap::new(),
             stage_step_counts: BTreeMap::new(),
             dimms,
             dimms,
+            bmc_sensors: Vec::new(),
+            bmc_sensors_updated_ms: 0,
+            bmc_sensor_history: VecDeque::with_capacity(64),
+            last_bmc_history_ms: 0,
+            dimm_temp_curves: (0..24).map(|_| VecDeque::with_capacity(64)).collect(),
+            rmt_status: "unobserved".to_string(),
             rmt_results: BTreeMap::new(),
             rmt_results: BTreeMap::new(),
             amt_results: BTreeMap::new(),
             amt_results: BTreeMap::new(),
             active_amt_cpus: BTreeSet::new(),
             active_amt_cpus: BTreeSet::new(),
@@ -1123,6 +1219,7 @@ impl StationState {
         }
         }
         self.hot.reset_for_new_boot(now);
         self.hot.reset_for_new_boot(now);
         self.reset_dimms_for_new_boot();
         self.reset_dimms_for_new_boot();
+        self.rmt_status = "unobserved".to_string();
         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();
@@ -1218,6 +1315,152 @@ impl StationState {
         }
         }
     }
     }
 
 
+    pub fn record_dimm_temp_sample(&mut self, slot_idx: usize, ts_ms: i64, temp_c: f64) {
+        if slot_idx >= 24 || !temp_c.is_finite() {
+            return;
+        }
+        if let Some(ring) = self.dimm_temp_curves.get_mut(slot_idx) {
+            if let Some(&(last_ts, _)) = ring.back() {
+                if ts_ms.saturating_sub(last_ts) < 900 {
+                    return;
+                }
+            }
+            if ring.len() >= 1800 {
+                ring.pop_front();
+            }
+            ring.push_back((ts_ms, temp_c));
+        }
+    }
+
+    pub fn update_bmc_sensors_snapshot(&mut self, sensors: Vec<BmcSensorReading>, now: i64) {
+        let count = sensors.len();
+        self.bmc_sensors = sensors;
+        self.bmc_sensors_updated_ms = now;
+        let should_push_hist = self.bmc_sensor_history.is_empty()
+            || now.saturating_sub(self.last_bmc_history_ms) >= 5_000;
+        if should_push_hist {
+            self.last_bmc_history_ms = now;
+            let mut snap = JsonVal::obj();
+            snap.set("ts_ms", JsonVal::Num(now as f64));
+            snap.set("station_id", JsonVal::Str(self.station_id.clone()));
+            snap.set("bmc_state", JsonVal::Str(self.bmc_state.clone()));
+            snap.set("server_power", JsonVal::Str(self.server_power.clone()));
+            snap.set(
+                "sensors",
+                JsonVal::Arr(self.bmc_sensors.iter().map(|s| s.to_json()).collect()),
+            );
+            if self.bmc_sensor_history.len() >= 360 {
+                self.bmc_sensor_history.pop_front();
+            }
+            self.bmc_sensor_history.push_back(snap);
+            if let Some(ref th) = self.trace_hub {
+                let mut temp_n = 0usize;
+                let mut volt_n = 0usize;
+                let mut fan_n = 0usize;
+                let mut pwr_n = 0usize;
+                let mut disc_n = 0usize;
+                let mut max_t: f64 = f64::NEG_INFINITY;
+                for s in &self.bmc_sensors {
+                    match s.category.as_str() {
+                        "temp" => {
+                            temp_n += 1;
+                            if let Some(v) = s.value {
+                                if v > max_t {
+                                    max_t = v;
+                                }
+                            }
+                        }
+                        "voltage" => volt_n += 1,
+                        "fan" => fan_n += 1,
+                        "power" | "current" => pwr_n += 1,
+                        "discrete" => disc_n += 1,
+                        _ => {}
+                    }
+                }
+                let max_t_str = if max_t.is_finite() {
+                    format!("{:.1}C", max_t)
+                } else {
+                    "na".to_string()
+                };
+                th.record_hardware_event(
+                    &self.station_id,
+                    "bmc_sensors",
+                    "sdr_snapshot",
+                    &format!(
+                        "total={} temp={} volt={} fan={} power={} discrete={} max_temp={}",
+                        count, temp_n, volt_n, fan_n, pwr_n, disc_n, max_t_str
+                    ),
+                );
+            }
+        }
+    }
+
+    pub fn build_dimm_curve_fallback_json(&self, slot_idx: usize) -> JsonVal {
+        let idx = slot_idx.min(23);
+        let cpu = idx / 12;
+        let ch = (b'A' + (idx % 12) as u8) as char;
+        let mut pts = Vec::new();
+        if let Some(ring) = self.dimm_temp_curves.get(idx) {
+            for &(ts, temp) in ring {
+                let mut p = JsonVal::obj();
+                p.set("unix_ms", JsonVal::Num(ts as f64));
+                p.set("dimm_c", JsonVal::Num(temp));
+                p.set("temp_c", JsonVal::Num(temp));
+                p.set("chamber_c", JsonVal::Null);
+                p.set("target_c", JsonVal::Num(self.thermal_target_c as f64));
+                pts.push(p);
+            }
+        } else if let Some(cur) = self.dimms[idx].value_c {
+            let mut p = JsonVal::obj();
+            p.set("unix_ms", JsonVal::Num(self.dimms[idx].received_ms as f64));
+            p.set("dimm_c", JsonVal::Num(cur));
+            p.set("temp_c", JsonVal::Num(cur));
+            p.set("chamber_c", JsonVal::Null);
+            p.set("target_c", JsonVal::Num(self.thermal_target_c as f64));
+            pts.push(p);
+        }
+        let mut out = JsonVal::obj();
+        out.set("station_id", JsonVal::Str(self.station_id.clone()));
+        out.set("slot", JsonVal::Num(idx as f64));
+        out.set("slot_id", JsonVal::Str(format!("CPU{}_{}", cpu, ch)));
+        out.set("source", JsonVal::Str("bmc_sdr_fallback".to_string()));
+        out.set("points", JsonVal::Arr(pts));
+        out
+    }
+
+    pub fn is_rmt_requested_by_config(&self) -> bool {
+        if self.boot_plan.get_bool("run_rmt") == Some(false) {
+            return false;
+        }
+        let preset = self.boot_plan.get_str_or("preset", "manual");
+        let mut explicitly_enabled =
+            preset != "manual" && self.boot_plan.get_bool("run_rmt") == Some(true);
+        for ov in &self.uip_overrides {
+            let id = ov.get_str_or("id", "");
+            let mode = ov.get_str_or("mode", "override");
+            if mode != "override" {
+                continue;
+            }
+            let val = ov.get_str_or("value", "").trim().to_ascii_lowercase();
+            if id == "rmt" {
+                if val == "disable" {
+                    return false;
+                }
+                if val == "enable" || val == "backside" || val.is_empty() {
+                    explicitly_enabled = true;
+                }
+            }
+            if id == "maskmain" {
+                for tok in val.split(|c: char| c == ',' || c == ';' || c.is_whitespace()) {
+                    if tok.trim() == "48" {
+                        return false;
+                    }
+                }
+            }
+        }
+        explicitly_enabled
+    }
+
     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" {
@@ -1807,6 +2050,7 @@ impl StationState {
         out.set("ict_stage1_complete", JsonVal::Bool(self.hot.ict_stage1_complete));
         out.set("ict_stage1_complete", JsonVal::Bool(self.hot.ict_stage1_complete));
         out.set("training_complete", JsonVal::Bool(self.hot.training_complete));
         out.set("training_complete", JsonVal::Bool(self.hot.training_complete));
         out.set("rmt_complete", JsonVal::Bool(self.hot.rmt_complete));
         out.set("rmt_complete", JsonVal::Bool(self.hot.rmt_complete));
+        out.set("rmt_status", JsonVal::Str(self.rmt_status.clone()));
         out.set("amt_complete", JsonVal::Bool(self.hot.amt_complete));
         out.set("amt_complete", JsonVal::Bool(self.hot.amt_complete));
         out.set("ict_stage2_complete", JsonVal::Bool(self.hot.ict_stage2_complete));
         out.set("ict_stage2_complete", JsonVal::Bool(self.hot.ict_stage2_complete));
         out.set("uefi_complete", JsonVal::Bool(self.hot.uefi_complete));
         out.set("uefi_complete", JsonVal::Bool(self.hot.uefi_complete));
@@ -1860,8 +2104,27 @@ impl StationState {
         let mut err = JsonVal::obj();
         let mut err = JsonVal::obj();
         err.set("stage", JsonVal::Str(stage.to_string()));
         err.set("stage", JsonVal::Str(stage.to_string()));
         err.set("kind", JsonVal::Str(kind.to_string()));
         err.set("kind", JsonVal::Str(kind.to_string()));
+        let mut slot_lbl = String::new();
         if let Some(c) = cpu {
         if let Some(c) = cpu {
             err.set("cpu", JsonVal::Num(c as f64));
             err.set("cpu", JsonVal::Num(c as f64));
+            if let Some(channel) = ch {
+                if (0..12).contains(&channel) {
+                    slot_lbl = format!("CPU{}_CH{}", c, (b'A' + channel as u8) as char);
+                } else {
+                    slot_lbl = format!("CPU{}_CH{}", c, channel);
+                }
+            } else {
+                slot_lbl = format!("CPU{}", c);
+            }
+        } else if let Some(channel) = ch {
+            if (0..12).contains(&channel) {
+                slot_lbl = format!("CH{}", (b'A' + channel as u8) as char);
+            } else {
+                slot_lbl = format!("CH{}", channel);
+            }
+        }
+        if !slot_lbl.is_empty() {
+            err.set("slot", JsonVal::Str(slot_lbl));
         }
         }
         if let Some(channel) = ch {
         if let Some(channel) = ch {
             err.set("channel", JsonVal::Str(channel.to_string()));
             err.set("channel", JsonVal::Str(channel.to_string()));
@@ -2578,17 +2841,13 @@ impl StationState {
             return;
             return;
         }
         }
 
 
-        // Check partial half-line tail for RMT dots or live prompts without per-chunk heap allocation
+        // Check partial half-line tail for live prompts without per-chunk heap allocation.
+        // Note: standalone progress dots (`...`) are emitted across Training/AMT/POST and MUST NOT
+        // falsely enter the RMT stage!
         let mut hl_buf = std::mem::take(&mut self.scratch_halfline);
         let mut hl_buf = std::mem::take(&mut self.scratch_halfline);
         hl_buf.clear();
         hl_buf.clear();
         hl_buf.extend_from_slice(self.cleaner.halfline_bytes());
         hl_buf.extend_from_slice(self.cleaner.halfline_bytes());
         if !hl_buf.is_empty() {
         if !hl_buf.is_empty() {
-            if hl_buf.iter().all(|&b| b == b'.' || b == b' ')
-                && hl_buf.contains(&b'.')
-                && self.observed_phase == "unknown"
-            {
-                self.advance_phase("rmt", "rmt_running", now);
-            }
             if let Some(prompt_ev) = self.cleaner.detect_live_prompt() {
             if let Some(prompt_ev) = self.cleaner.detect_live_prompt() {
                 self.apply_prompt_event(&prompt_ev, &hl_buf, now);
                 self.apply_prompt_event(&prompt_ev, &hl_buf, now);
             }
             }
@@ -3230,6 +3489,9 @@ impl StationState {
                     }
                     }
                     entry.execution_supported = true;
                     entry.execution_supported = true;
                 }
                 }
+                if self.rmt_status != "completed" {
+                    self.rmt_status = "running".to_string();
+                }
                 self.advance_phase("rmt", "rmt_running", now);
                 self.advance_phase("rmt", "rmt_running", now);
                 *self.stage_step_counts.entry("rmt".to_string()).or_insert(0) += 1;
                 *self.stage_step_counts.entry("rmt".to_string()).or_insert(0) += 1;
             }
             }
@@ -3259,15 +3521,25 @@ impl StationState {
                 if entry.state != "completed" {
                 if entry.state != "completed" {
                     entry.state = "running".to_string();
                     entry.state = "running".to_string();
                 }
                 }
+                if self.rmt_status != "completed" {
+                    self.rmt_status = "running".to_string();
+                }
                 self.advance_phase("rmt", "rmt_margin", now);
                 self.advance_phase("rmt", "rmt_margin", now);
                 *self.stage_step_counts.entry("rmt".to_string()).or_insert(0) += 1;
                 *self.stage_step_counts.entry("rmt".to_string()).or_insert(0) += 1;
 
 
                 if ev.channel >= 0 && (ev.channel as usize) < 12 && (0..=1).contains(&cpu) {
                 if ev.channel >= 0 && (ev.channel as usize) < 12 && (0..=1).contains(&cpu) {
                     let slot_idx = (cpu as usize) * 12 + (ev.channel as usize);
                     let slot_idx = (cpu as usize) * 12 + (ev.channel as usize);
+                    // RMT margin row columns: RxDqs(lo,hi), TxDq(lo,hi) or RxVref/TxVref
                     self.dimm_soa.rmt_rx_dq_lo[slot_idx] = ev.val0 as i16;
                     self.dimm_soa.rmt_rx_dq_lo[slot_idx] = ev.val0 as i16;
                     self.dimm_soa.rmt_rx_dq_hi[slot_idx] = ev.val1 as i16;
                     self.dimm_soa.rmt_rx_dq_hi[slot_idx] = ev.val1 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_tx_dq_lo[slot_idx] = ev.val2 as i16;
+                    self.dimm_soa.rmt_tx_dq_hi[slot_idx] = ev.val3 as i16;
+                    if ev.val2 != 0 || ev.val3 != 0 {
+                        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_tx_vref_lo[slot_idx] = ev.val2 as i16;
+                        self.dimm_soa.rmt_tx_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.dimm_seen_in_boot[slot_idx] = true;
                     self.sdr_absent_streak[slot_idx] = 0;
                     self.sdr_absent_streak[slot_idx] = 0;
@@ -3290,6 +3562,13 @@ impl StationState {
                         .find(|(_, r)| r.state == "running")
                         .find(|(_, r)| r.state == "running")
                         .map(|(&c, _)| c)
                         .map(|(&c, _)| c)
                 };
                 };
+                // Parse optional `Time=<N> ms` reported by 108_VD012 `Rank Margin Tool -- SUCCEEDED,Time=18 ms`.
+                // A 0 ms wrapper with 0 measurement rows means RMT did not actually execute measurements.
+                let time_ms_zero = trimmed
+                    .to_ascii_lowercase()
+                    .contains("time=0 ms")
+                    || trimmed.to_ascii_lowercase().contains("time=0ms");
+                let rmt_requested = self.is_rmt_requested_by_config();
                 if let Some(cpu) = target_cpu {
                 if let Some(cpu) = target_cpu {
                     let entry = self.rmt_results.entry(cpu).or_insert(RmtCpuResult {
                     let entry = self.rmt_results.entry(cpu).or_insert(RmtCpuResult {
                         cpu,
                         cpu,
@@ -3304,7 +3583,11 @@ impl StationState {
                     if ev.subkind == 3 {
                     if ev.subkind == 3 {
                         entry.state = "skipped".to_string();
                         entry.state = "skipped".to_string();
                         entry.verdict_supported = false;
                         entry.verdict_supported = false;
-                    } else if entry.measurement_rows > 0 || ev.subkind == 1 {
+                    } else if entry.measurement_rows > 0 {
+                        entry.state = "completed".to_string();
+                        entry.verdict_supported = true;
+                    } else if ev.subkind == 1 && rmt_requested && !time_ms_zero {
+                        // 108_VD012 with debuglog off runs RMT internally (>0 ms) and prints SUCCEEDED without lane rows
                         entry.state = "completed".to_string();
                         entry.state = "completed".to_string();
                         entry.verdict_supported = true;
                         entry.verdict_supported = true;
                     } else {
                     } else {
@@ -3341,6 +3624,7 @@ impl StationState {
                     .any(|r| r.measurement_rows > 0 || r.state == "completed");
                     .any(|r| r.measurement_rows > 0 || r.state == "completed");
                 if all_done && has_rmt_completed {
                 if all_done && has_rmt_completed {
                     self.hot.rmt_complete = true;
                     self.hot.rmt_complete = true;
+                    self.rmt_status = "completed".to_string();
                     self.advance_phase("rmt", "rmt_completed", now);
                     self.advance_phase("rmt", "rmt_completed", now);
                     for idx in 0..24 {
                     for idx in 0..24 {
                         if self.dimms[idx].presence == "present"
                         if self.dimms[idx].presence == "present"
@@ -3352,17 +3636,31 @@ impl StationState {
                             self.sync_dimm_to_soa(idx);
                             self.sync_dimm_to_soa(idx);
                         }
                         }
                     }
                     }
-                } else if has_rmt_completed || self.observed_stages.contains("rmt") {
+                } else if all_done && !has_rmt_completed {
+                    // Explicitly skipped or disabled (0 measurements): NEVER show RMT as completed or running!
+                    self.hot.rmt_complete = false;
+                    self.rmt_status = "skipped".to_string();
+                    self.observed_stages.remove("rmt");
+                    if self.observed_phase == "rmt" {
+                        self.observed_detail = "rmt_skipped".to_string();
+                    }
+                } else if ev.subkind == 3 && !has_rmt_completed {
+                    self.rmt_status = "skipped".to_string();
+                    self.observed_stages.remove("rmt");
+                } else if has_rmt_completed {
+                    self.rmt_status = "running".to_string();
                     self.advance_phase("rmt", "rmt_running", now);
                     self.advance_phase("rmt", "rmt_running", now);
                 }
                 }
                 self.log_debug(
                 self.log_debug(
                     "STAGE",
                     "STAGE",
                     &format!(
                     &format!(
-                        "RMT_STOP subkind={} has_rmt_rows={} has_rmt_completed={} all_done={} rmt_complete={} line={}",
-                        ev.subkind, has_rmt_rows, has_rmt_completed, all_done, self.hot.rmt_complete, trimmed
+                        "RMT_STOP subkind={} rmt_req={} time_zero={} has_rmt_rows={} has_rmt_completed={} all_done={} rmt_status={} rmt_complete={} line={}",
+                        ev.subkind, rmt_requested, time_ms_zero, has_rmt_rows, has_rmt_completed, all_done, self.rmt_status, self.hot.rmt_complete, trimmed
                     ),
                     ),
                 );
                 );
-                *self.stage_step_counts.entry("rmt".to_string()).or_insert(0) += 1;
+                if has_rmt_completed {
+                    *self.stage_step_counts.entry("rmt".to_string()).or_insert(0) += 1;
+                }
             }
             }
             lib::STL_LK_AMT_BANNER => {
             lib::STL_LK_AMT_BANNER => {
                 self.hot.ict_stage1_complete = true;
                 self.hot.ict_stage1_complete = true;

+ 77 - 16
native/stl_accel/src/storage.rs

@@ -39,6 +39,33 @@ pub fn atomic_write_bytes(path: &Path, data: &[u8]) -> std::io::Result<()> {
     Ok(())
     Ok(())
 }
 }
 
 
+#[inline]
+pub fn unix_ms_to_utc8_string(ts: i64) -> String {
+    let clamped = ts.max(0).saturating_add(8 * 3600 * 1000);
+    let total_secs = clamped / 1000;
+    let ms = clamped % 1000;
+    let days = total_secs / 86_400;
+    let rem = total_secs % 86_400;
+    let hh = rem / 3600;
+    let mm = (rem % 3600) / 60;
+    let ss = rem % 60;
+
+    let z = days + 719_468;
+    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
+    let doe = z - era * 146_097;
+    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+    let y = yoe + era * 400;
+    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+    let mp = (5 * doy + 2) / 153;
+    let d = doy - (153 * mp + 2) / 5 + 1;
+    let m = mp + if mp < 10 { 3 } else { -9 };
+    let year = y + if m <= 2 { 1 } else { 0 };
+    format!(
+        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}+08:00",
+        year, m, d, hh, mm, ss, ms
+    )
+}
+
 #[inline]
 #[inline]
 pub fn unix_ms_to_utc_string(ts: i64) -> String {
 pub fn unix_ms_to_utc_string(ts: i64) -> String {
     let clamped = ts.max(0);
     let clamped = ts.max(0);
@@ -136,7 +163,7 @@ pub fn save_web_auth_password(data_dir: &Path, new_pass: &str) -> std::io::Resul
     Ok(())
     Ok(())
 }
 }
 
 
-pub fn load_stations_roster(data_dir: &Path) -> Option<Vec<(String, String, usize)>> {
+pub fn load_stations_roster(data_dir: &Path) -> Option<Vec<(String, String, usize, String)>> {
     let p = data_dir.join("stations_roster.json");
     let p = data_dir.join("stations_roster.json");
     let txt = fs::read_to_string(&p).ok()?;
     let txt = fs::read_to_string(&p).ok()?;
     let val = parse_json(&txt).ok()?;
     let val = parse_json(&txt).ok()?;
@@ -149,7 +176,8 @@ pub fn load_stations_roster(data_dir: &Path) -> Option<Vec<(String, String, usiz
         }
         }
         let name = item.get_str_or("name", &sid);
         let name = item.get_str_or("name", &sid);
         let cpus = item.get_i64("cpu_count").unwrap_or(2).max(1) as usize;
         let cpus = item.get_i64("cpu_count").unwrap_or(2).max(1) as usize;
-        out.push((sid, name, cpus));
+        let bmc_host = item.get_str_or("bmc_host", "");
+        out.push((sid, name, cpus, bmc_host));
     }
     }
     if out.is_empty() {
     if out.is_empty() {
         None
         None
@@ -160,14 +188,17 @@ pub fn load_stations_roster(data_dir: &Path) -> Option<Vec<(String, String, usiz
 
 
 pub fn save_stations_roster(
 pub fn save_stations_roster(
     data_dir: &Path,
     data_dir: &Path,
-    entries: &[(String, String, usize)],
+    entries: &[(String, String, usize, String)],
 ) -> std::io::Result<()> {
 ) -> std::io::Result<()> {
     let mut arr = Vec::with_capacity(entries.len());
     let mut arr = Vec::with_capacity(entries.len());
-    for (sid, name, cpus) in entries {
+    for (sid, name, cpus, bmc_host) in entries {
         let mut o = JsonVal::obj();
         let mut o = JsonVal::obj();
         o.set("station_id", JsonVal::Str(sid.clone()));
         o.set("station_id", JsonVal::Str(sid.clone()));
         o.set("name", JsonVal::Str(name.clone()));
         o.set("name", JsonVal::Str(name.clone()));
         o.set("cpu_count", JsonVal::Num((*cpus).max(1) as f64));
         o.set("cpu_count", JsonVal::Num((*cpus).max(1) as f64));
+        if !bmc_host.is_empty() {
+            o.set("bmc_host", JsonVal::Str(bmc_host.clone()));
+        }
         arr.push(o);
         arr.push(o);
     }
     }
     let mut root = JsonVal::obj();
     let mut root = JsonVal::obj();
@@ -355,18 +386,14 @@ 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_secrets_recursive(tb);
             let mut clean_tb = strip_secrets_recursive(tb);
             let tb_state = clean_tb.get_str_or("state", "idle");
             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()));
+            // Preserve persisted batch queue metadata/history across restarts:
+            // if a batch was actively running when the host exited, mark it `"interrupted"` so operators can inspect or resume it.
+            if tb_state == "running" {
+                clean_tb.set("state", JsonVal::Str("interrupted".to_string()));
+                clean_tb.set(
+                    "halt_reason",
+                    JsonVal::Str("server_restarted".to_string()),
+                );
                 clean_tb.set(
                 clean_tb.set(
                     "updated_unix_ms",
                     "updated_unix_ms",
                     JsonVal::Str(crate::results::now_ms().to_string()),
                     JsonVal::Str(crate::results::now_ms().to_string()),
@@ -525,6 +552,30 @@ pub fn archive_task_run(
     let clean_path = dir.join("sol.clean.log");
     let clean_path = dir.join("sol.clean.log");
     let _ = fs::write(&clean_path, clean_txt.as_bytes());
     let _ = fs::write(&clean_path, clean_txt.as_bytes());
 
 
+    // Archive complete BMC & sensor telemetry timeline (`bmc_sensors.jsonl`) for post-test analysis
+    let bmc_sensors_path = dir.join("bmc_sensors.jsonl");
+    if !st.bmc_sensor_history.is_empty() || !st.bmc_sensors.is_empty() {
+        let mut bmc_lines = String::new();
+        for snap in &st.bmc_sensor_history {
+            bmc_lines.push_str(&snap.to_json());
+            bmc_lines.push('\n');
+        }
+        if st.bmc_sensor_history.is_empty() && !st.bmc_sensors.is_empty() {
+            let mut snap = JsonVal::obj();
+            snap.set("ts_ms", JsonVal::Num(st.bmc_sensors_updated_ms as f64));
+            snap.set("station_id", JsonVal::Str(st.station_id.clone()));
+            snap.set("bmc_state", JsonVal::Str(st.bmc_state.clone()));
+            snap.set("server_power", JsonVal::Str(st.server_power.clone()));
+            snap.set(
+                "sensors",
+                JsonVal::Arr(st.bmc_sensors.iter().map(|s| s.to_json()).collect()),
+            );
+            bmc_lines.push_str(&snap.to_json());
+            bmc_lines.push('\n');
+        }
+        let _ = fs::write(&bmc_sensors_path, bmc_lines.as_bytes());
+    }
+
     let mut rmt_arr = Vec::new();
     let mut rmt_arr = Vec::new();
     for r in st.rmt_results.values() {
     for r in st.rmt_results.values() {
         let mut o = JsonVal::obj();
         let mut o = JsonVal::obj();
@@ -573,6 +624,16 @@ pub fn archive_task_run(
     disk_summary.set("bytes_logged", JsonVal::Num((raw_vec.len()) as f64));
     disk_summary.set("bytes_logged", JsonVal::Num((raw_vec.len()) as f64));
     disk_summary.set("log_raw_path", JsonVal::Str(raw_path.to_string_lossy().to_string()));
     disk_summary.set("log_raw_path", JsonVal::Str(raw_path.to_string_lossy().to_string()));
     disk_summary.set("log_clean_path", JsonVal::Str(clean_path.to_string_lossy().to_string()));
     disk_summary.set("log_clean_path", JsonVal::Str(clean_path.to_string_lossy().to_string()));
+    if bmc_sensors_path.is_file() {
+        disk_summary.set(
+            "bmc_sensors_path",
+            JsonVal::Str(bmc_sensors_path.to_string_lossy().to_string()),
+        );
+        disk_summary.set(
+            "bmc_sensor_count",
+            JsonVal::Num(st.bmc_sensors.len() as f64),
+        );
+    }
     disk_summary.set("stage_completions", st.stage_completions_json());
     disk_summary.set("stage_completions", st.stage_completions_json());
     disk_summary.set("rmt_results", JsonVal::Arr(rmt_arr));
     disk_summary.set("rmt_results", JsonVal::Arr(rmt_arr));
     disk_summary.set("amt_results", JsonVal::Arr(amt_arr));
     disk_summary.set("amt_results", JsonVal::Arr(amt_arr));

+ 41 - 6
native/stl_accel/src/thermal_mcu.rs

@@ -1325,6 +1325,8 @@ struct ThermalSlotRuntime {
     rx_frames_ok: u64,
     rx_frames_ok: u64,
     tx_frames_sent: u64,
     tx_frames_sent: u64,
     cooling_requested: bool,
     cooling_requested: bool,
+    cooling_started_ms: i64,
+    chamber_hot_or_held: bool,
     heat_commanded: bool,
     heat_commanded: bool,
     last_heat_cmd_ms: i64,
     last_heat_cmd_ms: i64,
 
 
@@ -1429,6 +1431,8 @@ impl ThermalSlotRuntime {
             rx_frames_ok: 0,
             rx_frames_ok: 0,
             tx_frames_sent: 0,
             tx_frames_sent: 0,
             cooling_requested: false,
             cooling_requested: false,
+            cooling_started_ms: 0,
+            chamber_hot_or_held: false,
             heat_commanded: false,
             heat_commanded: false,
             last_heat_cmd_ms: 0,
             last_heat_cmd_ms: 0,
             mcu_bmc_temps: [None; 24],
             mcu_bmc_temps: [None; 24],
@@ -1606,6 +1610,9 @@ impl ThermalSlotRuntime {
             return "manual";
             return "manual";
         }
         }
         if self.cooling_requested {
         if self.cooling_requested {
+            if self.cooling_started_ms > 0 && now.saturating_sub(self.cooling_started_ms) >= 300_000 {
+                return "idle";
+            }
             return "cooling_purge";
             return "cooling_purge";
         }
         }
         "idle"
         "idle"
@@ -1620,6 +1627,9 @@ impl ThermalSlotRuntime {
         self.mock_dev = None;
         self.mock_dev = None;
         self.manual_hold_keepalive = false;
         self.manual_hold_keepalive = false;
         self.heat_commanded = false;
         self.heat_commanded = false;
+        self.cooling_requested = false;
+        self.cooling_started_ms = 0;
+        self.chamber_hot_or_held = false;
         self.followup_cmd_queue.clear();
         self.followup_cmd_queue.clear();
         if let Some(mut w) = self.pending_waiter.take() {
         if let Some(mut w) = self.pending_waiter.take() {
             if let Some(tx) = w.reply_tx.take() {
             if let Some(tx) = w.reply_tx.take() {
@@ -1910,8 +1920,17 @@ impl ThermalSlotRuntime {
                         if self.heat_commanded && now.saturating_sub(self.last_heat_cmd_ms) > 3000 {
                         if self.heat_commanded && now.saturating_sub(self.last_heat_cmd_ms) > 3000 {
                             self.heat_commanded = false;
                             self.heat_commanded = false;
                         }
                         }
+                        if self.cooling_requested
+                            && self.cooling_started_ms > 0
+                            && now.saturating_sub(self.cooling_started_ms) >= 300_000
+                        {
+                            self.cooling_requested = false;
+                            self.cooling_started_ms = 0;
+                        }
                     } else {
                     } else {
                         self.cooling_requested = false;
                         self.cooling_requested = false;
+                        self.cooling_started_ms = 0;
+                        self.chamber_hot_or_held = true;
                     }
                     }
                     self.last_f0_ms = now;
                     self.last_f0_ms = now;
                 }
                 }
@@ -2909,10 +2928,7 @@ impl ThermalHubRuntime {
         }
         }
         let mut root = JsonVal::obj();
         let mut root = JsonVal::obj();
         root.set("stations", st_map);
         root.set("stations", st_map);
-        let tmp = self.prefs_path().with_extension("json.tmp");
-        if fs::write(&tmp, root.to_json()).is_ok() {
-            let _ = fs::rename(&tmp, self.prefs_path());
-        }
+        let _ = crate::storage::atomic_write_bytes(&self.prefs_path(), root.to_json().as_bytes());
     }
     }
 
 
     fn console_claimed_serial_paths(&self) -> BTreeMap<String, String> {
     fn console_claimed_serial_paths(&self) -> BTreeMap<String, String> {
@@ -3596,6 +3612,9 @@ impl ThermalHubRuntime {
             "start_pid" => {
             "start_pid" => {
                 let slot = self.slots.get_mut(sid).unwrap();
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.heat_commanded = true;
                 slot.heat_commanded = true;
+                slot.chamber_hot_or_held = true;
+                slot.cooling_requested = false;
+                slot.cooling_started_ms = 0;
                 slot.last_heat_cmd_ms = now;
                 slot.last_heat_cmd_ms = now;
                 slot.arm_safety_lease(now);
                 slot.arm_safety_lease(now);
                 slot.send_command_with_waiter(
                 slot.send_command_with_waiter(
@@ -3612,6 +3631,8 @@ impl ThermalHubRuntime {
                 let slot = self.slots.get_mut(sid).unwrap();
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.manual_hold_keepalive = false;
                 slot.manual_hold_keepalive = false;
                 slot.cooling_requested = false;
                 slot.cooling_requested = false;
+                slot.cooling_started_ms = 0;
+                slot.chamber_hot_or_held = false;
                 slot.heat_commanded = false;
                 slot.heat_commanded = false;
                 slot.clear_safety_lease();
                 slot.clear_safety_lease();
                 slot.send_command_with_waiter(
                 slot.send_command_with_waiter(
@@ -3629,6 +3650,8 @@ impl ThermalHubRuntime {
                 let slot = self.slots.get_mut(sid).unwrap();
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.manual_hold_keepalive = false;
                 slot.manual_hold_keepalive = false;
                 slot.cooling_requested = purge;
                 slot.cooling_requested = purge;
+                slot.cooling_started_ms = if purge { now } else { 0 };
+                slot.chamber_hot_or_held = !purge;
                 slot.heat_commanded = false;
                 slot.heat_commanded = false;
                 slot.clear_safety_lease();
                 slot.clear_safety_lease();
                 let payload = [if purge { 0x00 } else { 0x01 }];
                 let payload = [if purge { 0x00 } else { 0x01 }];
@@ -3642,6 +3665,7 @@ impl ThermalHubRuntime {
             "stop_heaters" => {
             "stop_heaters" => {
                 let slot = self.slots.get_mut(sid).unwrap();
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.heat_commanded = false;
                 slot.heat_commanded = false;
+                slot.chamber_hot_or_held = false;
                 for d in &mut slot.manual_duty[..24] {
                 for d in &mut slot.manual_duty[..24] {
                     *d = 0;
                     *d = 0;
                 }
                 }
@@ -3661,6 +3685,7 @@ impl ThermalHubRuntime {
             "stop_fans" => {
             "stop_fans" => {
                 let slot = self.slots.get_mut(sid).unwrap();
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.cooling_requested = false;
                 slot.cooling_requested = false;
+                slot.cooling_started_ms = 0;
                 for d in &mut slot.manual_duty[24..32] {
                 for d in &mut slot.manual_duty[24..32] {
                     *d = 0;
                     *d = 0;
                 }
                 }
@@ -3678,6 +3703,8 @@ impl ThermalHubRuntime {
                 let slot = self.slots.get_mut(sid).unwrap();
                 let slot = self.slots.get_mut(sid).unwrap();
                 slot.manual_hold_keepalive = false;
                 slot.manual_hold_keepalive = false;
                 slot.cooling_requested = false;
                 slot.cooling_requested = false;
+                slot.cooling_started_ms = 0;
+                slot.chamber_hot_or_held = false;
                 slot.heat_commanded = false;
                 slot.heat_commanded = false;
                 slot.manual_duty.fill(0);
                 slot.manual_duty.fill(0);
                 slot.clear_safety_lease();
                 slot.clear_safety_lease();
@@ -4170,6 +4197,8 @@ impl ThermalMcuHub {
                                         slot.last_set_target_c = target_c;
                                         slot.last_set_target_c = target_c;
                                         slot.manual_hold_keepalive = false;
                                         slot.manual_hold_keepalive = false;
                                         slot.cooling_requested = false;
                                         slot.cooling_requested = false;
+                                        slot.cooling_started_ms = 0;
+                                        slot.chamber_hot_or_held = true;
                                         slot.heat_commanded = true;
                                         slot.heat_commanded = true;
                                         slot.last_heat_cmd_ms = now;
                                         slot.last_heat_cmd_ms = now;
                                         slot.arm_safety_lease(now);
                                         slot.arm_safety_lease(now);
@@ -4209,9 +4238,12 @@ impl ThermalMcuHub {
                                             && slot.mock_dev.is_some());
                                             && slot.mock_dev.is_some());
                                     let heating_or_holding = (slot.flags & 0x46) != 0
                                     let heating_or_holding = (slot.flags & 0x46) != 0
                                         || slot.heat_commanded
                                         || slot.heat_commanded
-                                        || slot.manual_hold_keepalive;
+                                        || slot.manual_hold_keepalive
+                                        || slot.chamber_hot_or_held;
                                     if link_active && heating_or_holding {
                                     if link_active && heating_or_holding {
                                         slot.cooling_requested = false;
                                         slot.cooling_requested = false;
+                                        slot.cooling_started_ms = 0;
+                                        slot.chamber_hot_or_held = true;
                                         if slot.send_raw_frame(0x08, &[0x01], now).is_ok() {
                                         if slot.send_raw_frame(0x08, &[0x01], now).is_ok() {
                                             let msg = format!(
                                             let msg = format!(
                                                 "多轮队列中间轮通过 ({}),已下发 0x08 01 保持腔体温度进入下一轮",
                                                 "多轮队列中间轮通过 ({}),已下发 0x08 01 保持腔体温度进入下一轮",
@@ -4238,12 +4270,15 @@ impl ThermalMcuHub {
                                     // flags bits: 0x02=preheating, 0x04=pid_running, 0x40=manual_active
                                     // flags bits: 0x02=preheating, 0x04=pid_running, 0x40=manual_active
                                     let heating_or_holding = (slot.flags & 0x46) != 0
                                     let heating_or_holding = (slot.flags & 0x46) != 0
                                         || slot.heat_commanded
                                         || slot.heat_commanded
-                                        || slot.manual_hold_keepalive;
+                                        || slot.manual_hold_keepalive
+                                        || slot.chamber_hot_or_held;
                                     if link_active && heating_or_holding && !slot.cooling_requested {
                                     if link_active && heating_or_holding && !slot.cooling_requested {
                                         slot.manual_hold_keepalive = false;
                                         slot.manual_hold_keepalive = false;
                                         slot.heat_commanded = false;
                                         slot.heat_commanded = false;
+                                        slot.chamber_hot_or_held = false;
                                         slot.followup_cmd_queue.clear();
                                         slot.followup_cmd_queue.clear();
                                         slot.cooling_requested = true;
                                         slot.cooling_requested = true;
+                                        slot.cooling_started_ms = now;
                                         slot.clear_safety_lease();
                                         slot.clear_safety_lease();
                                         if slot.send_raw_frame(0x08, &[0x00], now).is_ok() {
                                         if slot.send_raw_frame(0x08, &[0x00], now).is_ok() {
                                             let msg = format!(
                                             let msg = format!(

+ 301 - 89
native/stl_accel/src/trace.rs

@@ -122,37 +122,44 @@ impl TraceConfig {
 }
 }
 
 
 /// 64-byte cache-line aligned flat station memory snapshot for SIMD XOR diffing.
 /// 64-byte cache-line aligned flat station memory snapshot for SIMD XOR diffing.
+/// Exact layout = 320 bytes (5 x 64-byte cache lines) with zero uninitialized padding bytes.
+/// Note: `raw_write_offset`/`clean_write_offset` are kept on `StationTraceState` (not here) so
+/// streaming serial bytes do not emit offset-only `state_diff` spam when no logical state changed.
 #[repr(C, align(64))]
 #[repr(C, align(64))]
 #[derive(Clone, Copy)]
 #[derive(Clone, Copy)]
 pub struct StationCoreBinary {
 pub struct StationCoreBinary {
-    pub boot_seq: i64,
-    pub run_started_unix_ms: i64,
-    pub run_ended_unix_ms: i64,
-    pub raw_write_offset: u64,
-    pub clean_write_offset: u64,
-    pub alarm_count: u32,
-    pub stage_comp_mask: u32,
-    pub mt_errors: i32,
-    pub batch_done: u32,
-    pub batch_planned: u32,
-    pub flags: u32,
-    pub thermal_target_c: u8,
-    pub fw_family: u8,
-    pub observed_cpu: i8,
-    pub observed_uip_stage: i8,
-    pub prompt_cpu: i8,
-    pub prompt_uip_stage: i8,
-    pub _pad0: [u8; 2],
+    pub boot_seq: i64,            // 0..8
+    pub run_started_unix_ms: i64, // 8..16
+    pub run_ended_unix_ms: i64,   // 16..24
+    pub alarm_count: u32,         // 24..28
+    pub stage_comp_mask: u32,     // 28..32
+    pub mt_errors: i32,           // 32..36
+    pub batch_done: u32,          // 36..40
+    pub batch_planned: u32,       // 40..44
+    pub flags: u32,               // 44..48
+    pub bmc_sensor_count: u16,    // 48..50
+    pub chamber_temp_x10: i16,    // 50..52
+    pub thermal_target_c: u8,     // 52..53
+    pub fw_family: u8,            // 53..54
+    pub observed_cpu: i8,         // 54..55
+    pub observed_uip_stage: i8,   // 55..56
+    pub prompt_cpu: i8,           // 56..57
+    pub prompt_uip_stage: i8,     // 57..58
+    pub rmt_status_code: u8,      // 58..59 (0=unobserved,1=running,2=completed,3=skipped)
+    pub _pad0: [u8; 5],           // 59..64
     // 24 DIMM slots: state (0=idle,1=pass,2=fail), presence (0=unk,1=present,2=absent), enabled (0=unk,1=en,2=dis)
     // 24 DIMM slots: state (0=idle,1=pass,2=fail), presence (0=unk,1=present,2=absent), enabled (0=unk,1=en,2=dis)
-    pub dimm_state: [u8; 24],
-    pub dimm_presence: [u8; 24],
-    pub dimm_enabled: [u8; 24],
+    pub dimm_state: [u8; 24],     // 64..88
+    pub dimm_presence: [u8; 24],  // 88..112
+    pub dimm_enabled: [u8; 24],   // 112..136
     // 24 DIMM temperatures in 0.1 deg C (i16::MIN = none)
     // 24 DIMM temperatures in 0.1 deg C (i16::MIN = none)
-    pub dimm_temp_x10: [i16; 24],
+    pub dimm_temp_x10: [i16; 24], // 136..184
     // Fixed-size string fingerprints (FNV-1a 64-bit hashes) so scalar/string changes trigger SIMD mask cleanly
     // Fixed-size string fingerprints (FNV-1a 64-bit hashes) so scalar/string changes trigger SIMD mask cleanly
-    pub str_hashes: [u64; 10],
+    pub str_hashes: [u64; 10],    // 184..264
+    pub _pad_tail: [u8; 56],      // 264..320 (explicit zero tail -> zero uninitialized padding UB!)
 }
 }
 
 
+const _: [(); 320] = [(); std::mem::size_of::<StationCoreBinary>()];
+
 impl StationCoreBinary {
 impl StationCoreBinary {
     pub fn as_bytes(&self) -> &[u8] {
     pub fn as_bytes(&self) -> &[u8] {
         unsafe {
         unsafe {
@@ -167,6 +174,8 @@ impl StationCoreBinary {
 #[derive(Clone)]
 #[derive(Clone)]
 pub struct StationTraceState {
 pub struct StationTraceState {
     pub bin: StationCoreBinary,
     pub bin: StationCoreBinary,
+    pub raw_write_offset: u64,
+    pub clean_write_offset: u64,
     pub phase: String,
     pub phase: String,
     pub detail: String,
     pub detail: String,
     pub verdict: String,
     pub verdict: String,
@@ -277,34 +286,44 @@ pub fn capture_station_trace_state(st: &StationState) -> StationTraceState {
         fnv1a_64(&batch_state),
         fnv1a_64(&batch_state),
     ];
     ];
 
 
+    let rmt_status_code: u8 = match st.rmt_status.as_str() {
+        "running" => 1,
+        "completed" => 2,
+        "skipped" => 3,
+        _ => 0,
+    };
     let bin = StationCoreBinary {
     let bin = StationCoreBinary {
         boot_seq: st.boot_seq,
         boot_seq: st.boot_seq,
         run_started_unix_ms: st.run_started_unix_ms,
         run_started_unix_ms: st.run_started_unix_ms,
         run_ended_unix_ms: st.run_ended_unix_ms,
         run_ended_unix_ms: st.run_ended_unix_ms,
-        raw_write_offset: st.raw_ring.write_offset(),
-        clean_write_offset: st.clean_ring.write_offset(),
         alarm_count: st.alarm_records.len() as u32,
         alarm_count: st.alarm_records.len() as u32,
         stage_comp_mask: comp_mask,
         stage_comp_mask: comp_mask,
         mt_errors,
         mt_errors,
         batch_done,
         batch_done,
         batch_planned,
         batch_planned,
         flags,
         flags,
+        bmc_sensor_count: st.bmc_sensors.len().min(u16::MAX as usize) as u16,
+        chamber_temp_x10: i16::MIN,
         thermal_target_c: st.thermal_target_c,
         thermal_target_c: st.thermal_target_c,
         fw_family: st.hot.fw_family,
         fw_family: st.hot.fw_family,
         observed_cpu: st.observed_cpu.unwrap_or(-1) as i8,
         observed_cpu: st.observed_cpu.unwrap_or(-1) as i8,
         observed_uip_stage: st.observed_uip_stage.unwrap_or(-1) as i8,
         observed_uip_stage: st.observed_uip_stage.unwrap_or(-1) as i8,
         prompt_cpu: st.prompt_cpu.unwrap_or(-1) as i8,
         prompt_cpu: st.prompt_cpu.unwrap_or(-1) as i8,
         prompt_uip_stage: st.prompt_uip_stage.unwrap_or(-1) as i8,
         prompt_uip_stage: st.prompt_uip_stage.unwrap_or(-1) as i8,
-        _pad0: [0; 2],
+        rmt_status_code,
+        _pad0: [0; 5],
         dimm_state,
         dimm_state,
         dimm_presence,
         dimm_presence,
         dimm_enabled,
         dimm_enabled,
         dimm_temp_x10,
         dimm_temp_x10,
         str_hashes,
         str_hashes,
+        _pad_tail: [0; 56],
     };
     };
 
 
     StationTraceState {
     StationTraceState {
         bin,
         bin,
+        raw_write_offset: st.raw_ring.write_offset(),
+        clean_write_offset: st.clean_ring.write_offset(),
         phase: st.observed_phase.clone(),
         phase: st.observed_phase.clone(),
         detail: st.observed_detail.clone(),
         detail: st.observed_detail.clone(),
         verdict,
         verdict,
@@ -320,6 +339,15 @@ pub fn capture_station_trace_state(st: &StationState) -> StationTraceState {
     }
     }
 }
 }
 
 
+fn rmt_status_code_str(code: u8) -> &'static str {
+    match code {
+        1 => "running",
+        2 => "completed",
+        3 => "skipped",
+        _ => "unobserved",
+    }
+}
+
 fn dimm_state_str(code: u8) -> &'static str {
 fn dimm_state_str(code: u8) -> &'static str {
     match code {
     match code {
         1 => "pass",
         1 => "pass",
@@ -372,11 +400,19 @@ impl StationTraceState {
         o.set("thermal_auto_enabled", JsonVal::Bool((self.bin.flags & 32) != 0));
         o.set("thermal_auto_enabled", JsonVal::Bool((self.bin.flags & 32) != 0));
         o.set("thermal_heat_sent", JsonVal::Bool((self.bin.flags & 64) != 0));
         o.set("thermal_heat_sent", JsonVal::Bool((self.bin.flags & 64) != 0));
         o.set("link_offline_waiting", JsonVal::Bool((self.bin.flags & 128) != 0));
         o.set("link_offline_waiting", JsonVal::Bool((self.bin.flags & 128) != 0));
+        o.set("plan_paused", JsonVal::Bool((self.bin.flags & 256) != 0));
         o.set("thermal_target_c", JsonVal::Num(self.bin.thermal_target_c as f64));
         o.set("thermal_target_c", JsonVal::Num(self.bin.thermal_target_c as f64));
+        o.set("fw_family", JsonVal::Num(self.bin.fw_family as f64));
+        o.set("observed_cpu", JsonVal::Num(self.bin.observed_cpu as f64));
+        o.set("observed_uip_stage", JsonVal::Num(self.bin.observed_uip_stage as f64));
+        o.set("prompt_cpu", JsonVal::Num(self.bin.prompt_cpu as f64));
+        o.set("prompt_uip_stage", JsonVal::Num(self.bin.prompt_uip_stage as f64));
+        o.set("rmt_status", JsonVal::Str(rmt_status_code_str(self.bin.rmt_status_code).to_string()));
+        o.set("bmc_sensor_count", JsonVal::Num(self.bin.bmc_sensor_count as f64));
         o.set("run_started_unix_ms", JsonVal::Num(self.bin.run_started_unix_ms as f64));
         o.set("run_started_unix_ms", JsonVal::Num(self.bin.run_started_unix_ms as f64));
         o.set("run_ended_unix_ms", JsonVal::Num(self.bin.run_ended_unix_ms as f64));
         o.set("run_ended_unix_ms", JsonVal::Num(self.bin.run_ended_unix_ms as f64));
-        o.set("raw_write_offset", JsonVal::Num(self.bin.raw_write_offset as f64));
-        o.set("clean_write_offset", JsonVal::Num(self.bin.clean_write_offset as f64));
+        o.set("raw_write_offset", JsonVal::Num(self.raw_write_offset as f64));
+        o.set("clean_write_offset", JsonVal::Num(self.clean_write_offset as f64));
 
 
         let mut dimms = Vec::with_capacity(24);
         let mut dimms = Vec::with_capacity(24);
         for i in 0..24 {
         for i in 0..24 {
@@ -471,6 +507,7 @@ impl StationTraceState {
                 (5, "thermal_auto_enabled"),
                 (5, "thermal_auto_enabled"),
                 (6, "thermal_heat_sent"),
                 (6, "thermal_heat_sent"),
                 (7, "link_offline_waiting"),
                 (7, "link_offline_waiting"),
+                (8, "plan_paused"),
             ];
             ];
             for (bit, name) in bit_names {
             for (bit, name) in bit_names {
                 let ov = (self.bin.flags & (1 << bit)) != 0;
                 let ov = (self.bin.flags & (1 << bit)) != 0;
@@ -483,18 +520,37 @@ impl StationTraceState {
         if self.bin.thermal_target_c != next.bin.thermal_target_c {
         if self.bin.thermal_target_c != next.bin.thermal_target_c {
             push_ch("thermal_target_c", JsonVal::Num(self.bin.thermal_target_c as f64), JsonVal::Num(next.bin.thermal_target_c as f64));
             push_ch("thermal_target_c", JsonVal::Num(self.bin.thermal_target_c as f64), JsonVal::Num(next.bin.thermal_target_c as f64));
         }
         }
+        if self.bin.fw_family != next.bin.fw_family {
+            push_ch("fw_family", JsonVal::Num(self.bin.fw_family as f64), JsonVal::Num(next.bin.fw_family as f64));
+        }
+        if self.bin.observed_cpu != next.bin.observed_cpu {
+            push_ch("observed_cpu", JsonVal::Num(self.bin.observed_cpu as f64), JsonVal::Num(next.bin.observed_cpu as f64));
+        }
+        if self.bin.observed_uip_stage != next.bin.observed_uip_stage {
+            push_ch("observed_uip_stage", JsonVal::Num(self.bin.observed_uip_stage as f64), JsonVal::Num(next.bin.observed_uip_stage as f64));
+        }
+        if self.bin.prompt_cpu != next.bin.prompt_cpu {
+            push_ch("prompt_cpu", JsonVal::Num(self.bin.prompt_cpu as f64), JsonVal::Num(next.bin.prompt_cpu as f64));
+        }
+        if self.bin.prompt_uip_stage != next.bin.prompt_uip_stage {
+            push_ch("prompt_uip_stage", JsonVal::Num(self.bin.prompt_uip_stage as f64), JsonVal::Num(next.bin.prompt_uip_stage as f64));
+        }
+        if self.bin.rmt_status_code != next.bin.rmt_status_code {
+            push_ch(
+                "rmt_status",
+                JsonVal::Str(rmt_status_code_str(self.bin.rmt_status_code).to_string()),
+                JsonVal::Str(rmt_status_code_str(next.bin.rmt_status_code).to_string()),
+            );
+        }
+        if self.bin.bmc_sensor_count != next.bin.bmc_sensor_count {
+            push_ch("bmc_sensor_count", JsonVal::Num(self.bin.bmc_sensor_count as f64), JsonVal::Num(next.bin.bmc_sensor_count as f64));
+        }
         if self.bin.run_started_unix_ms != next.bin.run_started_unix_ms {
         if self.bin.run_started_unix_ms != next.bin.run_started_unix_ms {
             push_ch("run_started_unix_ms", JsonVal::Num(self.bin.run_started_unix_ms as f64), JsonVal::Num(next.bin.run_started_unix_ms as f64));
             push_ch("run_started_unix_ms", JsonVal::Num(self.bin.run_started_unix_ms as f64), JsonVal::Num(next.bin.run_started_unix_ms as f64));
         }
         }
         if self.bin.run_ended_unix_ms != next.bin.run_ended_unix_ms {
         if self.bin.run_ended_unix_ms != next.bin.run_ended_unix_ms {
             push_ch("run_ended_unix_ms", JsonVal::Num(self.bin.run_ended_unix_ms as f64), JsonVal::Num(next.bin.run_ended_unix_ms as f64));
             push_ch("run_ended_unix_ms", JsonVal::Num(self.bin.run_ended_unix_ms as f64), JsonVal::Num(next.bin.run_ended_unix_ms as f64));
         }
         }
-        if self.bin.raw_write_offset != next.bin.raw_write_offset {
-            push_ch("raw_write_offset", JsonVal::Num(self.bin.raw_write_offset as f64), JsonVal::Num(next.bin.raw_write_offset as f64));
-        }
-        if self.bin.clean_write_offset != next.bin.clean_write_offset {
-            push_ch("clean_write_offset", JsonVal::Num(self.bin.clean_write_offset as f64), JsonVal::Num(next.bin.clean_write_offset as f64));
-        }
         for i in 0..24 {
         for i in 0..24 {
             if self.bin.dimm_state[i] != next.bin.dimm_state[i] {
             if self.bin.dimm_state[i] != next.bin.dimm_state[i] {
                 push_ch(
                 push_ch(
@@ -574,10 +630,21 @@ impl RotatingFile {
             .join(format!("{}.{:04}.{}", self.prefix, self.volume_idx, self.ext))
             .join(format!("{}.{:04}.{}", self.prefix, self.volume_idx, self.ext))
     }
     }
 
 
-    fn ensure_open(&mut self, trace_dir: &Path, today: &str) -> std::io::Result<()> {
+    fn ensure_open(
+        &mut self,
+        trace_dir: &Path,
+        today: &str,
+        compress_rotated: bool,
+    ) -> std::io::Result<()> {
         if self.file.is_some() && self.day == today {
         if self.file.is_some() && self.day == today {
             return Ok(());
             return Ok(());
         }
         }
+        // Midnight rollover: close & index/compress previous day's active volume cleanly!
+        if self.file.is_some() && !self.day.is_empty() && self.day != today {
+            let prev_path = self.current_path(trace_dir);
+            self.file = None;
+            spawn_bg_index_and_gzip(prev_path, compress_rotated);
+        }
         self.file = None;
         self.file = None;
         self.day = today.to_string();
         self.day = today.to_string();
         let day_dir = trace_dir.join(&self.day);
         let day_dir = trace_dir.join(&self.day);
@@ -621,7 +688,7 @@ impl RotatingFile {
         if self.pending.is_empty() {
         if self.pending.is_empty() {
             return 0;
             return 0;
         }
         }
-        if self.ensure_open(trace_dir, today).is_err() {
+        if self.ensure_open(trace_dir, today, compress_rotated).is_err() {
             self.pending.clear();
             self.pending.clear();
             return 0;
             return 0;
         }
         }
@@ -640,25 +707,74 @@ impl RotatingFile {
             self.file = None;
             self.file = None;
             self.volume_idx = self.volume_idx.saturating_add(1);
             self.volume_idx = self.volume_idx.saturating_add(1);
             self.written_in_vol = 0;
             self.written_in_vol = 0;
-            if compress_rotated {
-                spawn_bg_gzip(rotated_path);
-            }
+            spawn_bg_index_and_gzip(rotated_path, compress_rotated);
         }
         }
         total_written
         total_written
     }
     }
 }
 }
 
 
-fn spawn_bg_gzip(path: PathBuf) {
+/// Low-priority (`SCHED_IDLE`) background rotation worker:
+/// 1. Runs hardware-accelerated batch CRC32 (`stl_batch_chunk_crc32`) + OpenCL/SIMD log scan
+///    (`opencl_or_cpu_batch_rescan`) to produce `<volume>.idx.json` for fast post-test indexing.
+/// 2. Optionally compresses the rotated volume with `gzip -1 -f`.
+fn spawn_bg_index_and_gzip(path: PathBuf, compress_rotated: bool) {
     let _ = thread::Builder::new()
     let _ = thread::Builder::new()
-        .name("stl-trace-gzip".to_string())
+        .name("stl-trace-idxgz".to_string())
         .spawn(move || {
         .spawn(move || {
             unsafe {
             unsafe {
                 lib::stl_set_thread_idle_priority();
                 lib::stl_set_thread_idle_priority();
             }
             }
-            let _ = std::process::Command::new("gzip")
-                .args(["-1", "-f"])
-                .arg(&path)
-                .status();
+            if let Ok(bytes) = fs::read(&path) {
+                if !bytes.is_empty() {
+                    let counts = lib::opencl_or_cpu_batch_rescan(&bytes);
+                    let chunk_sz: usize = 256 * 1024;
+                    let n_chunks = (bytes.len() + chunk_sz - 1) / chunk_sz;
+                    let mut crcs = vec![0u32; n_chunks];
+                    let mut used_gpu: i32 = 0;
+                    unsafe {
+                        lib::stl_batch_chunk_crc32(
+                            bytes.as_ptr(),
+                            bytes.len(),
+                            chunk_sz,
+                            crcs.as_mut_ptr(),
+                            n_chunks,
+                            &mut used_gpu,
+                        );
+                    }
+                    let mut idx_obj = JsonVal::obj();
+                    idx_obj.set(
+                        "file",
+                        JsonVal::Str(
+                            path.file_name()
+                                .and_then(|s| s.to_str())
+                                .unwrap_or("")
+                                .to_string(),
+                        ),
+                    );
+                    idx_obj.set("bytes", JsonVal::Num(bytes.len() as f64));
+                    idx_obj.set("error_markers", JsonVal::Num(counts[0] as f64));
+                    idx_obj.set("amt_markers", JsonVal::Num(counts[1] as f64));
+                    idx_obj.set("mt_markers", JsonVal::Num(counts[2] as f64));
+                    idx_obj.set("lines_counted", JsonVal::Num(counts[3] as f64));
+                    idx_obj.set("chunk_bytes", JsonVal::Num(chunk_sz as f64));
+                    idx_obj.set(
+                        "chunk_crc32",
+                        JsonVal::Arr(
+                            crcs.into_iter()
+                                .map(|c| JsonVal::Str(format!("{:08x}", c)))
+                                .collect(),
+                        ),
+                    );
+                    let idx_path = PathBuf::from(format!("{}.idx.json", path.to_string_lossy()));
+                    let _ = atomic_write_bytes(&idx_path, idx_obj.to_json().as_bytes());
+                }
+            }
+            if compress_rotated {
+                let _ = std::process::Command::new("gzip")
+                    .args(["-1", "-f"])
+                    .arg(&path)
+                    .status();
+            }
         });
         });
 }
 }
 
 
@@ -1024,12 +1140,13 @@ impl TraceHub {
         count
         count
     }
     }
 
 
-    /// Build a zero-dependency POSIX ustar `.tar` diagnostic archive of trace files.
-    pub fn build_diagnostic_bundle_tar(
+    /// Collect trace bundle entries (`(archive_name, optional_mem_bytes, optional_file_path, exact_size)`)
+    /// so we can compute exact `Content-Length` and stream straight to `TcpStream` in 64 KiB chunks (zero OOM!).
+    pub fn prepare_diagnostic_bundle_plan(
         &self,
         &self,
         station_filter: &str,
         station_filter: &str,
         day_filter: &str,
         day_filter: &str,
-    ) -> Result<(String, Vec<u8>), String> {
+    ) -> Result<(String, u64, Vec<(String, Option<Vec<u8>>, Option<PathBuf>, u64)>), String> {
         self.flush();
         self.flush();
         let target_day = if day_filter.is_empty() {
         let target_day = if day_filter.is_empty() {
             utc_day_string(now_ms())
             utc_day_string(now_ms())
@@ -1040,11 +1157,13 @@ impl TraceHub {
                 .take(10)
                 .take(10)
                 .collect()
                 .collect()
         };
         };
-        let mut tar = Vec::with_capacity(256 * 1024);
+        let mut plan: Vec<(String, Option<Vec<u8>>, Option<PathBuf>, u64)> = Vec::new();
         let cfg_bytes = self.get_config().to_json().to_json().into_bytes();
         let cfg_bytes = self.get_config().to_json().to_json().into_bytes();
-        tar_append_entry(&mut tar, "trace/config.json", &cfg_bytes);
+        let cfg_len = cfg_bytes.len() as u64;
+        plan.push(("trace/config.json".to_string(), Some(cfg_bytes), None, cfg_len));
         let status_bytes = self.get_status_json().to_json().into_bytes();
         let status_bytes = self.get_status_json().to_json().into_bytes();
-        tar_append_entry(&mut tar, "trace/status.json", &status_bytes);
+        let status_len = status_bytes.len() as u64;
+        plan.push(("trace/status.json".to_string(), Some(status_bytes), None, status_len));
 
 
         let day_dir = self.trace_dir.join(&target_day);
         let day_dir = self.trace_dir.join(&target_day);
         if day_dir.is_dir() {
         if day_dir.is_dir() {
@@ -1071,24 +1190,86 @@ impl TraceHub {
                 {
                 {
                     continue;
                     continue;
                 }
                 }
-                if let Ok(bytes) = fs::read(&path) {
+                if let Ok(md) = fs::metadata(&path) {
                     let arc_name = format!("trace/{}/{}", target_day, fname);
                     let arc_name = format!("trace/{}/{}", target_day, fname);
-                    tar_append_entry(&mut tar, &arc_name, &bytes);
+                    plan.push((arc_name, None, Some(path), md.len()));
                 }
                 }
             }
             }
         }
         }
-        // Standard POSIX tar EOF: two 512-byte zero blocks
-        tar.resize(tar.len() + 1024, 0);
+        let mut total_size: u64 = 1024; // 2x512B POSIX tar EOF
+        for (_, _, _, sz) in &plan {
+            let padded = (*sz + 511) & !511;
+            total_size = total_size.saturating_add(512 + padded);
+        }
         let fname = if station_filter.is_empty() {
         let fname = if station_filter.is_empty() {
             format!("stl_trace_{}.tar", target_day)
             format!("stl_trace_{}.tar", target_day)
         } else {
         } else {
             format!("stl_trace_{}_{}.tar", station_filter, target_day)
             format!("stl_trace_{}_{}.tar", station_filter, target_day)
         };
         };
+        Ok((fname, total_size, plan))
+    }
+
+    pub fn stream_diagnostic_bundle_tar<W: Write>(
+        plan: &[(String, Option<Vec<u8>>, Option<PathBuf>, u64)],
+        writer: &mut W,
+    ) -> std::io::Result<()> {
+        let mut io_buf = vec![0u8; 65536];
+        let zero_pad = [0u8; 512];
+        for (arc_name, mem_opt, path_opt, sz) in plan {
+            let hdr = build_tar_header(arc_name, *sz);
+            writer.write_all(&hdr)?;
+            let mut written: u64 = 0;
+            if let Some(bytes) = mem_opt {
+                let take = (bytes.len() as u64).min(*sz) as usize;
+                writer.write_all(&bytes[..take])?;
+                written = take as u64;
+            } else if let Some(path) = path_opt {
+                if let Ok(mut f) = File::open(path) {
+                    use std::io::Read;
+                    while written < *sz {
+                        let want = ((*sz - written) as usize).min(io_buf.len());
+                        match f.read(&mut io_buf[..want]) {
+                            Ok(0) => break,
+                            Ok(n) => {
+                                writer.write_all(&io_buf[..n])?;
+                                written += n as u64;
+                            }
+                            Err(_) => break,
+                        }
+                    }
+                }
+            }
+            // If file shrank concurrently, pad with zeros to preserve exact Content-Length & tar framing
+            while written < *sz {
+                let need = ((*sz - written) as usize).min(zero_pad.len());
+                writer.write_all(&zero_pad[..need])?;
+                written += need as u64;
+            }
+            let rem = (*sz % 512) as usize;
+            if rem != 0 {
+                writer.write_all(&zero_pad[..512 - rem])?;
+            }
+        }
+        writer.write_all(&zero_pad)?;
+        writer.write_all(&zero_pad)?;
+        Ok(())
+    }
+
+    /// Build a zero-dependency POSIX ustar `.tar` diagnostic archive of trace files (in-memory helper for tests).
+    pub fn build_diagnostic_bundle_tar(
+        &self,
+        station_filter: &str,
+        day_filter: &str,
+    ) -> Result<(String, Vec<u8>), String> {
+        let (fname, total_sz, plan) = self.prepare_diagnostic_bundle_plan(station_filter, day_filter)?;
+        let mut tar = Vec::with_capacity(total_sz.min(64 * 1024 * 1024) as usize);
+        Self::stream_diagnostic_bundle_tar(&plan, &mut tar)
+            .map_err(|e| format!("打包诊断归档失败: {}", e))?;
         Ok((fname, tar))
         Ok((fname, tar))
     }
     }
 }
 }
 
 
-fn tar_append_entry(tar: &mut Vec<u8>, name: &str, data: &[u8]) {
+fn build_tar_header(name: &str, size: u64) -> [u8; 512] {
     let mut hdr = [0u8; 512];
     let mut hdr = [0u8; 512];
     let nbytes = name.as_bytes();
     let nbytes = name.as_bytes();
     let nlen = nbytes.len().min(100);
     let nlen = nbytes.len().min(100);
@@ -1096,7 +1277,7 @@ fn tar_append_entry(tar: &mut Vec<u8>, name: &str, data: &[u8]) {
     hdr[100..108].copy_from_slice(b"0000644\0");
     hdr[100..108].copy_from_slice(b"0000644\0");
     hdr[108..116].copy_from_slice(b"0000000\0");
     hdr[108..116].copy_from_slice(b"0000000\0");
     hdr[116..124].copy_from_slice(b"0000000\0");
     hdr[116..124].copy_from_slice(b"0000000\0");
-    let sz_oct = format!("{:011o}\0", data.len());
+    let sz_oct = format!("{:011o}\0", size);
     hdr[124..136].copy_from_slice(&sz_oct.as_bytes()[..12]);
     hdr[124..136].copy_from_slice(&sz_oct.as_bytes()[..12]);
     let mtime = (now_ms().max(0) / 1000) as u64;
     let mtime = (now_ms().max(0) / 1000) as u64;
     let mt_oct = format!("{:011o}\0", mtime);
     let mt_oct = format!("{:011o}\0", mtime);
@@ -1110,13 +1291,7 @@ fn tar_append_entry(tar: &mut Vec<u8>, name: &str, data: &[u8]) {
     let csum: u32 = hdr.iter().map(|&b| b as u32).sum();
     let csum: u32 = hdr.iter().map(|&b| b as u32).sum();
     let cs_oct = format!("{:06o}\0 ", csum);
     let cs_oct = format!("{:06o}\0 ", csum);
     hdr[148..156].copy_from_slice(&cs_oct.as_bytes()[..8]);
     hdr[148..156].copy_from_slice(&cs_oct.as_bytes()[..8]);
-
-    tar.extend_from_slice(&hdr);
-    tar.extend_from_slice(data);
-    let rem = data.len() % 512;
-    if rem != 0 {
-        tar.resize(tar.len() + (512 - rem), 0);
-    }
+    hdr
 }
 }
 
 
 fn writer_loop(hub: Arc<TraceHub>, rx: mpsc::Receiver<TraceMsg>, mut cfg: TraceConfig) {
 fn writer_loop(hub: Arc<TraceHub>, rx: mpsc::Receiver<TraceMsg>, mut cfg: TraceConfig) {
@@ -1241,7 +1416,11 @@ fn writer_loop(hub: Arc<TraceHub>, rx: mpsc::Receiver<TraceMsg>, mut cfg: TraceC
             }
             }
             Ok(TraceMsg::ConfigUpdated(next_cfg)) => {
             Ok(TraceMsg::ConfigUpdated(next_cfg)) => {
                 flush_all(&hub, &cfg, &mut backend_file, &mut frontend_file, &mut serial_files, &mut pending_bytes);
                 flush_all(&hub, &cfg, &mut backend_file, &mut frontend_file, &mut serial_files, &mut pending_bytes);
+                let retention_lowered = next_cfg.retention_days < cfg.retention_days;
                 cfg = next_cfg;
                 cfg = next_cfg;
+                if retention_lowered {
+                    last_cleanup_day.clear();
+                }
                 check_disk_and_cleanup(&hub, &cfg, &mut last_cleanup_day);
                 check_disk_and_cleanup(&hub, &cfg, &mut last_cleanup_day);
             }
             }
             Ok(TraceMsg::ForceDiskCheck(reply)) => {
             Ok(TraceMsg::ForceDiskCheck(reply)) => {
@@ -1293,8 +1472,9 @@ fn apply_diff_path(state: &mut JsonVal, path: &str, new_val: JsonVal) {
 }
 }
 
 
 /// Offline state reconstructor (`--replay-trace <dir> [--station S1] [--at-ms <unix_ms>]`).
 /// Offline state reconstructor (`--replay-trace <dir> [--station S1] [--at-ms <unix_ms>]`).
-/// Scans `backend.*.jsonl` files inside `<dir>` (or its `YYYY-MM-DD` subdirectories), locates the latest
-/// `state_snapshot` <= `at_ms` per station, replays every `state_diff` up to `at_ms`, and returns reconstructed JSON.
+/// Transparently scans both `backend.*.jsonl` and rotated `backend.*.jsonl.gz` files inside `<dir>`
+/// (or its `YYYY-MM-DD` subdirectories), locates the latest `state_snapshot` <= `at_ms` per station,
+/// replays every `state_diff` up to `at_ms`, and returns reconstructed JSON.
 pub fn replay_trace_dir(
 pub fn replay_trace_dir(
     dir: &Path,
     dir: &Path,
     station_filter: Option<&str>,
     station_filter: Option<&str>,
@@ -1307,7 +1487,9 @@ pub fn replay_trace_dir(
                 let p = ent.path();
                 let p = ent.path();
                 if p.is_file() {
                 if p.is_file() {
                     let name = ent.file_name().to_string_lossy().to_string();
                     let name = ent.file_name().to_string_lossy().to_string();
-                    if name.starts_with("backend.") && name.ends_with(".jsonl") {
+                    if name.starts_with("backend.")
+                        && (name.ends_with(".jsonl") || name.ends_with(".jsonl.gz"))
+                    {
                         out.push(p);
                         out.push(p);
                     }
                     }
                 }
                 }
@@ -1328,35 +1510,65 @@ pub fn replay_trace_dir(
     }
     }
     files.sort();
     files.sort();
     if files.is_empty() {
     if files.is_empty() {
-        return Err(format!("在目录 {} 下未找到 backend.*.jsonl 日志文件", dir.display()));
+        return Err(format!(
+            "在目录 {} 下未找到 backend.*.jsonl(.gz) 日志文件",
+            dir.display()
+        ));
     }
     }
 
 
     let mut events: Vec<(i64, u64, JsonVal)> = Vec::new();
     let mut events: Vec<(i64, u64, JsonVal)> = Vec::new();
-    for fpath in &files {
-        let Ok(f) = File::open(fpath) else { continue; };
-        let reader = BufReader::new(f);
-        for line in reader.lines().map_while(Result::ok) {
-            let trimmed = line.trim();
-            if trimmed.is_empty() {
-                continue;
-            }
-            let Ok(ev) = parse_json(trimmed) else { continue; };
-            let kind = ev.get_str_or("kind", "");
-            if kind != "state_snapshot" && kind != "state_diff" {
-                continue;
+    let mut ingest_line = |line: &str| {
+        let trimmed = line.trim();
+        if trimmed.is_empty() {
+            return;
+        }
+        let Ok(ev) = parse_json(trimmed) else { return; };
+        let kind = ev.get_str_or("kind", "");
+        if kind != "state_snapshot" && kind != "state_diff" {
+            return;
+        }
+        let sid = ev.get_str_or("station_id", "");
+        if let Some(filt) = station_filter {
+            if !filt.is_empty() && sid != filt {
+                return;
             }
             }
-            let sid = ev.get_str_or("station_id", "");
-            if let Some(filt) = station_filter {
-                if !filt.is_empty() && sid != filt {
-                    continue;
+        }
+        let ts = ev.get_i64("ts_ms").unwrap_or(0);
+        if at_ms >= 0 && ts > at_ms {
+            return;
+        }
+        let seq = ev.get_i64("seq").unwrap_or(0).max(0) as u64;
+        events.push((ts, seq, ev));
+    };
+
+    for fpath in &files {
+        let is_gz = fpath
+            .file_name()
+            .and_then(|s| s.to_str())
+            .map(|s| s.ends_with(".gz"))
+            .unwrap_or(false);
+        if is_gz {
+            if let Ok(mut child) = std::process::Command::new("gzip")
+                .args(["-dc"])
+                .arg(fpath)
+                .stdout(std::process::Stdio::piped())
+                .stderr(std::process::Stdio::null())
+                .spawn()
+            {
+                if let Some(stdout) = child.stdout.take() {
+                    let reader = BufReader::new(stdout);
+                    for line in reader.lines().map_while(Result::ok) {
+                        ingest_line(&line);
+                    }
                 }
                 }
+                let _ = child.wait();
             }
             }
-            let ts = ev.get_i64("ts_ms").unwrap_or(0);
-            if at_ms > 0 && ts > at_ms {
-                continue;
+        } else {
+            let Ok(f) = File::open(fpath) else { continue; };
+            let reader = BufReader::new(f);
+            for line in reader.lines().map_while(Result::ok) {
+                ingest_line(&line);
             }
             }
-            let seq = ev.get_i64("seq").unwrap_or(0).max(0) as u64;
-            events.push((ts, seq, ev));
         }
         }
     }
     }
     events.sort_by_key(|(ts, seq, _)| (*ts, *seq));
     events.sort_by_key(|(ts, seq, _)| (*ts, *seq));

+ 285 - 60
native/stl_accel/src/workflow.rs

@@ -1135,6 +1135,62 @@ pub fn build_uefi_mt_steps(st: &StationState, sel: &JsonVal) -> Vec<AsyncScriptS
                     st.pxe_server_ip.as_str()
                     st.pxe_server_ip.as_str()
                 }
                 }
             });
             });
+        // Diskless-first UEFI Shell support: if no local FSx: filesystem exists at all and no local EFI was found,
+        // boot directly over TFTP into RAM (`tftp <ip> 118.efi` -> `118.efi`, or GRUB `net_bootp` + `chainloader (tftp,<ip>)/118.efi`)!
+        if st.uefi_fs_candidates.is_empty() && st.resolved_mt_efi_path.is_none() {
+            if let Some(ref grub_loader) = st.resolved_grub_tftp_loader {
+                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,{})/{}", tftp_ip, efi_basename),
+                    expected_prompt_kind: "grub_cli".to_string(),
+                    timeout_ms: 15000,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: "boot".to_string(),
+                    expected_prompt_kind: String::new(),
+                    timeout_ms: 4000,
+                    reject_on_fw_error: false,
+                });
+            } else {
+                steps.push(AsyncScriptStep {
+                    line: format!("tftp {} {}", tftp_ip, efi_basename),
+                    expected_prompt_kind: "uefi".to_string(),
+                    timeout_ms: 15000,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: format!("tftp {} mt86.cfg", tftp_ip),
+                    expected_prompt_kind: "uefi".to_string(),
+                    timeout_ms: 8000,
+                    reject_on_fw_error: false,
+                });
+                steps.push(AsyncScriptStep {
+                    line: efi_basename,
+                    expected_prompt_kind: String::new(),
+                    timeout_ms: 2000,
+                    reject_on_fw_error: false,
+                });
+            }
+            return steps;
+        }
         let cfg_lines: Vec<String> = render_mt86_cfg_text(sel, tftp_ip)
         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())
@@ -1284,17 +1340,35 @@ pub fn evaluate_stage_watchdog(st: &mut StationState, now: i64) -> bool {
         }
         }
     }
     }
 
 
-    let batch_unattended = st.task_batch.get_str_or("state", "idle") == "running"
-        && !st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
-    let batch_reboot = st
-        .task_batch
-        .get_bool("reboot_on_hang")
-        .unwrap_or(st.watchdog.reboot_on_hang);
-    let max_hangs = st
-        .task_batch
-        .get_i64("max_consecutive_hangs")
-        .map(|v| v.clamp(1, 20) as u32)
-        .unwrap_or(st.watchdog.max_consecutive_hangs);
+    let batch_running = st.task_batch.get_str_or("state", "idle") == "running";
+    let eff_hang_action = if batch_running {
+        if let Some(ha) = st.task_batch.get_str("hang_action") {
+            crate::results::normalize_hang_action(ha)
+        } else if let Some(roh) = st.task_batch.get_bool("reboot_on_hang") {
+            if roh {
+                "retry_current_task"
+            } else {
+                "stop"
+            }
+        } else {
+            st.watchdog.effective_hang_action()
+        }
+    } else {
+        st.watchdog.effective_hang_action()
+    };
+    let max_hangs = if batch_running {
+        st.task_batch
+            .get_i64("max_consecutive_hangs")
+            .map(|v| v.clamp(0, 100) as u32)
+            .unwrap_or(st.watchdog.max_consecutive_hangs)
+    } else {
+        st.watchdog.max_consecutive_hangs
+    };
+    let hang_action_label = match eff_hang_action {
+        "retry_current_task" => "自动重启并重做当前未完成任务",
+        "restart_full_plan" => "自动重启并重做整个计划",
+        _ => "冻结计时并保留死机现场",
+    };
 
 
     // 1. Check total stage duration caps for MT and AMT (catches ANSI clock-redraw infinite loops)
     // 1. Check total stage duration caps for MT and AMT (catches ANSI clock-redraw infinite loops)
     if st.observed_phase == "mt"
     if st.observed_phase == "mt"
@@ -1304,11 +1378,12 @@ pub fn evaluate_stage_watchdog(st: &mut StationState, now: i64) -> bool {
         let mt_dur = now.saturating_sub(st.mt_started_unix_ms);
         let mt_dur = now.saturating_sub(st.mt_started_unix_ms);
         if mt_dur >= st.watchdog.mt_max_duration_ms {
         if mt_dur >= st.watchdog.mt_max_duration_ms {
             let next_hangs = st.consecutive_hang_count.saturating_add(1);
             let next_hangs = st.consecutive_hang_count.saturating_add(1);
-            let will_reboot = batch_unattended && batch_reboot && next_hangs < max_hangs;
+            let within_limit = max_hangs == 0 || next_hangs < max_hangs;
+            let will_reboot = eff_hang_action != "stop" && within_limit;
             st.consecutive_hang_count = next_hangs;
             st.consecutive_hang_count = next_hangs;
-            let msg = if !will_reboot && batch_unattended && batch_reboot && next_hangs >= max_hangs {
+            let msg = if !will_reboot && eff_hang_action != "stop" && !within_limit {
                 format!(
                 format!(
-                    "MT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (mt_duration_timeout);连续死机已达 {}/{} 次熔断上限,停止自动重启并保留现场",
+                    "MT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (mt_duration_timeout);连续死机已达 {}/{} 次上限,停止自动重启并保留现场",
                     mt_dur as f64 / 1000.0,
                     mt_dur as f64 / 1000.0,
                     st.watchdog.mt_max_duration_ms as f64 / 1000.0,
                     st.watchdog.mt_max_duration_ms as f64 / 1000.0,
                     next_hangs,
                     next_hangs,
@@ -1316,11 +1391,12 @@ pub fn evaluate_stage_watchdog(st: &mut StationState, now: i64) -> bool {
                 )
                 )
             } else if will_reboot {
             } else if will_reboot {
                 format!(
                 format!(
-                    "MT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (mt_duration_timeout);将执行第 {}/{} 次自动重启恢复",
+                    "MT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (mt_duration_timeout);将执行第 {} 次{}(上限 {})",
                     mt_dur as f64 / 1000.0,
                     mt_dur as f64 / 1000.0,
                     st.watchdog.mt_max_duration_ms as f64 / 1000.0,
                     st.watchdog.mt_max_duration_ms as f64 / 1000.0,
                     next_hangs,
                     next_hangs,
-                    max_hangs
+                    hang_action_label,
+                    if max_hangs == 0 { "不限".to_string() } else { max_hangs.to_string() }
                 )
                 )
             } else {
             } else {
                 format!(
                 format!(
@@ -1348,14 +1424,20 @@ pub fn evaluate_stage_watchdog(st: &mut StationState, now: i64) -> bool {
         let amt_dur = now.saturating_sub(st.amt_started_unix_ms);
         let amt_dur = now.saturating_sub(st.amt_started_unix_ms);
         if amt_dur >= st.watchdog.amt_max_duration_ms {
         if amt_dur >= st.watchdog.amt_max_duration_ms {
             let next_hangs = st.consecutive_hang_count.saturating_add(1);
             let next_hangs = st.consecutive_hang_count.saturating_add(1);
-            let will_reboot = batch_unattended && batch_reboot && next_hangs < max_hangs;
+            let within_limit = max_hangs == 0 || next_hangs < max_hangs;
+            let will_reboot = eff_hang_action != "stop" && within_limit;
             st.consecutive_hang_count = next_hangs;
             st.consecutive_hang_count = next_hangs;
             let msg = format!(
             let msg = format!(
                 "AMT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (amt_duration_timeout);{}",
                 "AMT 阶段总运行时长 {:.1}s 超过上限 {:.0}s (amt_duration_timeout);{}",
                 amt_dur as f64 / 1000.0,
                 amt_dur as f64 / 1000.0,
                 st.watchdog.amt_max_duration_ms as f64 / 1000.0,
                 st.watchdog.amt_max_duration_ms as f64 / 1000.0,
                 if will_reboot {
                 if will_reboot {
-                    format!("将执行第 {}/{} 次自动重启恢复", next_hangs, max_hangs)
+                    format!(
+                        "将执行第 {} 次{}(上限 {})",
+                        next_hangs,
+                        hang_action_label,
+                        if max_hangs == 0 { "不限".to_string() } else { max_hangs.to_string() }
+                    )
                 } else {
                 } else {
                     "已冻结计时并保留死机现场未重启".to_string()
                     "已冻结计时并保留死机现场未重启".to_string()
                 }
                 }
@@ -1386,11 +1468,12 @@ pub fn evaluate_stage_watchdog(st: &mut StationState, now: i64) -> bool {
             st.observed_phase.clone()
             st.observed_phase.clone()
         };
         };
         let next_hangs = st.consecutive_hang_count.saturating_add(1);
         let next_hangs = st.consecutive_hang_count.saturating_add(1);
-        let will_reboot = batch_unattended && batch_reboot && next_hangs < max_hangs;
+        let within_limit = max_hangs == 0 || next_hangs < max_hangs;
+        let will_reboot = eff_hang_action != "stop" && within_limit;
         st.consecutive_hang_count = next_hangs;
         st.consecutive_hang_count = next_hangs;
-        let msg = if !will_reboot && batch_unattended && batch_reboot && next_hangs >= max_hangs {
+        let msg = if !will_reboot && eff_hang_action != "stop" && !within_limit {
             format!(
             format!(
-                "阶段 {} 连续 {:.1}s 无串口输出 (阈值 {:.0}s),判定服务器死机卡死 (stage_hang_timeout);连续死机已达 {}/{} 次熔断阈值,停止自动重启并保留现场",
+                "阶段 {} 连续 {:.1}s 无串口输出 (阈值 {:.0}s),判定服务器死机卡死 (stage_hang_timeout);连续死机已达 {}/{} 次上限,停止自动重启并保留现场",
                 stg,
                 stg,
                 silence_ms as f64 / 1000.0,
                 silence_ms as f64 / 1000.0,
                 limit_ms as f64 / 1000.0,
                 limit_ms as f64 / 1000.0,
@@ -1399,12 +1482,13 @@ pub fn evaluate_stage_watchdog(st: &mut StationState, now: i64) -> bool {
             )
             )
         } else if will_reboot {
         } else if will_reboot {
             format!(
             format!(
-                "阶段 {} 连续 {:.1}s 无串口输出 (阈值 {:.0}s),判定服务器死机卡死 (stage_hang_timeout);将执行第 {}/{} 次自动重启恢复",
+                "阶段 {} 连续 {:.1}s 无串口输出 (阈值 {:.0}s),判定服务器死机卡死 (stage_hang_timeout);将执行第 {} 次{}(上限 {})",
                 stg,
                 stg,
                 silence_ms as f64 / 1000.0,
                 silence_ms as f64 / 1000.0,
                 limit_ms as f64 / 1000.0,
                 limit_ms as f64 / 1000.0,
                 next_hangs,
                 next_hangs,
-                max_hangs
+                hang_action_label,
+                if max_hangs == 0 { "不限".to_string() } else { max_hangs.to_string() }
             )
             )
         } else {
         } else {
             format!(
             format!(
@@ -2375,8 +2459,12 @@ pub fn apply_profile_to_station(
             .iter()
             .iter()
             .any(|c| c.trim().to_ascii_lowercase().starts_with("pxe "))
             .any(|c| c.trim().to_ascii_lowercase().starts_with("pxe "))
     {
     {
-        for cmd in crate::pxe::STAGE1_PXE_COMMANDS {
-            uip_raws.push(cmd.to_string());
+        let sip = pxe_state.get_str_or("pxe_server_ip", &st.pxe_server_ip);
+        let mask = pxe_state.get_str_or("pxe_subnet_mask", "255.255.255.0");
+        let cip = pxe_state.get_str_or("pxe_client_ip", "192.168.0.160");
+        let efi = pxe_state.get_str_or("active_efi", crate::pxe::PXE_EFI_FILENAME);
+        for cmd in crate::pxe::build_stage1_pxe_commands(&sip, &mask, &cip, &efi) {
+            uip_raws.push(cmd);
         }
         }
     }
     }
     let _ = contract.build_uip_commands_for_family(
     let _ = contract.build_uip_commands_for_family(
@@ -2463,26 +2551,38 @@ pub fn apply_profile_to_station(
     if let Some(wd) = profile.get("watchdog") {
     if let Some(wd) = profile.get("watchdog") {
         st.watchdog.apply_patch(wd);
         st.watchdog.apply_patch(wd);
     }
     }
-    if let Some(roh) = profile.get_bool("reboot_on_hang") {
+    if let Some(ha) = profile.get_str("hang_action") {
+        let norm = crate::results::normalize_hang_action(ha);
+        st.watchdog.hang_action = norm.to_string();
+        st.watchdog.reboot_on_hang = norm != "stop";
+    } else if let Some(roh) = profile.get_bool("reboot_on_hang") {
         st.watchdog.reboot_on_hang = roh;
         st.watchdog.reboot_on_hang = roh;
+        if !roh {
+            st.watchdog.hang_action = "stop".to_string();
+        } else if st.watchdog.hang_action == "stop" {
+            st.watchdog.hang_action = "retry_current_task".to_string();
+        }
     }
     }
     if let Some(mch) = profile.get_i64("max_consecutive_hangs") {
     if let Some(mch) = profile.get_i64("max_consecutive_hangs") {
-        st.watchdog.max_consecutive_hangs = mch.max(1) as u32;
+        st.watchdog.max_consecutive_hangs = mch.clamp(0, 100) as u32;
     }
     }
-    if let Some(en) = profile
+    let explicit_th_auto = profile
         .get_bool("thermal_auto_enabled")
         .get_bool("thermal_auto_enabled")
-        .or_else(|| profile.get("thermal_policy").and_then(|t| t.get_bool("auto_enabled")))
-    {
-        st.thermal_auto_enabled = en;
-    }
-    if let Some(tc) = profile
+        .or_else(|| profile.get("thermal_policy").and_then(|t| t.get_bool("auto_enabled")));
+    let explicit_th_tgt = profile
         .get_i64("target_temp_c")
         .get_i64("target_temp_c")
-        .or_else(|| profile.get("thermal_policy").and_then(|t| t.get_i64("target_temp_c")))
-    {
+        .or_else(|| profile.get("thermal_policy").and_then(|t| t.get_i64("target_temp_c")));
+    if let Some(tc) = explicit_th_tgt {
         if (0..=254).contains(&tc) {
         if (0..=254).contains(&tc) {
             st.thermal_target_c = tc as u8;
             st.thermal_target_c = tc as u8;
+            if explicit_th_auto.is_none() {
+                st.thermal_auto_enabled = tc > 0;
+            }
         }
         }
     }
     }
+    if let Some(en) = explicit_th_auto {
+        st.thermal_auto_enabled = en;
+    }
     if let Some(req) = profile
     if let Some(req) = profile
         .get_bool("require_thermal_online")
         .get_bool("require_thermal_online")
         .or_else(|| profile.get("thermal_policy").and_then(|t| t.get_bool("require_online")))
         .or_else(|| profile.get("thermal_policy").and_then(|t| t.get_bool("require_online")))
@@ -2551,21 +2651,36 @@ pub fn submit_task_batch(
         .map(|s| s.to_string())
         .map(|s| s.to_string())
         .unwrap_or_else(|| format!("TB-{}-{}", st.station_id, now));
         .unwrap_or_else(|| format!("TB-{}-{}", st.station_id, now));
     let stop_on_fail = args.get_bool("stop_on_fail").unwrap_or(true);
     let stop_on_fail = args.get_bool("stop_on_fail").unwrap_or(true);
-    let reboot_on_hang = args
+    if let Some(wd) = args.get("watchdog") {
+        st.watchdog.apply_patch(wd);
+    }
+    let hang_action_str = if let Some(ha) = args
+        .get_str("hang_action")
+        .or_else(|| args.get("watchdog").and_then(|w| w.get_str("hang_action")))
+    {
+        crate::results::normalize_hang_action(ha).to_string()
+    } else if let Some(roh) = args
         .get_bool("reboot_on_hang")
         .get_bool("reboot_on_hang")
         .or_else(|| args.get("watchdog").and_then(|w| w.get_bool("reboot_on_hang")))
         .or_else(|| args.get("watchdog").and_then(|w| w.get_bool("reboot_on_hang")))
-        .unwrap_or(st.watchdog.reboot_on_hang);
+    {
+        if roh {
+            "retry_current_task".to_string()
+        } else {
+            "stop".to_string()
+        }
+    } else {
+        st.watchdog.effective_hang_action().to_string()
+    };
+    let reboot_on_hang = hang_action_str != "stop";
     let max_consecutive_hangs = args
     let max_consecutive_hangs = args
         .get_i64("max_consecutive_hangs")
         .get_i64("max_consecutive_hangs")
         .or_else(|| {
         .or_else(|| {
             args.get("watchdog")
             args.get("watchdog")
                 .and_then(|w| w.get_i64("max_consecutive_hangs"))
                 .and_then(|w| w.get_i64("max_consecutive_hangs"))
         })
         })
-        .map(|v| v.max(1) as u32)
+        .map(|v| v.clamp(0, 100) as u32)
         .unwrap_or(st.watchdog.max_consecutive_hangs);
         .unwrap_or(st.watchdog.max_consecutive_hangs);
-    if let Some(wd) = args.get("watchdog") {
-        st.watchdog.apply_patch(wd);
-    }
+    st.watchdog.hang_action = hang_action_str.clone();
     st.watchdog.reboot_on_hang = reboot_on_hang;
     st.watchdog.reboot_on_hang = reboot_on_hang;
     st.watchdog.max_consecutive_hangs = max_consecutive_hangs;
     st.watchdog.max_consecutive_hangs = max_consecutive_hangs;
     let auto_start = args.get_bool("auto_start").unwrap_or(true);
     let auto_start = args.get_bool("auto_start").unwrap_or(true);
@@ -2636,6 +2751,7 @@ pub fn submit_task_batch(
     tb.set("total_runs_completed", JsonVal::Num(0.0));
     tb.set("total_runs_completed", JsonVal::Num(0.0));
     tb.set("total_runs_planned", JsonVal::Num(total_planned as f64));
     tb.set("total_runs_planned", JsonVal::Num(total_planned as f64));
     tb.set("stop_on_fail", JsonVal::Bool(stop_on_fail));
     tb.set("stop_on_fail", JsonVal::Bool(stop_on_fail));
+    tb.set("hang_action", JsonVal::Str(hang_action_str));
     tb.set("reboot_on_hang", JsonVal::Bool(reboot_on_hang));
     tb.set("reboot_on_hang", JsonVal::Bool(reboot_on_hang));
     tb.set(
     tb.set(
         "max_consecutive_hangs",
         "max_consecutive_hangs",
@@ -2753,6 +2869,68 @@ pub fn step_task_batch(
         } else {
         } else {
             "fail"
             "fail"
         };
         };
+        let single_hang_action = st.watchdog.effective_hang_action();
+        let single_max_hangs = st.watchdog.max_consecutive_hangs;
+        let single_can_retry = st.single_run_active
+            && is_hang_fault
+            && single_hang_action != "stop"
+            && (single_max_hangs == 0 || st.consecutive_hang_count < single_max_hangs);
+
+        if single_can_retry {
+            // Archive hung attempt and reboot via BMC to redo the unfinished complete task cleanly!
+            let attempt_no = st.consecutive_hang_count;
+            let base_id = if st.single_run_id.is_empty() {
+                format!("RUN-{}-{}", st.station_id, now)
+            } else {
+                st.single_run_id.clone()
+            };
+            let archived_run_id = format!("{}-hang{}", base_id, attempt_no);
+            let p_name = st
+                .single_run_profile
+                .get_str("name")
+                .or_else(|| st.single_run_profile.get_str("task_name"))
+                .unwrap_or("Single-Run")
+                .to_string();
+            let started_ms = if st.run_started_unix_ms > 0 {
+                st.run_started_unix_ms
+            } else {
+                now
+            };
+            let prof_clone = st.single_run_profile.clone();
+            let (_, _, summary_obj) = archive_task_run(
+                data_dir,
+                st,
+                &archived_run_id,
+                "",
+                0,
+                &p_name,
+                attempt_no as usize,
+                single_max_hangs as usize,
+                "fail",
+                started_ms,
+                now,
+                &prof_clone,
+            );
+            st.task_history.push(summary_obj.clone());
+            emit_complete_signal(st, &archived_run_id, "", "fail", &summary_obj, false);
+            st.log_debug(
+                "WATCHDOG",
+                &format!(
+                    "SINGLE_RUN_HANG_REBOOT action={} attempt={} max={} run_id={}",
+                    single_hang_action, attempt_no, single_max_hangs, archived_run_id
+                ),
+            );
+            let saved_hang_cnt = st.consecutive_hang_count;
+            let _ = control_boot_plan_impl(st, "restart", data_dir, false);
+            st.consecutive_hang_count = saved_hang_cnt;
+            st.single_run_active = true;
+            st.single_run_id = format!("RUN-{}-{}", st.station_id, now);
+            st.single_run_started_ms = now;
+            st.task_status = "running".to_string();
+            save_station_settings(data_dir, st);
+            return;
+        }
+
         if st.single_run_active || matches!(st.task_status.as_str(), "running" | "queued") {
         if st.single_run_active || matches!(st.task_status.as_str(), "running" | "queued") {
             st.task_status = if verdict == "pass" {
             st.task_status = if verdict == "pass" {
                 "completed".to_string()
                 "completed".to_string()
@@ -2830,14 +3008,22 @@ pub fn step_task_batch(
         .max(0) as usize;
         .max(0) as usize;
     let cur_rep = st.task_batch.get_i64("current_repeat").unwrap_or(1).max(1) as usize;
     let cur_rep = st.task_batch.get_i64("current_repeat").unwrap_or(1).max(1) as usize;
     let stop_on_fail = st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
     let stop_on_fail = st.task_batch.get_bool("stop_on_fail").unwrap_or(true);
-    let reboot_on_hang = st
-        .task_batch
-        .get_bool("reboot_on_hang")
-        .unwrap_or(st.watchdog.reboot_on_hang);
+    let eff_hang_action = if let Some(ha) = st.task_batch.get_str("hang_action") {
+        crate::results::normalize_hang_action(ha)
+    } else if let Some(roh) = st.task_batch.get_bool("reboot_on_hang") {
+        if roh {
+            "retry_current_task"
+        } else {
+            "stop"
+        }
+    } else {
+        st.watchdog.effective_hang_action()
+    };
+    let reboot_on_hang = eff_hang_action != "stop";
     let max_hangs = st
     let max_hangs = st
         .task_batch
         .task_batch
         .get_i64("max_consecutive_hangs")
         .get_i64("max_consecutive_hangs")
-        .map(|v| v.max(1) as u32)
+        .map(|v| v.clamp(0, 100) as u32)
         .unwrap_or(st.watchdog.max_consecutive_hangs);
         .unwrap_or(st.watchdog.max_consecutive_hangs);
     let profiles = st.task_batch.get_arr("profiles").cloned().unwrap_or_default();
     let profiles = st.task_batch.get_arr("profiles").cloned().unwrap_or_default();
     if cur_p_idx >= profiles.len() {
     if cur_p_idx >= profiles.len() {
@@ -2851,7 +3037,20 @@ pub fn step_task_batch(
     let p_name = cur_profile.get_str_or("name", &format!("Profile-{}", cur_p_idx + 1));
     let p_name = cur_profile.get_str_or("name", &format!("Profile-{}", cur_p_idx + 1));
     // repeat == 0 means infinite continuous burn-in loop until stopped!
     // repeat == 0 means infinite continuous burn-in loop until stopped!
     let p_rep_total = cur_profile.get_i64("repeat").unwrap_or(1).max(0) as usize;
     let p_rep_total = cur_profile.get_i64("repeat").unwrap_or(1).max(0) as usize;
-    let run_id = format!("{}-P{}-R{}", batch_id, cur_p_idx + 1, cur_rep);
+    let hang_will_recover = is_hang_fault
+        && reboot_on_hang
+        && (max_hangs == 0 || st.consecutive_hang_count < max_hangs);
+    let run_id = if hang_will_recover {
+        format!(
+            "{}-P{}-R{}-hang{}",
+            batch_id,
+            cur_p_idx + 1,
+            cur_rep,
+            st.consecutive_hang_count
+        )
+    } else {
+        format!("{}-P{}-R{}", batch_id, cur_p_idx + 1, cur_rep)
+    };
     let has_any_err = st.awaiting_dimm_replacement
     let has_any_err = st.awaiting_dimm_replacement
         || !st.last_fault_code.is_empty()
         || !st.last_fault_code.is_empty()
         || st.stage_errors.values().any(|v| !v.is_empty());
         || st.stage_errors.values().any(|v| !v.is_empty());
@@ -2892,6 +3091,7 @@ pub fn step_task_batch(
     );
     );
 
 
     if let Some(last_run) = runs.last_mut() {
     if let Some(last_run) = runs.last_mut() {
+        last_run.set("run_id", JsonVal::Str(run_id.clone()));
         last_run.set("state", JsonVal::Str(bp_state.clone()));
         last_run.set("state", JsonVal::Str(bp_state.clone()));
         last_run.set("verdict", JsonVal::Str(verdict.to_string()));
         last_run.set("verdict", JsonVal::Str(verdict.to_string()));
         last_run.set("boot_id", JsonVal::Str(st.boot_id.clone()));
         last_run.set("boot_id", JsonVal::Str(st.boot_id.clone()));
@@ -2912,17 +3112,20 @@ pub fn step_task_batch(
 
 
     st.task_history.push(summary_obj.clone());
     st.task_history.push(summary_obj.clone());
 
 
-    let completed_total = st.task_batch.get_i64("total_runs_completed").unwrap_or(0) + 1;
+    let mut completed_total = st.task_batch.get_i64("total_runs_completed").unwrap_or(0);
+    if !hang_will_recover {
+        completed_total += 1;
+    }
     st.task_batch
     st.task_batch
         .set("total_runs_completed", JsonVal::Num(completed_total as f64));
         .set("total_runs_completed", JsonVal::Num(completed_total as f64));
     st.task_batch
     st.task_batch
         .set("updated_unix_ms", JsonVal::Str(now.to_string()));
         .set("updated_unix_ms", JsonVal::Str(now.to_string()));
 
 
-    let halt_for_hang_policy =
-        is_hang_fault && (!reboot_on_hang || st.consecutive_hang_count >= max_hangs);
-    if verdict == "fail" && (stop_on_fail || is_link_or_pwr_fault || halt_for_hang_policy) {
-        let halt_reason = if is_hang_fault && reboot_on_hang && st.consecutive_hang_count >= max_hangs
-        {
+    let hang_exceeded = is_hang_fault && reboot_on_hang && max_hangs > 0 && st.consecutive_hang_count >= max_hangs;
+    let halt_for_hang_policy = is_hang_fault && (!reboot_on_hang || hang_exceeded);
+    let halt_for_non_hang_fail = verdict == "fail" && !hang_will_recover && (stop_on_fail || is_link_or_pwr_fault);
+    if halt_for_hang_policy || halt_for_non_hang_fail {
+        let halt_reason = if hang_exceeded {
             st.last_fault_code = "consecutive_hang_limit_exceeded".to_string();
             st.last_fault_code = "consecutive_hang_limit_exceeded".to_string();
             st.hang_scene_preserved = true;
             st.hang_scene_preserved = true;
             "consecutive_hang_limit_exceeded".to_string()
             "consecutive_hang_limit_exceeded".to_string()
@@ -2955,7 +3158,17 @@ pub fn step_task_batch(
         return;
         return;
     }
     }
 
 
-    let (next_p_idx, next_rep) = if p_rep_total == 0 || cur_rep < p_rep_total {
+    let (next_p_idx, next_rep) = if hang_will_recover {
+        if eff_hang_action == "restart_full_plan" {
+            // Restart the ENTIRE batch plan from Profile 1 Round 1
+            completed_total = 0;
+            st.task_batch.set("total_runs_completed", JsonVal::Num(0.0));
+            (0usize, 1usize)
+        } else {
+            // `retry_current_task`: redo the exact unfinished task/round from boot
+            (cur_p_idx, cur_rep)
+        }
+    } else if p_rep_total == 0 || cur_rep < p_rep_total {
         (cur_p_idx, cur_rep + 1)
         (cur_p_idx, cur_rep + 1)
     } else {
     } else {
         (cur_p_idx + 1, 1)
         (cur_p_idx + 1, 1)
@@ -2991,18 +3204,30 @@ pub fn step_task_batch(
     let next_profile = &profiles[next_p_idx];
     let next_profile = &profiles[next_p_idx];
     let next_name = next_profile.get_str_or("name", &format!("Profile-{}", next_p_idx + 1));
     let next_name = next_profile.get_str_or("name", &format!("Profile-{}", next_p_idx + 1));
     let next_rep_total = next_profile.get_i64("repeat").unwrap_or(1).max(0) as usize;
     let next_rep_total = next_profile.get_i64("repeat").unwrap_or(1).max(0) as usize;
+    let saved_hang_cnt = st.consecutive_hang_count;
 
 
     let _ = apply_profile_to_station(st, next_profile, contract, pxe_state, data_dir, pxe_tftp_dir);
     let _ = apply_profile_to_station(st, next_profile, contract, pxe_state, data_dir, pxe_tftp_dir);
     st.single_run_active = false;
     st.single_run_active = false;
     st.task_batch
     st.task_batch
         .set("state", JsonVal::Str("running".to_string()));
         .set("state", JsonVal::Str("running".to_string()));
-    let _ = control_boot_plan_impl(st, "restart", data_dir, true);
-
+    let _ = control_boot_plan_impl(st, "restart", data_dir, !hang_will_recover);
+    if hang_will_recover {
+        st.consecutive_hang_count = saved_hang_cnt;
+    }
+
+    let next_run_id = if hang_will_recover {
+        format!(
+            "{}-P{}-R{}-retry{}",
+            batch_id,
+            next_p_idx + 1,
+            next_rep,
+            saved_hang_cnt
+        )
+    } else {
+        format!("{}-P{}-R{}", batch_id, next_p_idx + 1, next_rep)
+    };
     let mut next_run = JsonVal::obj();
     let mut next_run = JsonVal::obj();
-    next_run.set(
-        "run_id",
-        JsonVal::Str(format!("{}-P{}-R{}", batch_id, next_p_idx + 1, next_rep)),
-    );
+    next_run.set("run_id", JsonVal::Str(next_run_id));
     next_run.set("profile_index", JsonVal::Num(next_p_idx as f64));
     next_run.set("profile_index", JsonVal::Num(next_p_idx as f64));
     next_run.set("profile_name", JsonVal::Str(next_name.clone()));
     next_run.set("profile_name", JsonVal::Str(next_name.clone()));
     next_run.set("repeat_index", JsonVal::Num(next_rep as f64));
     next_run.set("repeat_index", JsonVal::Num(next_rep as f64));

+ 39 - 2
native/stl_accel/stl_accel.h

@@ -33,7 +33,6 @@ const char *stl_isa_tier_name(int tier);
 /* Assembly entry points (scan_asm.S) */
 /* Assembly entry points (scan_asm.S) */
 uint64_t asm_xgetbv_eax0(void);
 uint64_t asm_xgetbv_eax0(void);
 size_t   asm_base64_encode_sse2(const uint8_t *src, size_t len, uint8_t *dst);
 size_t   asm_base64_encode_sse2(const uint8_t *src, size_t len, uint8_t *dst);
-size_t   asm_base64_encode_avx2(const uint8_t *src, size_t len, uint8_t *dst);
 
 
 /* Multi-tier SIMD kernels (simd_kernels.c) */
 /* Multi-tier SIMD kernels (simd_kernels.c) */
 void    *stl_aligned_buf_alloc(size_t size, size_t *out_aligned_cap);
 void    *stl_aligned_buf_alloc(size_t size, size_t *out_aligned_cap);
@@ -53,6 +52,7 @@ size_t   simd_base64_encode_avx2(const uint8_t *src, size_t len, uint8_t *dst);
 
 
 uint32_t simd_crc32_ieee_slicing8(uint32_t init_crc, const uint8_t *buf, size_t len);
 uint32_t simd_crc32_ieee_slicing8(uint32_t init_crc, const uint8_t *buf, size_t len);
 uint32_t simd_crc32_ieee_pclmul(uint32_t init_crc, const uint8_t *buf, size_t len);
 uint32_t simd_crc32_ieee_pclmul(uint32_t init_crc, const uint8_t *buf, size_t len);
+uint32_t simd_crc32_ieee_vpclmul(uint32_t init_crc, const uint8_t *buf, size_t len);
 
 
 void     simd_sha1_sw(const uint8_t *data, size_t len, uint8_t out20[20]);
 void     simd_sha1_sw(const uint8_t *data, size_t len, uint8_t out20[20]);
 void     simd_sha1_shani(const uint8_t *data, size_t len, uint8_t out20[20]);
 void     simd_sha1_shani(const uint8_t *data, size_t len, uint8_t out20[20]);
@@ -358,12 +358,49 @@ 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, monotonic clock, SIMD diff & permission helpers */
+/* Filesystem free-space guard, idle priority, monotonic clock, SIMD diff, permission & UDP/NIC helpers */
 int      stl_free_disk_bytes(const char *path, uint64_t *out_avail_bytes);
 int      stl_free_disk_bytes(const char *path, uint64_t *out_avail_bytes);
 void     stl_set_thread_idle_priority(void);
 void     stl_set_thread_idle_priority(void);
 int      stl_chmod_0600(const char *path);
 int      stl_chmod_0600(const char *path);
 uint64_t stl_mono_us(void);
 uint64_t stl_mono_us(void);
 uint64_t stl_mem_diff_64b_mask(const uint8_t *a, const uint8_t *b, size_t len);
 uint64_t stl_mem_diff_64b_mask(const uint8_t *a, const uint8_t *b, size_t len);
+void     stl_batch_mem_diff_64b_masks(
+    const uint8_t *prev_base,
+    const uint8_t *cur_base,
+    size_t         stride,
+    size_t         item_len,
+    size_t         count,
+    uint64_t      *out_masks);
+
+typedef struct {
+    char     name[32];
+    uint32_t ip_be;
+    uint32_t mask_be;
+    uint32_t bcast_be;
+    uint32_t ifindex;
+    uint8_t  mac[6];
+    uint8_t  is_up;
+    uint8_t  is_loopback;
+} StlNetIface;
+
+int     c_list_ipv4_ifaces(StlNetIface *out_list, int max_count);
+int     c_udp_bind_dhcp_socket(const char *iface, int port, int reuse_port);
+ssize_t c_udp_recv_pktinfo(
+    int       fd,
+    uint8_t  *buf,
+    size_t    cap,
+    uint32_t *out_peer_ip_be,
+    uint16_t *out_peer_port,
+    uint32_t *out_local_ip_be,
+    uint32_t *out_ifindex);
+ssize_t c_udp_send_pktinfo(
+    int            fd,
+    const uint8_t *buf,
+    size_t         len,
+    uint32_t       dst_ip_be,
+    uint16_t       dst_port,
+    uint32_t       src_ip_be,
+    uint32_t       ifindex);
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }

+ 5 - 161
native/stl_accel/zig_kernels.zig

@@ -1,134 +1,10 @@
-// zig_kernels.zig — Pure x86-64 SSE2 SIMD Kernels (v0.8.1.19)
-// Compiled with: zig build-obj -OReleaseFast -target x86_64-linux-gnu -mcpu=x86_64 -fPIC
-// Safe on all Intel 2nd..8th Gen Core / Celeron / Pentium CPUs (no AVX/POPCNT required).
+// zig_kernels.zig — Pure x86-64 SSE2 SIMD Kernels
+// Compiled with: zig build-obj -O ReleaseFast -fPIC -mcpu=x86_64
+// Safe on all x86-64 CPUs (no AVX/POPCNT required).
 
 
 const std = @import("std");
 const std = @import("std");
 
 
-// 1. SIMD-accelerated terminal cleaner (SSE2 @Vector(16, u8) fallback)
-pub export fn zig_clean_terminal_fast(
-    src_ptr: [*]const u8,
-    src_len: usize,
-    dst_ptr: [*]u8,
-    first_ctrl_hint: usize,
-) callconv(.c) usize {
-    const src = src_ptr[0..src_len];
-    var out_len: usize = 0;
-    var i: usize = 0;
-    var last_cursor_row: usize = 0;
-
-    if (first_ctrl_hint > 0 and first_ctrl_hint <= src_len) {
-        @memcpy(dst_ptr[0..first_ctrl_hint], src[0..first_ctrl_hint]);
-        out_len = first_ctrl_hint;
-        i = first_ctrl_hint;
-    }
-
-    const Vec16 = @Vector(16, u8);
-    const v_nul: Vec16 = @splat(0x00);
-    const v_bs: Vec16 = @splat(0x08);
-    const v_esc: Vec16 = @splat(0x1B);
-
-    while (i < src_len) {
-        while (i + 16 <= src_len) {
-            const chunk: Vec16 = src_ptr[i..][0..16].*;
-            const m_esc = chunk == v_esc;
-            const m_bs = chunk == v_bs;
-            const m_nul = chunk == v_nul;
-            const m_any = @as(u16, @bitCast(m_esc)) | @as(u16, @bitCast(m_bs)) | @as(u16, @bitCast(m_nul));
-            if (m_any != 0) {
-                const adv: usize = @ctz(m_any);
-                if (adv > 0) {
-                    @memcpy(dst_ptr[out_len .. out_len + adv], src[i .. i + adv]);
-                    out_len += adv;
-                    i += adv;
-                }
-                break;
-            }
-            dst_ptr[out_len..][0..16].* = chunk;
-            out_len += 16;
-            i += 16;
-        }
-        if (i >= src_len) break;
-
-        const b = src[i];
-        if (b == 0x00) {
-            i += 1;
-            continue;
-        }
-        if (b == 0x1B) {
-            if (i + 1 < src_len and src[i + 1] == '[') {
-                var j = i + 2;
-                var row: usize = 0;
-                var col: usize = 0;
-                var seen_semi = false;
-                while (j < src_len) : (j += 1) {
-                    const c = src[j];
-                    if (c >= '0' and c <= '9') {
-                        if (!seen_semi) {
-                            row = row * 10 + (c - '0');
-                        } else {
-                            col = col * 10 + (c - '0');
-                        }
-                    } else if (c == ';') {
-                        seen_semi = true;
-                    } else if (c >= 0x40 and c <= 0x7E) {
-                        if (c == 'H' or c == 'f') {
-                            const r = if (row == 0) 1 else row;
-                            if (last_cursor_row != 0 and r != last_cursor_row) {
-                                if (out_len > 0 and dst_ptr[out_len - 1] != '\n') {
-                                    dst_ptr[out_len] = '\n';
-                                    out_len += 1;
-                                }
-                            } else if (col > 1 and out_len > 0 and dst_ptr[out_len - 1] != ' ' and dst_ptr[out_len - 1] != '\n') {
-                                dst_ptr[out_len] = ' ';
-                                out_len += 1;
-                            }
-                            last_cursor_row = r;
-                        } else if (c == 'C') {
-                            dst_ptr[out_len] = ' ';
-                            out_len += 1;
-                        }
-                        j += 1;
-                        break;
-                    }
-                }
-                i = j;
-                continue;
-            } else if (i + 1 < src_len and src[i + 1] == ']') {
-                var j = i + 2;
-                while (j < src_len) : (j += 1) {
-                    if (src[j] == 0x07) {
-                        j += 1;
-                        break;
-                    }
-                    if (src[j] == 0x1B and j + 1 < src_len and src[j + 1] == '\\') {
-                        j += 2;
-                        break;
-                    }
-                }
-                i = j;
-                continue;
-            }
-            i += 1;
-            continue;
-        }
-        if (b == 0x08) {
-            if (out_len > 0) {
-                out_len -= 1;
-                while (out_len > 0 and (dst_ptr[out_len] & 0xC0) == 0x80) {
-                    out_len -= 1;
-                }
-            }
-            i += 1;
-            continue;
-        }
-        dst_ptr[out_len] = b;
-        out_len += 1;
-        i += 1;
-    }
-    return out_len;
-}
-
-// 2. RFC 6455 Sec-WebSocket-Accept computation (SHA-1 + Base64)
+// 1. RFC 6455 Sec-WebSocket-Accept fallback & RFC 4648 Base64 decoder
 pub export fn zig_ws_accept_key(
 pub export fn zig_ws_accept_key(
     key_ptr: [*]const u8,
     key_ptr: [*]const u8,
     key_len: usize,
     key_len: usize,
@@ -144,18 +20,6 @@ pub export fn zig_ws_accept_key(
     return encoded.len;
     return encoded.len;
 }
 }
 
 
-pub export fn zig_base64_encode(
-    src_ptr: [*]const u8,
-    src_len: usize,
-    dst_ptr: [*]u8,
-    dst_cap: usize,
-) callconv(.c) usize {
-    const enc_len = std.base64.standard.Encoder.calcSize(src_len);
-    if (enc_len > dst_cap) return 0;
-    const res = std.base64.standard.Encoder.encode(dst_ptr[0..enc_len], src_ptr[0..src_len]);
-    return res.len;
-}
-
 pub export fn zig_base64_decode(
 pub export fn zig_base64_decode(
     src_ptr: [*]const u8,
     src_ptr: [*]const u8,
     src_len: usize,
     src_len: usize,
@@ -168,27 +32,7 @@ pub export fn zig_base64_decode(
     return max_len;
     return max_len;
 }
 }
 
 
-// 3. CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF) for CPLD 6400/MRDIMM local thermal hood UART
-pub export fn zig_crc16_ccitt_false(
-    data_ptr: [*]const u8,
-    len: usize,
-) callconv(.c) u16 {
-    var crc: u16 = 0xFFFF;
-    for (data_ptr[0..len]) |b| {
-        crc ^= @as(u16, b) << 8;
-        var bit: u4 = 0;
-        while (bit < 8) : (bit += 1) {
-            if ((crc & 0x8000) != 0) {
-                crc = (crc << 1) ^ 0x1021;
-            } else {
-                crc <<= 1;
-            }
-        }
-    }
-    return crc;
-}
-
-// 4. SSE2 SIMD Historical Log Rescan CPU Fallback
+// 2. SSE2 SIMD Historical Log Rescan CPU Fallback
 pub export fn zig_batch_rescan_logs_cpu(
 pub export fn zig_batch_rescan_logs_cpu(
     buf_ptr: [*]const u8,
     buf_ptr: [*]const u8,
     len: usize,
     len: usize,

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 16 - 13
sim/README.md


+ 444 - 0
sim/bench_scale_performance.py

@@ -0,0 +1,444 @@
+#!/usr/bin/env python3
+"""
+bench_scale_performance.py — Tier 5: 6-Tier CPU ISA Kernel Micro-Benchmark + Live 200-Station Scale Test
+
+Measures real hardware throughput of unmodified `build/native/libstl_kernels.a` and
+`build/native/stl_native_server` under 200 concurrent live TCP serial stations:
+  Part A: All supported CPU ISA tiers (SSE2 -> SSSE3 -> SSE4.2+PCLMUL -> SHA-NI -> AVX2+BMI2 -> AVX-512)
+          for Base64, Hex, IEEE CRC-32, 64B batch SIMD state-diff, ASM serial cleaner, and 200-station RMT eye.
+  Part B: Live 200-station `stl_native_server` over 200 real simultaneous TCP serial streams with full detail trace
+          enabled — measuring OS thread count, VmRSS, sustained aggregate MB/s, lines/s, and WS RPC latency.
+"""
+
+import asyncio
+import contextlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from typing import Any, Dict, List, Optional
+
+import aiohttp
+
+ROOT_DIR = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster"))
+from cluster_harness import CONTRACTS_PATH, STL_SERVER_BIN, WEB_DIR, WsRpcClient  # noqa: E402
+
+ISA_BENCH_C = r"""
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include "native/stl_accel/stl_accel.h"
+
+static double now_sec(void) {
+    return (double)stl_mono_us() / 1e6;
+}
+
+int main(void) {
+    int detected_tier = stl_cpu_tier_detect();
+    StlOpenClInfo ocl;
+    memset(&ocl, 0, sizeof(ocl));
+    stl_opencl_query_info(&ocl);
+    long nprocs = sysconf(_SC_NPROCESSORS_ONLN);
+
+    const size_t PAYLOAD_SZ = 1024 * 1024; /* 1 MiB */
+    uint8_t *src = (uint8_t *)malloc(PAYLOAD_SZ);
+    uint8_t *dst = (uint8_t *)malloc(PAYLOAD_SZ * 2 + 64);
+    uint32_t x = 0x13579BDFu;
+    for (size_t i = 0; i < PAYLOAD_SZ; i++) {
+        x = x * 1664525u + 1013904223u;
+        src[i] = (uint8_t)(x >> 24);
+    }
+
+    /* Realistic 1 MiB BIOS/Training/RMT/ANSI/MT86 serial payload */
+    const char *sample_lines[] = {
+        "[HS_BIOS][Training][ScktId: 0][42]Read Vref Training -- SUCCEEDED,Time=128 ms\r\n",
+        "\x1b[12;1HRunning test #7 [Moving inversions, 32 bit pattern] (Test: 7/26 26%)  Errors: 0\r\n",
+        "N0.C3.D0.R0   -18   19   -16   17   -14   15   -12   13   34500 mV\r\n",
+        "[0][Hovsee]Current stage is 1  [HS_DRAM] N0.C0.D0 DDR5 Present Size:65536\r\n",
+    };
+    uint8_t *ser_buf = (uint8_t *)malloc(PAYLOAD_SZ);
+    size_t spos = 0;
+    int lidx = 0;
+    while (spos < PAYLOAD_SZ) {
+        const char *ln = sample_lines[lidx++ & 3];
+        size_t ll = strlen(ln);
+        size_t cp = (spos + ll <= PAYLOAD_SZ) ? ll : (PAYLOAD_SZ - spos);
+        memcpy(ser_buf + spos, ln, cp);
+        spos += cp;
+    }
+
+    /* 200-station x 320B snapshot diff buffers */
+    const size_t N_ST = 200;
+    const size_t STRIDE = 320;
+    uint8_t *prev_st = (uint8_t *)calloc(N_ST, STRIDE);
+    uint8_t *cur_st  = (uint8_t *)calloc(N_ST, STRIDE);
+    for (size_t i = 0; i < N_ST; i += 5) cur_st[i * STRIDE + 128] = 0x5A;
+    uint64_t masks[200];
+
+    /* 200-station RMT eye reduction buffers */
+    float *margins = (float *)malloc(N_ST * 24 * 4 * sizeof(float));
+    float *eye_out = (float *)malloc(N_ST * 24 * 256 * sizeof(float));
+    float *sum_out = (float *)malloc(N_ST * 4 * sizeof(float));
+    for (size_t i = 0; i < N_ST * 24 * 4; i++) margins[i] = 14.0f;
+
+    printf("{\"detected_tier\":%d,\"detected_tier_name\":\"%s\",\"online_cpus\":%ld,\"opencl_available\":%d,\"opencl_device\":\"%s\",\"tiers\":[",
+           detected_tier, stl_isa_tier_name(detected_tier), nprocs, ocl.available, ocl.device_name);
+
+    int first = 1;
+    for (int t = 0; t <= detected_tier; t++) {
+        stl_force_isa_tier(t);
+        if (!first) printf(",");
+        first = 0;
+
+        /* 1. Base64 */
+        double t0 = now_sec();
+        volatile size_t sink = 0;
+        for (int it = 0; it < 48; it++) sink += stl_base64_encode(src, PAYLOAD_SZ, dst);
+        double b64_mbps = (48.0 * 1.0) / (now_sec() - t0);
+
+        /* 2. Hex */
+        t0 = now_sec();
+        for (int it = 0; it < 48; it++) sink += stl_hex_encode(src, PAYLOAD_SZ, dst);
+        double hex_mbps = (48.0 * 1.0) / (now_sec() - t0);
+
+        /* 3. CRC32 IEEE */
+        t0 = now_sec();
+        volatile uint32_t crc_sink = 0;
+        for (int it = 0; it < 96; it++) crc_sink ^= stl_crc32_ieee(0, src, PAYLOAD_SZ);
+        double crc_mbps = (96.0 * 1.0) / (now_sec() - t0);
+
+        /* 4. 200-station batch 64B diff */
+        t0 = now_sec();
+        for (int it = 0; it < 50000; it++) {
+            stl_batch_mem_diff_64b_masks(prev_st, cur_st, STRIDE, STRIDE, N_ST, masks);
+        }
+        double diff_dt = now_sec() - t0;
+        double diff_mstations_s = ((double)50000 * (double)N_ST / 1e6) / diff_dt;
+
+        /* 5. ASM single-pass serial cleaner */
+        StlCleanStreamState cst;
+        stl_clean_stream_init(&cst);
+        uint8_t *out_clean = (uint8_t *)malloc(PAYLOAD_SZ * 2);
+        StlCleanLineSpan *spans = (StlCleanLineSpan *)malloc(32768 * sizeof(StlCleanLineSpan));
+        size_t total_lines = 0;
+        t0 = now_sec();
+        for (int it = 0; it < 32; it++) {
+            StlCleanOutput co;
+            memset(&co, 0, sizeof(co));
+            co.clean_buf = out_clean;
+            co.clean_cap = PAYLOAD_SZ * 2;
+            co.spans     = spans;
+            co.spans_cap = 32768;
+            stl_clean_split_classify(&cst, ser_buf, PAYLOAD_SZ, &co);
+            total_lines += co.spans_count;
+        }
+        double clean_dt = now_sec() - t0;
+        double clean_mbps = 32.0 / clean_dt;
+        double clean_mlines_s = ((double)total_lines / 1e6) / clean_dt;
+        free(out_clean);
+        free(spans);
+
+        /* 6. 200-station RMT eye reduction */
+        int used_gpu = 0;
+        t0 = now_sec();
+        for (int it = 0; it < 10; it++) {
+            stl_batch_rmt_eye_reduce(margins, N_ST, eye_out, sum_out, &used_gpu);
+        }
+        double rmt_ms = ((now_sec() - t0) / 10.0) * 1000.0;
+
+        printf("{\"tier\":%d,\"tier_name\":\"%s\",\"b64_mbps\":%.1f,\"hex_mbps\":%.1f,\"crc32_mbps\":%.1f,"
+               "\"diff200_mstations_s\":%.2f,\"clean_mbps\":%.1f,\"clean_mlines_s\":%.2f,"
+               "\"rmt200_ms\":%.2f,\"rmt_used_gpu\":%d}",
+               t, stl_isa_tier_name(t), b64_mbps, hex_mbps, crc_mbps, diff_mstations_s, clean_mbps, clean_mlines_s, rmt_ms, used_gpu);
+        (void)sink; (void)crc_sink;
+    }
+    stl_force_isa_tier(-1);
+    printf("]}\n");
+
+    free(src); free(dst); free(ser_buf);
+    free(prev_st); free(cur_st);
+    free(margins); free(eye_out); free(sum_out);
+    return 0;
+}
+"""
+
+
+def clean_env() -> Dict[str, str]:
+    env = dict(os.environ)
+    for k in (
+        "LD_LIBRARY_PATH",
+        "http_proxy",
+        "https_proxy",
+        "HTTP_PROXY",
+        "HTTPS_PROXY",
+        "all_proxy",
+        "ALL_PROXY",
+    ):
+        env.pop(k, None)
+    return env
+
+
+def run_part_a_isa_bench() -> Dict[str, Any]:
+    print("[Tier5][Part A] Running 6-tier CPU ISA kernel throughput benchmark...", flush=True)
+    tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_isa_bench_"))
+    try:
+        c_file = tmp_dir / "isa_bench.c"
+        bin_file = tmp_dir / "isa_bench"
+        c_file.write_text(ISA_BENCH_C, encoding="utf-8")
+        subprocess.run(
+            [
+                "gcc",
+                "-O2",
+                f"-I{ROOT_DIR}",
+                str(c_file),
+                f"-L{ROOT_DIR / 'build' / 'native'}",
+                "-lstl_kernels",
+                "-lfreeipmi",
+                "-lipmiconsole",
+                "-lssh",
+                "-lutil",
+                "-ldl",
+                "-lpthread",
+                "-lm",
+                "-o",
+                str(bin_file),
+            ],
+            check=True,
+            cwd=str(ROOT_DIR),
+            env=clean_env(),
+            capture_output=True,
+            text=True,
+        )
+        out = subprocess.run(
+            [str(bin_file)],
+            check=True,
+            cwd=str(ROOT_DIR),
+            env=clean_env(),
+            capture_output=True,
+            text=True,
+            timeout=60,
+        )
+        data = json.loads(out.stdout.strip())
+        for row in data.get("tiers", []):
+            print(
+                f"   Tier {row['tier']}: B64={row['b64_mbps']} MB/s | Hex={row['hex_mbps']} MB/s | "
+                f"CRC32={row['crc32_mbps']} MB/s | Clean={row['clean_mbps']} MB/s ({row['clean_mlines_s']}M ln/s) | "
+                f"Diff200={row['diff200_mstations_s']}M st/s | RMT200={row['rmt200_ms']} ms",
+                flush=True,
+            )
+        return data
+    finally:
+        shutil.rmtree(tmp_dir, ignore_errors=True)
+
+
+def read_proc_metrics(pid: int) -> Dict[str, Any]:
+    threads = 0
+    rss_kb = 0
+    try:
+        for line in Path(f"/proc/{pid}/status").read_text(encoding="utf-8").splitlines():
+            if line.startswith("Threads:"):
+                threads = int(line.split()[1])
+            elif line.startswith("VmRSS:"):
+                rss_kb = int(line.split()[1])
+    except Exception:
+        pass
+    cpu_ticks = 0
+    try:
+        parts = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split()
+        cpu_ticks = int(parts[11]) + int(parts[12])  # utime + stime
+    except Exception:
+        pass
+    return {"threads": threads, "rss_mb": round(rss_kb / 1024.0, 2), "cpu_ticks": cpu_ticks}
+
+
+async def run_part_b_200_stations(num_stations: int = 200, duration_s: float = 4.0) -> Dict[str, Any]:
+    print(f"[Tier5][Part B] Running live {num_stations}-station concurrent TCP serial scale benchmark ({duration_s}s)...", flush=True)
+    tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_scale200_"))
+    data_dir = tmp_dir / "data"
+    data_dir.mkdir(parents=True, exist_ok=True)
+    web_port = 19885
+    tcp_port = 19886
+
+    # Build synthetic realistic BIOS/RMT/MT86 burst payload (~8 KiB per burst)
+    burst_unit = (
+        b"[HS_BIOS]Version:108_VD012\r\n"
+        b"[HS_BIOS][Training][ScktId: 0][42]Read Vref Training -- SUCCEEDED,Time=120 ms\r\n"
+        b"N0.C0.D0.R0  -16  18  -14  16  -12  14  -11  12\r\n"
+        b"\x1b[10;1HRunning test #7 (Test: 7/26 26%) Errors: 0\r\n"
+    )
+    burst_payload = burst_unit * 32  # ~6.8 KiB, 128 lines per burst
+    lines_per_burst = 4 * 32
+
+    connected_writers: List[asyncio.StreamWriter] = []
+    conn_event = asyncio.Event()
+    stop_stream = asyncio.Event()
+    sent_bytes = 0
+    sent_lines = 0
+
+    async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+        nonlocal sent_bytes, sent_lines
+        connected_writers.append(writer)
+        if len(connected_writers) >= num_stations:
+            conn_event.set()
+        try:
+            # Wait until streaming starts, then pump bursts continuously until stop_stream
+            await conn_event.wait()
+            while not stop_stream.is_set():
+                writer.write(burst_payload)
+                await writer.drain()
+                sent_bytes += len(burst_payload)
+                sent_lines += lines_per_burst
+                await asyncio.sleep(0.025)  # ~270 KB/s per station -> ~54 MB/s across 200 stations
+        except Exception:
+            pass
+        finally:
+            with contextlib.suppress(Exception):
+                writer.close()
+
+    tcp_server = await asyncio.start_server(handle_client, "127.0.0.1", tcp_port, backlog=512)
+    server_proc: Optional[subprocess.Popen] = None
+
+    try:
+        stations_cfg = []
+        for i in range(1, num_stations + 1):
+            sid = f"S{i:03d}"
+            stations_cfg.append({
+                "station_id": sid,
+                "frontend_index": i - 1,
+                "name": f"压测工位 {i:03d}",
+                "mode": "hardware",
+                "cpu_count": 2,
+                "channels_per_cpu": 12,
+                "bmc": {"enabled": False, "host": ""},
+                "console": {
+                    "enabled": True,
+                    "transport": "tcp_serial",
+                    "host": "127.0.0.1",
+                    "port": tcp_port,
+                },
+            })
+        cfg_path = tmp_dir / "scale200.json"
+        cfg_path.write_text(json.dumps({"mode": "hardware", "data_dir": str(data_dir), "stations": stations_cfg}), encoding="utf-8")
+
+        server_proc = subprocess.Popen(
+            [
+                str(STL_SERVER_BIN),
+                "--config", str(cfg_path),
+                "--data-dir", str(data_dir),
+                "--web-listen", f"127.0.0.1:{web_port}",
+                "--tftp-listen", "disabled",
+                "--pxe-mode", "disabled",
+                "--batch-window-ms", "100",
+                "--detail-log", "on",
+                "--web-dir", str(WEB_DIR),
+                "--contracts", str(CONTRACTS_PATH),
+                "--web-password", "disabled",
+            ],
+            cwd=str(ROOT_DIR),
+            stdout=subprocess.DEVNULL,
+            stderr=subprocess.PIPE,
+            text=True,
+            env=clean_env(),
+        )
+
+        # Wait for all 200 TCP serial connections to establish!
+        await asyncio.wait_for(conn_event.wait(), timeout=20.0)
+        clk_tck = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
+        m0 = read_proc_metrics(server_proc.pid)
+        t_stream0 = time.monotonic()
+
+        # While all 200 streams blast data simultaneously, also measure live WebSocket ListStations RPC latency!
+        rpc_latencies_ms: List[float] = []
+        async with aiohttp.ClientSession() as http:
+            ws = WsRpcClient(http, f"ws://127.0.0.1:{web_port}/ws")
+            await ws.connect()
+            try:
+                while time.monotonic() - t_stream0 < duration_s:
+                    tr0 = time.monotonic()
+                    lst = await ws.call("ListStations", {}, timeout=10.0)
+                    rpc_latencies_ms.append(round((time.monotonic() - tr0) * 1000.0, 2))
+                    assert len(lst.get("stations") or []) == num_stations
+                    await asyncio.sleep(0.5)
+                stop_stream.set()
+                await asyncio.sleep(0.25)
+                m1 = read_proc_metrics(server_proc.pid)
+                hw_info = await ws.call("GetHardwareInfo", {})
+                trace_st = await ws.call("GetTraceStatus", {})
+            finally:
+                await ws.close()
+
+        elapsed = max(0.01, time.monotonic() - t_stream0)
+        cpu_sec = (m1["cpu_ticks"] - m0["cpu_ticks"]) / float(clk_tck)
+        cpu_pct = round((cpu_sec / elapsed) * 100.0, 1)
+        mb_sent = sent_bytes / (1024.0 * 1024.0)
+        mb_per_s = round(mb_sent / elapsed, 2)
+        lines_per_s = int(sent_lines / elapsed)
+        avg_rpc_ms = round(sum(rpc_latencies_ms) / max(1, len(rpc_latencies_ms)), 2)
+
+        assert m1["threads"] <= 32, f"Thread explosion! Expected <= 32 OS threads for 200 stations, got {m1['threads']}"
+        assert mb_per_s >= 10.0, f"Throughput too low: {mb_per_s} MB/s"
+
+        res = {
+            "num_stations": num_stations,
+            "connected_streams": len(connected_writers),
+            "duration_s": round(elapsed, 2),
+            "os_threads": m1["threads"],
+            "vm_rss_mb": m1["rss_mb"],
+            "cpu_percent_total": cpu_pct,
+            "total_mb_ingested": round(mb_sent, 2),
+            "sustained_mb_per_sec": mb_per_s,
+            "sustained_lines_per_sec": lines_per_s,
+            "list200_rpc_avg_ms": avg_rpc_ms,
+            "trace_serial_mb_written": round(float(trace_st.get("serial_bytes_written", 0)) / (1024.0 * 1024.0), 2),
+            "isa_tier_name": hw_info.get("tier_name"),
+            "ok": True,
+        }
+        print(
+            f"   200 Stations LIVE: Threads={res['os_threads']} | RSS={res['vm_rss_mb']} MiB | "
+            f"CPU={res['cpu_percent_total']}% | Throughput={res['sustained_mb_per_sec']} MB/s "
+            f"({res['sustained_lines_per_sec']} lines/s) | ListStations(200)={res['list200_rpc_avg_ms']} ms | "
+            f"TraceRawDisk={res['trace_serial_mb_written']} MiB",
+            flush=True,
+        )
+        return res
+    finally:
+        stop_stream.set()
+        tcp_server.close()
+        with contextlib.suppress(Exception):
+            await tcp_server.wait_closed()
+        if server_proc is not None and server_proc.poll() is None:
+            with contextlib.suppress(Exception):
+                server_proc.terminate()
+                server_proc.wait(timeout=3.0)
+            if server_proc.poll() is None:
+                with contextlib.suppress(Exception):
+                    server_proc.kill()
+        shutil.rmtree(tmp_dir, ignore_errors=True)
+
+
+def main() -> None:
+    t0 = time.monotonic()
+    part_a = run_part_a_isa_bench()
+    part_b = asyncio.run(run_part_b_200_stations(num_stations=200, duration_s=4.0))
+    report = {
+        "tier": "Tier5_6Tier_ISA_And_200Station_Scale_Benchmark",
+        "ok": True,
+        "elapsed_s": round(time.monotonic() - t0, 2),
+        "isa_kernels": part_a,
+        "live_200_stations": part_b,
+    }
+    out_file = ROOT_DIR / "build" / "sim" / "tier5_scale_bench_report.json"
+    out_file.parent.mkdir(parents=True, exist_ok=True)
+    out_file.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+    print(f"\n[Tier5] 6-TIER ISA & 200-STATION SCALE BENCHMARK PASSED in {report['elapsed_s']}s! Report: {out_file}", flush=True)
+
+
+if __name__ == "__main__":
+    main()

+ 134 - 9
sim/hil_cluster/bmc_ssh_hil_sim.c

@@ -40,6 +40,8 @@
 #define MAX_STATIONS 8
 #define MAX_STATIONS 8
 #define MAX_RMCP_SESSIONS 32
 #define MAX_RMCP_SESSIONS 32
 #define NUM_DIMMS 24
 #define NUM_DIMMS 24
+#define NUM_EXTRA_SENSORS 6
+#define NUM_SDR_RECORDS (NUM_DIMMS + NUM_EXTRA_SENSORS)
 
 
 typedef struct {
 typedef struct {
     int      in_use;
     int      in_use;
@@ -88,8 +90,8 @@ typedef struct {
     int             dimm_present[NUM_DIMMS];
     int             dimm_present[NUM_DIMMS];
     int             dimm_temp_c[NUM_DIMMS];
     int             dimm_temp_c[NUM_DIMMS];
 
 
-    uint8_t         sdr_records[NUM_DIMMS][64];
-    unsigned int    sdr_record_lens[NUM_DIMMS];
+    uint8_t         sdr_records[NUM_SDR_RECORDS][64];
+    unsigned int    sdr_record_lens[NUM_SDR_RECORDS];
 
 
     pthread_mutex_t mu;
     pthread_mutex_t mu;
     RmcpSimSession  sessions[MAX_RMCP_SESSIONS];
     RmcpSimSession  sessions[MAX_RMCP_SESSIONS];
@@ -212,6 +214,115 @@ static void build_station_sdr_repository(SimStation *st) {
         st->sdr_record_lens[i] = (len > 0) ? (unsigned int)len : 0;
         st->sdr_record_lens[i] = (len > 0) ? (unsigned int)len : 0;
         fiid_obj_destroy(obj);
         fiid_obj_destroy(obj);
     }
     }
+
+    /* Extra system sensors (Voltage, Fan, Power, Current) for full BMC telemetry verification */
+    struct {
+        const char *name;
+        uint8_t     snum;
+        uint8_t     stype;
+        uint8_t     base_unit;
+        uint16_t    m;
+        int8_t      r_exp;
+        uint8_t     nominal;
+    } extras[NUM_EXTRA_SENSORS] = {
+        { "P12V",        0x30, 0x02, 4,  10,  -2, 120 }, /* 12.00 V */
+        { "VDDQ_CPU0",   0x31, 0x02, 4,  10,  -3, 110 }, /* 1.10 V */
+        { "FAN1_RPM",    0x32, 0x04, 18, 100,  0,  54 }, /* 5400 RPM */
+        { "FAN2_RPM",    0x33, 0x04, 18, 100,  0,  52 }, /* 5200 RPM */
+        { "PSU1_PIN_W",  0x34, 0x03, 6,  4,    0,  80 }, /* 320 W */
+        { "PSU1_IIN_A",  0x35, 0x03, 5,  10,  -2, 145 }, /* 14.50 A */
+    };
+    for (int e = 0; e < NUM_EXTRA_SENSORS; e++) {
+        int rec_idx = NUM_DIMMS + e;
+        size_t nlen = strlen(extras[e].name);
+        if (nlen > 16) nlen = 16;
+        fiid_obj_t obj = fiid_obj_create(tmpl_sdr_full_sensor_record);
+        fiid_obj_clear(obj);
+        fiid_obj_set(obj, "record_id", (uint64_t)(rec_idx + 1));
+        fiid_obj_set(obj, "sdr_version_major", 1);
+        fiid_obj_set(obj, "sdr_version_minor", 5);
+        fiid_obj_set(obj, "record_type", IPMI_SDR_FORMAT_FULL_SENSOR_RECORD);
+        fiid_obj_set(obj, "record_length", (uint64_t)(43 + nlen));
+        fiid_obj_set(obj, "sensor_owner_id.type", 0);
+        fiid_obj_set(obj, "sensor_owner_id", 0x10);
+        fiid_obj_set(obj, "sensor_owner_lun", 0);
+        fiid_obj_set(obj, "sensor_owner_lun.reserved", 0);
+        fiid_obj_set(obj, "channel_number", 0);
+        fiid_obj_set(obj, "sensor_number", (uint64_t)extras[e].snum);
+        fiid_obj_set(obj, "entity_id", 7); /* System Board */
+        fiid_obj_set(obj, "entity_instance", (uint64_t)(e + 1));
+        fiid_obj_set(obj, "entity_instance.type", 0);
+        fiid_obj_set(obj, "sensor_initialization.sensor_scanning", 1);
+        fiid_obj_set(obj, "sensor_initialization.event_generation", 0);
+        fiid_obj_set(obj, "sensor_initialization.init_sensor_type", 1);
+        fiid_obj_set(obj, "sensor_initialization.init_hysteresis", 0);
+        fiid_obj_set(obj, "sensor_initialization.init_thresholds", 1);
+        fiid_obj_set(obj, "sensor_initialization.init_events", 0);
+        fiid_obj_set(obj, "sensor_initialization.init_scanning", 1);
+        fiid_obj_set(obj, "sensor_initialization.settable_sensor", 0);
+
+        fiid_obj_set(obj, "sensor_capabilities.event_message_control_support", 3);
+        fiid_obj_set(obj, "sensor_capabilities.threshold_access_support", 1);
+        fiid_obj_set(obj, "sensor_capabilities.hysteresis_support", 0);
+        fiid_obj_set(obj, "sensor_capabilities.auto_re_arm_support", 1);
+        fiid_obj_set(obj, "sensor_capabilities.entity_ignore_support", 0);
+
+        fiid_obj_set(obj, "sensor_type", extras[e].stype);
+        fiid_obj_set(obj, "event_reading_type_code", 0x01);
+
+        fiid_obj_set(obj, "assertion_event_lower_threshold_reading_mask", 0);
+        fiid_obj_set(obj, "deassertion_event_upper_threshold_reading_mask", 0);
+        fiid_obj_set(obj, "discrete_reading_settable_threshold_readable_threshold_mask", 0);
+
+        fiid_obj_set(obj, "sensor_unit1.percentage", 0);
+        fiid_obj_set(obj, "sensor_unit1.modifier_unit", 0);
+        fiid_obj_set(obj, "sensor_unit1.rate_unit", 0);
+        fiid_obj_set(obj, "sensor_unit1.analog_data_format", 0);
+        fiid_obj_set(obj, "sensor_unit2.base_unit", extras[e].base_unit);
+        fiid_obj_set(obj, "sensor_unit3.modifier_unit", 0);
+
+        fiid_obj_set(obj, "linearization", 0);
+        fiid_obj_set(obj, "linearization.reserved", 0);
+        fiid_obj_set(obj, "m_ls", extras[e].m & 0xFF);
+        fiid_obj_set(obj, "tolerance", 0);
+        fiid_obj_set(obj, "m_ms", (extras[e].m >> 8) & 0x03);
+        fiid_obj_set(obj, "b_ls", 0);
+        fiid_obj_set(obj, "accuracy_ls", 0);
+        fiid_obj_set(obj, "b_ms", 0);
+        fiid_obj_set(obj, "sensor_direction", 0);
+        fiid_obj_set(obj, "accuracy_exp", 0);
+        fiid_obj_set(obj, "accuracy_ms", 0);
+        fiid_obj_set(obj, "b_exponent", 0);
+        fiid_obj_set(obj, "r_exponent", (uint64_t)(extras[e].r_exp & 0x0F));
+
+        fiid_obj_set(obj, "analog_characteristics_flag.nominal_reading", 1);
+        fiid_obj_set(obj, "analog_characteristics_flag.normal_max", 1);
+        fiid_obj_set(obj, "analog_characteristics_flag.normal_min", 1);
+        fiid_obj_set(obj, "analog_characteristics_flag.reserved", 0);
+
+        fiid_obj_set(obj, "nominal_reading", extras[e].nominal);
+        fiid_obj_set(obj, "normal_maximum", 240);
+        fiid_obj_set(obj, "normal_minimum", 10);
+        fiid_obj_set(obj, "sensor_maximum_reading", 255);
+        fiid_obj_set(obj, "sensor_minimum_reading", 0);
+
+        fiid_obj_set(obj, "upper_non_recoverable_threshold", 250);
+        fiid_obj_set(obj, "upper_critical_threshold", 245);
+        fiid_obj_set(obj, "upper_non_critical_threshold", 240);
+        fiid_obj_set(obj, "lower_non_recoverable_threshold", 0);
+        fiid_obj_set(obj, "lower_critical_threshold", 0);
+        fiid_obj_set(obj, "lower_non_critical_threshold", 5);
+        fiid_obj_set(obj, "positive_going_threshold_hysteresis", 1);
+        fiid_obj_set(obj, "negative_going_threshold_hysteresis", 1);
+        fiid_obj_set(obj, "reserved", 0);
+        fiid_obj_set(obj, "oem", 0);
+
+        fiid_obj_set(obj, "id_string_type_length_code", (uint64_t)(0xC0 | nlen));
+        fiid_obj_set_data(obj, "id_string", extras[e].name, (unsigned int)nlen);
+        int len = fiid_obj_get_all(obj, st->sdr_records[rec_idx], sizeof(st->sdr_records[rec_idx]));
+        st->sdr_record_lens[rec_idx] = (len > 0) ? (unsigned int)len : 0;
+        fiid_obj_destroy(obj);
+    }
 }
 }
 
 
 static void notify_uart_power_event(SimStation *st, const char *ev_name) {
 static void notify_uart_power_event(SimStation *st, const char *ev_name) {
@@ -353,12 +464,12 @@ static size_t handle_ipmb_command(
         /* Get SDR Repository Info */
         /* Get SDR Repository Info */
         rs_data[0] = 0x00;
         rs_data[0] = 0x00;
         rs_data[1] = 0x51; /* SDR version 1.5 */
         rs_data[1] = 0x51; /* SDR version 1.5 */
-        rs_data[2] = NUM_DIMMS & 0xFF;
-        rs_data[3] = (NUM_DIMMS >> 8) & 0xFF;
+        rs_data[2] = NUM_SDR_RECORDS & 0xFF;
+        rs_data[3] = (NUM_SDR_RECORDS >> 8) & 0xFF;
         rs_data[4] = 0x00; rs_data[5] = 0x10; /* Free space */
         rs_data[4] = 0x00; rs_data[5] = 0x10; /* Free space */
         /* Fixed timestamps so SDR cache stays valid */
         /* Fixed timestamps so SDR cache stays valid */
-        rs_data[6] = 0x01; rs_data[7] = 0x00; rs_data[8] = 0x00; rs_data[9] = 0x67;
-        rs_data[10] = 0x01; rs_data[11] = 0x00; rs_data[12] = 0x00; rs_data[13] = 0x67;
+        rs_data[6] = 0x02; rs_data[7] = 0x00; rs_data[8] = 0x00; rs_data[9] = 0x68;
+        rs_data[10] = 0x02; rs_data[11] = 0x00; rs_data[12] = 0x00; rs_data[13] = 0x68;
         rs_data[14] = 0x02; /* Reserve SDR supported */
         rs_data[14] = 0x02; /* Reserve SDR supported */
         return 15;
         return 15;
     }
     }
@@ -379,7 +490,7 @@ static size_t handle_ipmb_command(
         uint8_t offset = req_data[4];
         uint8_t offset = req_data[4];
         uint8_t to_read = req_data[5];
         uint8_t to_read = req_data[5];
         int idx = (rec_id == 0x0000) ? 0 : ((int)rec_id - 1);
         int idx = (rec_id == 0x0000) ? 0 : ((int)rec_id - 1);
-        if (idx < 0 || idx >= NUM_DIMMS) {
+        if (idx < 0 || idx >= NUM_SDR_RECORDS) {
             rs_data[0] = 0xCB; /* Requested sensor/record not present */
             rs_data[0] = 0xCB; /* Requested sensor/record not present */
             return 1;
             return 1;
         }
         }
@@ -390,7 +501,7 @@ static size_t handle_ipmb_command(
         }
         }
         unsigned int avail = rlen - offset;
         unsigned int avail = rlen - offset;
         unsigned int copy_n = (to_read == 0xFF || to_read > avail) ? avail : to_read;
         unsigned int copy_n = (to_read == 0xFF || to_read > avail) ? avail : to_read;
-        uint16_t next_id = (idx + 1 < NUM_DIMMS) ? (uint16_t)(idx + 2) : 0xFFFF;
+        uint16_t next_id = (idx + 1 < NUM_SDR_RECORDS) ? (uint16_t)(idx + 2) : 0xFFFF;
         rs_data[0] = 0x00;
         rs_data[0] = 0x00;
         rs_data[1] = (uint8_t)(next_id & 0xFF);
         rs_data[1] = (uint8_t)(next_id & 0xFF);
         rs_data[2] = (uint8_t)((next_id >> 8) & 0xFF);
         rs_data[2] = (uint8_t)((next_id >> 8) & 0xFF);
@@ -403,7 +514,21 @@ static size_t handle_ipmb_command(
             rs_data[0] = 0xC7;
             rs_data[0] = 0xC7;
             return 1;
             return 1;
         }
         }
-        int snum = (int)req_data[0] - 0x10;
+        uint8_t raw_snum = req_data[0];
+        if (raw_snum >= 0x30 && raw_snum < 0x30 + NUM_EXTRA_SENSORS) {
+            static const uint8_t extra_vals[NUM_EXTRA_SENSORS] = { 120, 110, 54, 52, 80, 145 };
+            int eidx = (int)(raw_snum - 0x30);
+            if (!st->power_on) {
+                rs_data[0] = 0x00; rs_data[1] = 0x00; rs_data[2] = 0x20; rs_data[3] = 0x00;
+                return 4;
+            }
+            rs_data[0] = 0x00;
+            rs_data[1] = extra_vals[eidx];
+            rs_data[2] = 0x40;
+            rs_data[3] = 0xC0;
+            return 4;
+        }
+        int snum = (int)raw_snum - 0x10;
         if (snum < 0 || snum >= NUM_DIMMS) {
         if (snum < 0 || snum >= NUM_DIMMS) {
             rs_data[0] = 0xCB;
             rs_data[0] = 0xCB;
             return 1;
             return 1;

+ 1 - 0
sim/hil_cluster/cluster_harness.py

@@ -272,6 +272,7 @@ class HilClusterStack:
                 "--data-dir", str(self.data_dir),
                 "--data-dir", str(self.data_dir),
                 "--web-listen", f"127.0.0.1:{self.web_port}",
                 "--web-listen", f"127.0.0.1:{self.web_port}",
                 "--tftp-listen", f"127.0.0.1:{self.tftp_port}",
                 "--tftp-listen", f"127.0.0.1:{self.tftp_port}",
+                "--pxe-mode", "disabled",
                 "--web-dir", str(WEB_DIR),
                 "--web-dir", str(WEB_DIR),
                 "--contracts", str(CONTRACTS_PATH),
                 "--contracts", str(CONTRACTS_PATH),
                 "--web-password", self.web_password,
                 "--web-password", self.web_password,

+ 26 - 16
sim/hil_cluster/dut_and_hood_sim.py

@@ -511,6 +511,7 @@ class DutStationSim:
             )
             )
 
 
             self.stage = "uip1"
             self.stage = "uip1"
+            rmt_enabled = True
             uip1_prompt = f"[0][{tag}]Please input your command:"
             uip1_prompt = f"[0][{tag}]Please input your command:"
             await self._tx(uip1_prompt)
             await self._tx(uip1_prompt)
             self.prompt_str = uip1_prompt
             self.prompt_str = uip1_prompt
@@ -525,6 +526,10 @@ class DutStationSim:
                     await self._tx(f"{cmd}\r\n[{tag}]Exit UIP\r\n")
                     await self._tx(f"{cmd}\r\n[{tag}]Exit UIP\r\n")
                     self.prompt_str = ""
                     self.prompt_str = ""
                     break
                     break
+                if "rmt disable" in low or "maskmain 48" in low:
+                    rmt_enabled = False
+                elif "rmt enable" in low or "unmaskmain 48" in low:
+                    rmt_enabled = True
                 await self._tx(f"{cmd}\r\n[0][{tag}] Set OK: {cmd}\r\n{uip1_prompt}")
                 await self._tx(f"{cmd}\r\n[0][{tag}] Set OK: {cmd}\r\n{uip1_prompt}")
 
 
             # 2. DDR5 MRC Training + 24-DIMM Inventory
             # 2. DDR5 MRC Training + 24-DIMM Inventory
@@ -548,22 +553,27 @@ class DutStationSim:
             await self._sleep_scaled(0.10)
             await self._sleep_scaled(0.10)
 
 
             # 3. Rank Margin Tool (RMT)
             # 3. Rank Margin Tool (RMT)
-            self.stage = "rmt"
-            for cpu in range(2):
-                await self._tx(f"START_RMT_N{cpu}\r\n")
-                for ch in range(12):
-                    await self._tx(f"[{pfx}_RMTSensor] N{cpu}.C{ch}.D0 : {66 + (ch % 4)}.5\r\n")
-                    if cpu == 0 and ch == 5 and self._consume_hang_for_stage("rmt"):
-                        # Hard hang mid-RMT: TCP :2200 & BMC :623 stay alive, UART completely silent!
-                        while self.running and self.power_on:
-                            await asyncio.sleep(1.0)
-                        return
-                    if self.inject_error_stage == "rmt" and cpu == 0 and ch == 2:
-                        await self._tx("N0.C2.D0.R0 : 0 0 0 0 Critical Margin Error\r\n")
-                    else:
-                        await self._tx(f"N{cpu}.C{ch}.D0.R0 : -18 19 -17 18\r\n")
-                await self._sleep_scaled(0.08)
-                await self._tx(f"STOP_RMT_N{cpu}\r\n")
+            if not rmt_enabled:
+                # Authentic 108_VD012 0-row wrapper output when RMT is disabled/masked
+                await self._tx(f"[{pfx}_BIOS] Rank Margin Tool -- SUCCEEDED,Time=18 ms\r\n")
+                await self._sleep_scaled(0.05)
+            else:
+                self.stage = "rmt"
+                for cpu in range(2):
+                    await self._tx(f"START_RMT_N{cpu}\r\n")
+                    for ch in range(12):
+                        await self._tx(f"[{pfx}_RMTSensor] N{cpu}.C{ch}.D0 : {66 + (ch % 4)}.5\r\n")
+                        if cpu == 0 and ch == 5 and self._consume_hang_for_stage("rmt"):
+                            # Hard hang mid-RMT: TCP :2200 & BMC :623 stay alive, UART completely silent!
+                            while self.running and self.power_on:
+                                await asyncio.sleep(1.0)
+                            return
+                        if self.inject_error_stage == "rmt" and cpu == 0 and ch == 2:
+                            await self._tx("N0.C2.D0.R0 : 0 0 0 0 Critical Margin Error\r\n")
+                        else:
+                            await self._tx(f"N{cpu}.C{ch}.D0.R0 : -18 19 -17 18\r\n")
+                    await self._sleep_scaled(0.08)
+                    await self._tx(f"STOP_RMT_N{cpu}\r\n")
 
 
             # 4. Dual-Socket Advanced Memory Test (AMT / AMEMDIAG)
             # 4. Dual-Socket Advanced Memory Test (AMT / AMEMDIAG)
             self.stage = "amt"
             self.stage = "amt"

+ 62 - 13
sim/hil_cluster/test_tier2_hil_e2e.py

@@ -130,7 +130,7 @@ async def run_tier2_suite() -> Dict[str, Any]:
         for k in ("ict_stage1_complete", "training_complete", "rmt_complete", "amt_complete", "ict_stage2_complete", "uefi_complete", "mt_pass_complete"):
         for k in ("ict_stage1_complete", "training_complete", "rmt_complete", "amt_complete", "ict_stage2_complete", "uefi_complete", "mt_pass_complete"):
             assert comps.get(k) is True, f"Missing stage completion {k} in {comps}"
             assert comps.get(k) is True, f"Missing stage completion {k} in {comps}"
 
 
-        # Verify 24-ch BMC SDR temperatures were read over RMCP+ and TFTP HTML report ingested
+        # Verify 24-ch BMC SDR temperatures + Full BMC system sensors (Voltage/Fan/Power/Current) + TFTP HTML report + HTTP Boot
         ctrl_s1 = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
         ctrl_s1 = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
         dimms_s1 = ctrl_s1.get("dimms") or []
         dimms_s1 = ctrl_s1.get("dimms") or []
         assert len(dimms_s1) == 24, f"Expected 24 DIMMs, got {len(dimms_s1)}"
         assert len(dimms_s1) == 24, f"Expected 24 DIMMs, got {len(dimms_s1)}"
@@ -140,10 +140,27 @@ async def run_tier2_suite() -> Dict[str, Any]:
             if isinstance((d.get("temperature") or {}).get("value_c"), (int, float))
             if isinstance((d.get("temperature") or {}).get("value_c"), (int, float))
         ]
         ]
         assert len(valid_temps) == 24, f"Expected 24 valid SDR/RMT DIMM temps, got {len(valid_temps)}"
         assert len(valid_temps) == 24, f"Expected 24 valid SDR/RMT DIMM temps, got {len(valid_temps)}"
+        bmc_sensors_s1 = ctrl_s1.get("bmc_sensors") or []
+        sensor_cats = {s.get("category") for s in bmc_sensors_s1}
+        assert len(bmc_sensors_s1) >= 30, f"Expected >= 30 full BMC sensors (24 DIMM + 6 system), got {len(bmc_sensors_s1)}"
+        for expected_cat in ("temp", "voltage", "fan", "power", "current"):
+            assert expected_cat in sensor_cats, f"Missing BMC sensor category {expected_cat} in {sensor_cats}"
+        # Verify bmc_sensors.jsonl archived in task-runs/
+        archived_sensor_files = list((stack.data_dir / "task-runs").rglob("bmc_sensors.jsonl"))
+        assert archived_sensor_files, "Expected bmc_sensors.jsonl archived inside task-runs/"
+        # Verify unauthenticated UEFI HTTP Boot /pxe/118.efi & /pxe/mt86.cfg endpoints
+        assert stack.http_session is not None
+        async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/pxe/118.efi") as r_efi:
+            assert r_efi.status == 200 and (await r_efi.read()).startswith(b"MZ"), "HTTP Boot /pxe/118.efi failed"
+        async with stack.http_session.get(f"http://127.0.0.1:{stack.web_port}/pxe/mt86.cfg") as r_cfg:
+            assert r_cfg.status == 200 and b"TSTLIST=" in (await r_cfg.read()), "HTTP Boot /pxe/mt86.cfg failed"
+        # Verify TEMP-2: GetDimmCurve returns BMC SDR fallback points on S2 even with NO hood connected!
+        curve_s2 = await stack.admin_ws.call("GetDimmCurve", {"station_id": "S2", "slot": 0})
+        assert len(curve_s2.get("points") or []) >= 1, f"Expected BMC SDR fallback curve points on S2, got {curve_s2}"
         pxe_rpts = ((ctrl_s1.get("pxe_control") or {}).get("recent_reports")) or []
         pxe_rpts = ((ctrl_s1.get("pxe_control") or {}).get("recent_reports")) or []
         assert len(pxe_rpts) >= 1, "Expected TFTP WRQ MemTest86 HTML report in recent_reports"
         assert len(pxe_rpts) >= 1, "Expected TFTP WRQ MemTest86 HTML report in recent_reports"
-        results.append({"scenario": "1_full_7stage_pass_sdr_tftp", "status": "PASS"})
-        print("      -> PASS", flush=True)
+        results.append({"scenario": "1_full_7stage_pass_full_bmc_sensors_tftp_httpboot", "status": "PASS", "bmc_sensor_count": len(bmc_sensors_s1)})
+        print(f"      -> PASS (bmc_sensors={len(bmc_sensors_s1)})", flush=True)
 
 
         # ====================================================================
         # ====================================================================
         # Scenario 2: Single-Link Drop (<no reset>) + >5s Dual-Disconnect (`link_offline_waiting`)
         # Scenario 2: Single-Link Drop (<no reset>) + >5s Dual-Disconnect (`link_offline_waiting`)
@@ -425,20 +442,21 @@ async def run_tier2_suite() -> Dict[str, Any]:
         print("      -> PASS", flush=True)
         print("      -> PASS", flush=True)
 
 
         # ====================================================================
         # ====================================================================
-        # Scenario 7: Level-2 Unattended `reboot_on_hang=True` SmartRestart Recovery & Circuit Breaker
+        # Scenario 7: 3-Mode Hang Recovery (`retry_current_task` + `restart_full_plan`) & Circuit Breaker
         # ====================================================================
         # ====================================================================
-        print("[Tier2][7/8] Testing Level-2 `reboot_on_hang=True` SmartRestart recovery (S1) + `max_consecutive_hangs=2` circuit breaker (S2)...", flush=True)
-        # 7a: S1 hangs ONCE in RMT (`hang_remaining_boots=1`), Round 2 recovers via real RMCP+ SmartRestart and PASSES!
+        print("[Tier2][7/8] Testing 3-mode hang recovery: retry_current_task (S1) + restart_full_plan (S4) + max_consecutive_hangs breaker (S2)...", flush=True)
+        # 7a: S1 hangs ONCE in RMT (`hang_remaining_boots=1`), `retry_current_task` REDOES unfinished Round 1 (PASS) AND runs Round 2 (PASS)!
         await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12)
         await stack.configure_dut(0, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12)
         await stack.enqueue_cmd(
         await stack.enqueue_cmd(
             "S1",
             "S1",
             "SubmitTaskBatch",
             "SubmitTaskBatch",
             {
             {
                 "stop_on_fail": False,
                 "stop_on_fail": False,
+                "hang_action": "retry_current_task",
                 "reboot_on_hang": True,
                 "reboot_on_hang": True,
                 "max_consecutive_hangs": 2,
                 "max_consecutive_hangs": 2,
                 "watchdog": {"dense_stage_silence_timeout_ms": 2200},
                 "watchdog": {"dense_stage_silence_timeout_ms": 2200},
-                "profiles": [{"name": "Level2-Transient-Hang-Recovery", "repeat": 2, "run_rmt": True, "run_amt": False, "run_mt": False}],
+                "profiles": [{"name": "RetryCurrentTask-2R", "repeat": 2, "run_rmt": True, "run_amt": False, "run_mt": False}],
             },
             },
         )
         )
 
 
@@ -447,14 +465,45 @@ async def run_tier2_suite() -> Dict[str, Any]:
             b = resp.get("task_batch") or {}
             b = resp.get("task_batch") or {}
             return b if b.get("state") in ("completed", "failed") else None
             return b if b.get("state") in ("completed", "failed") else None
 
 
-        b_s1_rec = await wait_until(_s1_batch_done, timeout_s=45.0, desc="S1 Level-2 2-round batch completion")
+        b_s1_rec = await wait_until(_s1_batch_done, timeout_s=45.0, desc="S1 retry_current_task 2-round batch completion")
         runs_s1 = b_s1_rec.get("runs") or []
         runs_s1 = b_s1_rec.get("runs") or []
-        assert len(runs_s1) == 2, f"Expected 2 runs (R1 hang -> SmartRestart -> R2 pass), got {b_s1_rec}"
-        assert runs_s1[0].get("verdict") == "fail", f"Expected R1 fail, got {runs_s1[0]}"
-        assert runs_s1[1].get("verdict") == "pass", f"Expected R2 pass after SmartRestart recovery, got {runs_s1[1]}"
+        assert len(runs_s1) == 3, f"Expected 3 runs (R1 hang -> SmartRestart redoes R1 pass -> R2 pass), got {b_s1_rec}"
+        assert runs_s1[0].get("verdict") == "fail" and runs_s1[0].get("repeat_index") == 1, f"Expected R1 fail, got {runs_s1[0]}"
+        assert runs_s1[1].get("verdict") == "pass" and runs_s1[1].get("repeat_index") == 1, f"Expected R1 redone PASS, got {runs_s1[1]}"
+        assert runs_s1[2].get("verdict") == "pass" and runs_s1[2].get("repeat_index") == 2, f"Expected R2 PASS, got {runs_s1[2]}"
+
+        # 7b: S4 `restart_full_plan`: Profile 1 (no RMT) PASS -> Profile 2 (with RMT) hangs ONCE -> restarts FULL PLAN back to Profile 1 -> both PASS!
+        await stack.configure_dut(3, hang_stage="rmt", hang_remaining_boots=1, speed_scale=0.12)
+        await stack.enqueue_cmd(
+            "S4",
+            "SubmitTaskBatch",
+            {
+                "stop_on_fail": False,
+                "hang_action": "restart_full_plan",
+                "reboot_on_hang": True,
+                "max_consecutive_hangs": 2,
+                "watchdog": {"dense_stage_silence_timeout_ms": 2200},
+                "profiles": [
+                    {"name": "Plan-Step1-NoRMT", "repeat": 1, "run_rmt": False, "run_amt": False, "run_mt": False},
+                    {"name": "Plan-Step2-RMT", "repeat": 1, "run_rmt": True, "run_amt": False, "run_mt": False},
+                ],
+            },
+        )
+
+        async def _s4_batch_done():
+            resp = await stack.admin_ws.call("GetStationControl", {"station_id": "S4"})
+            b = resp.get("task_batch") or {}
+            return b if b.get("state") in ("completed", "failed") else None
+
+        b_s4_full = await wait_until(_s4_batch_done, timeout_s=50.0, desc="S4 restart_full_plan completion")
+        runs_s4 = b_s4_full.get("runs") or []
+        assert b_s4_full.get("state") == "completed", f"Expected S4 restart_full_plan completed, got {b_s4_full}"
+        assert len(runs_s4) == 4, f"Expected 4 runs (P1 pass, P2 fail -> restart -> P1 pass, P2 pass), got {runs_s4}"
+        assert [r.get("profile_name") for r in runs_s4] == ["Plan-Step1-NoRMT", "Plan-Step2-RMT", "Plan-Step1-NoRMT", "Plan-Step2-RMT"]
+        assert [r.get("verdict") for r in runs_s4] == ["pass", "fail", "pass", "pass"]
 
 
-        # 7b: S2 permanently dead board (`hang_remaining_boots=99`, `repeat=4`, `max_consecutive_hangs=2`)
-        #     -> hangs in R1, auto-reboots into R2, hangs in R2 -> trips `consecutive_hang_limit_exceeded` & cools hood!
+        # 7c: S2 permanently dead board (`hang_remaining_boots=99`, `repeat=4`, `max_consecutive_hangs=2`)
+        #     -> hangs in R1, auto-reboots to redo R1, hangs again -> trips `consecutive_hang_limit_exceeded` & cools hood!
         await stack.clear_hood_history(1)
         await stack.clear_hood_history(1)
         await stack.connect_and_heat_backend_hood("S2", 1, target_c=70)
         await stack.connect_and_heat_backend_hood("S2", 1, target_c=70)
         await stack.configure_dut(1, hang_stage="rmt", hang_remaining_boots=99, speed_scale=0.12)
         await stack.configure_dut(1, hang_stage="rmt", hang_remaining_boots=99, speed_scale=0.12)

+ 8 - 5
sim/kvm_uefi_tier/test_tier3_kvm_uefi_e2e.py

@@ -164,12 +164,14 @@ async def bridge_kvm_uart_and_pwr(
                         q_writer.write("".join(out_chars).encode("utf-8"))
                         q_writer.write("".join(out_chars).encode("utf-8"))
                         await q_writer.drain()
                         await q_writer.drain()
 
 
+            stats["bridge_connected"] = True
             await asyncio.gather(qemu_to_bmc(), bmc_to_qemu())
             await asyncio.gather(qemu_to_bmc(), bmc_to_qemu())
         except asyncio.CancelledError:
         except asyncio.CancelledError:
             raise
             raise
-        except Exception:
-            pass
+        except Exception as exc:
+            stats.setdefault("bridge_errors", []).append(repr(exc))
         finally:
         finally:
+            stats["bridge_connected"] = False
             for w in (q_writer, b_writer):
             for w in (q_writer, b_writer):
                 if w is not None:
                 if w is not None:
                     with contextlib.suppress(Exception):
                     with contextlib.suppress(Exception):
@@ -310,12 +312,12 @@ podman run -d --rm --name {cname} \
             text=True,
             text=True,
             env=env,
             env=env,
         )
         )
-        await asyncio.sleep(0.4)
-
+        await asyncio.sleep(0.6)
         stats: Dict[str, Any] = {}
         stats: Dict[str, Any] = {}
         bridge_task = asyncio.create_task(
         bridge_task = asyncio.create_task(
             bridge_kvm_uart_and_pwr(q_serial_port, bmc_uart_port, qmp, stats)
             bridge_kvm_uart_and_pwr(q_serial_port, bmc_uart_port, qmp, stats)
         )
         )
+        await wait_until(lambda: stats.get("bridge_connected") is True, timeout_s=10.0, desc="KVM UART bridge connected")
 
 
         # Start `/dev/pts/*` 6400 Hood simulator for S1
         # Start `/dev/pts/*` 6400 Hood simulator for S1
         hood = HoodPtsSim("kvm-hood-S1", 0, ("127.0.0.1", bmc_ctrl_port), sync_bmc=True)
         hood = HoodPtsSim("kvm-hood-S1", 0, ("127.0.0.1", bmc_ctrl_port), sync_bmc=True)
@@ -375,6 +377,7 @@ podman run -d --rm --name {cname} \
                 "--data-dir", str(data_dir),
                 "--data-dir", str(data_dir),
                 "--web-listen", f"127.0.0.1:{web_port}",
                 "--web-listen", f"127.0.0.1:{web_port}",
                 "--tftp-listen", "disabled",
                 "--tftp-listen", "disabled",
+                "--pxe-mode", "disabled",
                 "--web-dir", str(WEB_DIR),
                 "--web-dir", str(WEB_DIR),
                 "--contracts", str(CONTRACTS_PATH),
                 "--contracts", str(CONTRACTS_PATH),
                 "--web-password", "disabled",
                 "--web-password", "disabled",
@@ -450,7 +453,7 @@ podman run -d --rm --name {cname} \
                 if st_pass["task_status"] != "completed":
                 if st_pass["task_status"] != "completed":
                     clean_u = await ws.call("ReadCleanedUart", {"station_id": "S1", "offset": 0, "max_bytes": 8192})
                     clean_u = await ws.call("ReadCleanedUart", {"station_id": "S1", "offset": 0, "max_bytes": 8192})
                     raise AssertionError(
                     raise AssertionError(
-                        f"Unexpected KVM S1 state: {st_pass}\nRAW_TAIL={repr(stats.get('tail_text', '')[-1200:])}\nCLEAN_TAIL={repr(clean_u.get('text', '')[-1200:])}"
+                        f"Unexpected KVM S1 state: {st_pass}\nBRIDGE={stats.get('bridge_connected')} ERRS={stats.get('bridge_errors')}\nRAW_TAIL={repr(stats.get('tail_text', '')[-1200:])}\nCLEAN_TAIL={repr(clean_u.get('text', '')[-1200:])}"
                     )
                     )
                 assert st_pass["verdict"] == "pass", f"Unexpected KVM S1 state: {st_pass}"
                 assert st_pass["verdict"] == "pass", f"Unexpected KVM S1 state: {st_pass}"
                 assert (st_pass.get("stage_completions") or {}).get("uefi_complete") is True
                 assert (st_pass.get("stage_completions") or {}).get("uefi_complete") is True

+ 645 - 0
sim/kvm_uefi_tier/test_tier3b_diskless_pxe.py

@@ -0,0 +1,645 @@
+#!/usr/bin/env python3
+"""
+test_tier3b_diskless_pxe.py — Tier 3B Real 100% Diskless KVM + OVMF UEFI PXE Boot
+                              via Built-in ProxyDHCP under a Competing LAN DHCP Router
+
+Runs completely isolated inside an ephemeral Podman container (`--rm --network=none --device /dev/kvm --device /dev/net/tun`)
+on `root@192.168.2.25` so zero host network state is ever touched:
+  1. Real L2 Ethernet bridge `br0` (`10.99.77.1/24` = unmodified `stl_native_server --pxe-mode proxy --pxe-iface br0`)
+  2. Separate network namespace `lan_rtr` (`10.99.77.2/24`) running a real competing LAN DHCP Router (assigns IPs ONLY, no PXE)
+  3. Separate network namespace `office_pc` sending an ordinary non-PXE `DHCPDISCOVER` -> verifies ONLY the competing router
+     replies and `stl_native_server` ignores it (`packets_ignored_non_pxe >= 1`)
+  4. `stl_native_server` 1-click LAN self-check (`ProbePxeNetwork`) -> verifies detection of external router `10.99.77.2`
+  5. 100% DISKLESS (`-drive` NONE — ZERO disks attached!) KVM + EDK2 OVMF VM on `tap0` (`mac=52:54:00:aa:bb:cc`) ->
+     gets IP `10.99.77.5x` from competing router `10.99.77.2`, gets ProxyDHCP `118.efi` from `stl_native_server` (`10.99.77.1`),
+     downloads real x86-64 `mt86plus.efi` via built-in UDP :69 TFTP, and boots it in RAM with zero local disks!
+"""
+
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+from typing import Any, Dict, List
+
+ROOT_DIR = Path(__file__).resolve().parents[2]
+STL_SERVER_BIN = ROOT_DIR / "build" / "native" / "stl_native_server"
+CONTRACTS_PATH = ROOT_DIR / "contracts" / "firmware-vd012.json"
+WEB_DIR = ROOT_DIR / "web"
+
+REMOTE_HOST = os.environ.get("STL_KVM_HOST", "192.168.2.25")
+REMOTE_USER = os.environ.get("STL_KVM_USER", "root")
+PODMAN_IMAGE = "localhost/omo-lab:13-iso-20260921T030408Z"
+
+SKIP_SO_PREFIXES = (
+    "libc.so",
+    "libm.so",
+    "libdl.so",
+    "libpthread.so",
+    "librt.so",
+    "libutil.so",
+    "libgcc_s.so",
+    "libresolv.so",
+    "ld-linux",
+)
+
+IN_CONTAINER_RUNNER = r'''#!/usr/bin/env python3
+import base64
+import hashlib
+import json
+import os
+from pathlib import Path
+import socket
+import struct
+import subprocess
+import sys
+import threading
+import time
+import urllib.request
+
+SIM = Path("/sim")
+DHCP_COOKIE = b"\x63\x82\x53\x63"
+
+
+def sh(cmd: str, check: bool = True) -> subprocess.CompletedProcess:
+    return subprocess.run(["bash", "-lc", cmd], check=check, capture_output=True, text=True)
+
+
+def run_competing_lan_dhcp_router() -> None:
+    """Real RFC 2131 LAN DHCP Router (assigns 10.99.77.50..99, ZERO PXE options)."""
+    srv_ip = socket.inet_aton("10.99.77.2")
+    mask = socket.inet_aton("255.255.255.0")
+    leases = {}
+    next_host = [50]
+
+    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
+    sock.setsockopt(socket.SOL_SOCKET, 25, b"veth-rtr\x00")  # SO_BINDTODEVICE
+    sock.bind(("0.0.0.0", 67))
+    sock.settimeout(0.5)
+
+    def parse_opts(data: bytes):
+        opts = {}
+        i = 240
+        while i < len(data):
+            c = data[i]
+            i += 1
+            if c == 0:
+                continue
+            if c == 255:
+                break
+            if i >= len(data):
+                break
+            ln = data[i]
+            i += 1
+            opts[c] = data[i : i + ln]
+            i += ln
+        return opts
+
+    log_path = SIM / "router_dhcp.log"
+    while not (SIM / "stop_router").exists():
+        try:
+            pkt, addr = sock.recvfrom(1500)
+        except socket.timeout:
+            continue
+        except Exception as exc:
+            with open(log_path, "a", encoding="utf-8") as fp:
+                fp.write(f"ERR {exc!r}\n")
+            continue
+        if len(pkt) < 240 or pkt[0] != 1 or pkt[236:240] != DHCP_COOKIE:
+            continue
+        opts = parse_opts(pkt)
+        mtype = opts.get(53, b"\x00")[0]
+        if mtype not in (1, 3):
+            continue
+        mac = pkt[28:34]
+        mac_str = ":".join(f"{b:02x}" for b in mac)
+        if mac_str not in leases:
+            ip_str = f"10.99.77.{next_host[0]}"
+            next_host[0] += 1
+            leases[mac_str] = ip_str
+        yiaddr = socket.inet_aton(leases[mac_str])
+        reply_type = 2 if mtype == 1 else 5  # OFFER or ACK
+
+        resp = bytearray(240)
+        resp[0] = 2  # BOOTREPLY
+        resp[1] = 1
+        resp[2] = 6
+        resp[4:8] = pkt[4:8]      # xid
+        resp[10:12] = pkt[10:12]  # flags
+        resp[16:20] = yiaddr      # yiaddr (client IP ONLY, siaddr=0.0.0.0, file="")
+        resp[28:44] = pkt[28:44]  # chaddr
+        resp[236:240] = DHCP_COOKIE
+        resp += bytes([53, 1, reply_type])
+        resp += bytes([54, 4]) + srv_ip
+        resp += bytes([51, 4]) + struct.pack("!I", 3600)
+        resp += bytes([1, 4]) + mask
+        resp += bytes([3, 4]) + srv_ip
+        resp += bytes([255])
+        if len(resp) < 300:
+            resp += b"\x00" * (300 - len(resp))
+
+        sock.sendto(bytes(resp), ("255.255.255.255", 68))
+        with open(log_path, "a", encoding="utf-8") as fp:
+            fp.write(f"{'OFFER' if reply_type == 2 else 'ACK'} mac={mac_str} ip={leases[mac_str]}\n")
+
+
+def run_office_pc_non_pxe_probe() -> dict:
+    """Send ordinary MSFT 5.0 non-PXE DHCPDISCOVER and capture ALL UDP:68 replies via AF_PACKET (authentic unaddressed NIC)."""
+    raw_rx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
+    raw_rx.bind(("veth-pc", 0))
+    raw_rx.settimeout(0.2)
+
+    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
+    sock.setsockopt(socket.SOL_SOCKET, 25, b"veth-pc\x00")  # SO_BINDTODEVICE
+    sock.bind(("0.0.0.0", 68))
+
+    xid = b"\xde\xad\xbe\xef"
+    mac = bytes([0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0x01])
+    disc = bytearray(240)
+    disc[0] = 1
+    disc[1] = 1
+    disc[2] = 6
+    disc[4:8] = xid
+    disc[10:12] = b"\x80\x00"  # broadcast
+    disc[28:34] = mac
+    disc[236:240] = DHCP_COOKIE
+    disc += bytes([53, 1, 1])
+    vc = b"MSFT 5.0"
+    disc += bytes([60, len(vc)]) + vc
+    disc += bytes([55, 3, 1, 3, 6])
+    disc += bytes([255])
+    if len(disc) < 300:
+        disc += b"\x00" * (300 - len(disc))
+
+    sock.sendto(bytes(disc), ("255.255.255.255", 67))
+    offers = []
+    deadline = time.monotonic() + 1.1
+    while time.monotonic() < deadline:
+        try:
+            frame = raw_rx.recv(2048)
+        except socket.timeout:
+            continue
+        if len(frame) < 14 + 20 + 8:
+            continue
+        ihl = (frame[14] & 0x0F) * 4
+        if frame[14 + 9] != 17 or len(frame) < 14 + ihl + 8:
+            continue
+        src_ip = socket.inet_ntoa(frame[14 + 12 : 14 + 16])
+        udp_off = 14 + ihl
+        src_port, dst_port = struct.unpack("!HH", frame[udp_off : udp_off + 4])
+        if dst_port != 68:
+            continue
+        pkt = frame[udp_off + 8 :]
+        if len(pkt) < 240 or pkt[0] != 2 or pkt[4:8] != xid:
+            continue
+        yiaddr = socket.inet_ntoa(pkt[16:20])
+        siaddr = socket.inet_ntoa(pkt[20:24])
+        file_field = pkt[108:236].split(b"\x00", 1)[0].decode("ascii", errors="replace")
+        offers.append({"from": src_ip, "src_port": src_port, "yiaddr": yiaddr, "siaddr": siaddr, "file": file_field})
+    sock.close()
+    raw_rx.close()
+    return {"offers": offers}
+
+
+def ws_rpc_call(port: int, method: str, params: dict) -> dict:
+    """Minimal zero-dependency RFC 6455 WebSocket JSON-RPC client (no aiohttp needed inside container)."""
+    s = socket.create_connection(("127.0.0.1", port), timeout=15.0)
+    key = base64.b64encode(os.urandom(16)).decode("ascii")
+    req = (
+        f"GET /ws HTTP/1.1\r\n"
+        f"Host: 127.0.0.1:{port}\r\n"
+        f"Upgrade: websocket\r\n"
+        f"Connection: Upgrade\r\n"
+        f"Sec-WebSocket-Key: {key}\r\n"
+        f"Sec-WebSocket-Version: 13\r\n\r\n"
+    )
+    s.sendall(req.encode("ascii"))
+    hdr = b""
+    while b"\r\n\r\n" not in hdr:
+        chunk = s.recv(4096)
+        if not chunk:
+            raise RuntimeError("WS handshake closed")
+        hdr += chunk
+    if b"101 " not in hdr.split(b"\r\n", 1)[0]:
+        raise RuntimeError(f"WS handshake failed: {hdr[:120]!r}")
+    extra = hdr.split(b"\r\n\r\n", 1)[1]
+
+    req_id = f"pxe3b-{int(time.time() * 1000)}"
+    payload = json.dumps({"v": 1, "id": req_id, "method": method, "params": params}).encode("utf-8")
+    mask_key = os.urandom(4)
+    frame = bytearray([0x81])
+    if len(payload) < 126:
+        frame.append(0x80 | len(payload))
+    elif len(payload) < 65536:
+        frame.append(0x80 | 126)
+        frame += struct.pack("!H", len(payload))
+    else:
+        frame.append(0x80 | 127)
+        frame += struct.pack("!Q", len(payload))
+    frame += mask_key
+    frame += bytes(b ^ mask_key[i & 3] for i, b in enumerate(payload))
+    s.sendall(bytes(frame))
+
+    buf = bytearray(extra)
+
+    def read_exact(n: int) -> bytes:
+        while len(buf) < n:
+            c = s.recv(4096)
+            if not c:
+                raise RuntimeError("WS EOF")
+            buf.extend(c)
+        out = bytes(buf[:n])
+        del buf[:n]
+        return out
+
+    try:
+        while True:
+            b0, b1 = read_exact(2)
+            op = b0 & 0x0F
+            ln = b1 & 0x7F
+            if ln == 126:
+                ln = struct.unpack("!H", read_exact(2))[0]
+            elif ln == 127:
+                ln = struct.unpack("!Q", read_exact(8))[0]
+            data = read_exact(ln)
+            if op == 1:
+                msg = json.loads(data.decode("utf-8"))
+                if msg.get("id") == req_id:
+                    if not msg.get("ok"):
+                        raise RuntimeError(f"RPC {method} error: {msg.get('error')}")
+                    return msg.get("result") or {}
+    finally:
+        s.close()
+
+
+def main() -> None:
+    if len(sys.argv) >= 2 and sys.argv[1] == "--router":
+        run_competing_lan_dhcp_router()
+        return
+    if len(sys.argv) >= 2 and sys.argv[1] == "--office-pc":
+        print(json.dumps(run_office_pc_non_pxe_probe()))
+        return
+
+    # 1. Build real 3-node Ethernet L2 topology on bridge br0
+    sh(
+        """
+set -euo pipefail
+ip link set lo up
+ip link add br0 type bridge
+ip link set br0 type bridge stp_state 0
+ip addr add 10.99.77.1/24 dev br0
+ip link set br0 up
+ip route add 255.255.255.255/32 dev br0
+
+ip netns add lan_rtr
+ip link add veth-rtr type veth peer name veth-rtr-br
+ip link set veth-rtr netns lan_rtr
+ip link set veth-rtr-br master br0 up
+ip netns exec lan_rtr ip link set lo up
+ip netns exec lan_rtr ip addr add 10.99.77.2/24 dev veth-rtr
+ip netns exec lan_rtr ip link set veth-rtr up
+ip netns exec lan_rtr ip route add 255.255.255.255/32 dev veth-rtr
+
+ip netns add office_pc
+ip link add veth-pc type veth peer name veth-pc-br
+ip link set veth-pc address 02:aa:bb:cc:dd:01
+ip link set veth-pc netns office_pc
+ip link set veth-pc-br master br0 up
+ip netns exec office_pc ip link set lo up
+ip netns exec office_pc ip link set veth-pc up
+ip netns exec office_pc ip route add 255.255.255.255/32 dev veth-pc
+
+ip tuntap add dev tap0 mode tap
+ip link set tap0 master br0
+ip link set tap0 up
+"""
+    )
+
+    # 2. Start competing LAN DHCP Router in `lan_rtr` (10.99.77.2, NO PXE options)
+    rtr_proc = subprocess.Popen(
+        ["ip", "netns", "exec", "lan_rtr", "python3", str(SIM / "in_container_pxe_runner.py"), "--router"],
+        stdout=subprocess.DEVNULL,
+        stderr=subprocess.PIPE,
+        text=True,
+    )
+    time.sleep(0.4)
+
+    # 3. Prepare data dir with REAL compiled mt86plus.efi as 118.efi
+    data_dir = SIM / "data"
+    pxe_dir = data_dir / "pxe_tftp"
+    pxe_dir.mkdir(parents=True, exist_ok=True)
+    efi_bytes = (SIM / "mt86plus.efi").read_bytes()
+    (pxe_dir / "118.efi").write_bytes(efi_bytes)
+    efi_sha256 = hashlib.sha256(efi_bytes).hexdigest()
+
+    cfg_path = SIM / "station.json"
+    cfg_path.write_text(
+        json.dumps(
+            {
+                "mode": "hardware",
+                "data_dir": str(data_dir),
+                "stations": [
+                    {
+                        "station_id": "S1",
+                        "name": "Diskless-PXE-KVM",
+                        "cpu_count": 1,
+                        "os_mac": "52:54:00:aa:bb:cc",
+                        "bmc": {"enabled": False, "host": ""},
+                        "console": {"enabled": False, "transport": "local_serial", "host": ""},
+                    }
+                ],
+            }
+        ),
+        encoding="utf-8",
+    )
+
+    srv_env = dict(os.environ)
+    srv_env["LD_LIBRARY_PATH"] = str(SIM / "libs")
+    srv_log = open(SIM / "stl_server.log", "w", encoding="utf-8")
+    srv_proc = subprocess.Popen(
+        [
+            str(SIM / "stl_native_server"),
+            "--config", str(cfg_path),
+            "--data-dir", str(data_dir),
+            "--web-listen", "0.0.0.0:18099",
+            "--tftp-listen", "0.0.0.0:69",
+            "--pxe-mode", "proxy",
+            "--pxe-iface", "br0",
+            "--web-dir", str(SIM / "web"),
+            "--contracts", str(SIM / "contracts" / "firmware-vd012.json"),
+            "--web-password", "disabled",
+            "--detail-log", "on",
+        ],
+        env=srv_env,
+        stdout=srv_log,
+        stderr=subprocess.STDOUT,
+        text=True,
+    )
+
+    qemu_proc = None
+    try:
+        # Wait until stl_native_server binds UDP 67, 4011, 69 & HTTP 18099
+        st_pxe = None
+        for _ in range(40):
+            try:
+                st_pxe = ws_rpc_call(18099, "GetPxeStatus", {})
+                if st_pxe.get("dhcp67_bound") and st_pxe.get("proxy4011_bound") and st_pxe.get("tftp69_bound"):
+                    break
+            except Exception:
+                pass
+            time.sleep(0.25)
+        assert st_pxe and st_pxe.get("dhcp67_bound") and st_pxe.get("proxy4011_bound") and st_pxe.get("tftp69_bound"), (
+            f"stl_native_server failed to bind PXE/TFTP ports: {st_pxe}\nLOG={Path(SIM / 'stl_server.log').read_text()}"
+        )
+        assert st_pxe.get("efi_present") is True and int(st_pxe.get("efi_bytes", 0)) == len(efi_bytes)
+
+        # Verify HTTP Boot endpoint serves byte-identical 118.efi
+        with urllib.request.urlopen("http://10.99.77.1:18099/pxe/118.efi", timeout=5) as r:
+            dl_efi = r.read()
+            assert hashlib.sha256(dl_efi).hexdigest() == efi_sha256, "HTTP Boot /pxe/118.efi SHA mismatch"
+
+        # 4. Verify non-PXE office PC ONLY gets reply from competing router 10.99.77.2 (0 from stl_native_server)
+        pc_out = subprocess.run(
+            ["ip", "netns", "exec", "office_pc", "python3", str(SIM / "in_container_pxe_runner.py"), "--office-pc"],
+            capture_output=True,
+            text=True,
+            timeout=10,
+        )
+        assert pc_out.returncode == 0, f"office_pc probe failed rc={pc_out.returncode}: stdout={pc_out.stdout} stderr={pc_out.stderr}"
+        pc_res = json.loads(pc_out.stdout.strip())
+        offers = pc_res.get("offers") or []
+        assert len(offers) == 1, f"Office PC must get EXACTLY 1 offer (from competing router only!), got {offers}"
+        assert offers[0]["from"] == "10.99.77.2" and offers[0]["yiaddr"].startswith("10.99.77.5"), f"Bad office PC offer: {offers}"
+        assert offers[0]["file"] == ""
+        st_after_pc = ws_rpc_call(18099, "GetPxeStatus", {})
+        assert int(st_after_pc.get("packets_ignored_non_pxe", 0)) >= 1, f"ProxyDHCP must count ignored non-PXE packet: {st_after_pc}"
+
+        # 5. Verify 1-click LAN DHCP/PXE self-check (`ProbePxeNetwork`) detects external router 10.99.77.2
+        probe_res = ws_rpc_call(18099, "ProbePxeNetwork", {"iface": "br0", "timeout_ms": 1000})
+        ext_srvs = probe_res.get("external_dhcp_servers") or []
+        assert any(s.get("server_ip") == "10.99.77.2" and s.get("has_pxe_conflict") is False for s in ext_srvs), (
+            f"ProbePxeNetwork must detect competing LAN DHCP router 10.99.77.2: {probe_res}"
+        )
+        assert probe_res.get("recommended_mode") == "proxy", f"Expected recommended_mode=proxy: {probe_res}"
+
+        # 6. Boot 100% DISKLESS (`-drive` NONE — ZERO disks!) real KVM + EDK2 OVMF UEFI VM over PXE!
+        serial_log_path = SIM / "vm_serial.log"
+        serial_log_path.write_bytes(b"")
+        qemu_cmd = [
+            "qemu-system-x86_64",
+            "-machine", "q35,accel=kvm",
+            "-cpu", "host",
+            "-smp", "2",
+            "-m", "512M",
+            "-display", "none",
+            "-drive", f"if=pflash,format=raw,readonly=on,file={SIM / 'code.fd'}",
+            "-drive", f"if=pflash,format=raw,file={SIM / 'vars.fd'}",
+            "-netdev", "tap,id=net0,ifname=tap0,script=no,downscript=no",
+            "-device", "e1000,netdev=net0,mac=52:54:00:aa:bb:cc,bootindex=1",
+            "-serial", f"file:{serial_log_path}",
+        ]
+        qemu_proc = subprocess.Popen(qemu_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
+
+        # Wait up to 45s for OVMF UEFI PXE to obtain IP from router 10.99.77.2 + ProxyDHCP 118.efi from 10.99.77.1 + TFTP download!
+        vm_serial = ""
+        pxe_client_ack = None
+        deadline = time.monotonic() + 45.0
+        while time.monotonic() < deadline:
+            if serial_log_path.is_file():
+                vm_serial = serial_log_path.read_text(encoding="utf-8", errors="replace")
+            st_now = ws_rpc_call(18099, "GetPxeStatus", {})
+            clients = st_now.get("discovered_clients") or []
+            for c in clients:
+                if (
+                    c.get("mac") == "52:54:00:aa:bb:cc"
+                    and c.get("boot_target") == "118.efi"
+                    and int(c.get("reply_count", 0)) >= 1
+                ):
+                    pxe_client_ack = c
+            if (
+                "Station IP address is 10.99.77." in vm_serial
+                and "Server IP address is 10.99.77.1" in vm_serial
+                and "NBP filename is 118.efi" in vm_serial
+                and "NBP file downloaded successfully" in vm_serial
+                and "BdsDxe: starting" in vm_serial
+                and pxe_client_ack is not None
+            ):
+                # Give real mt86plus.efi 2.5s to run in KVM RAM after NBP handoff
+                time.sleep(2.5)
+                vm_serial = serial_log_path.read_text(encoding="utf-8", errors="replace")
+                break
+            time.sleep(0.5)
+
+        st_final = ws_rpc_call(18099, "GetPxeStatus", {})
+        router_log = (SIM / "router_dhcp.log").read_text(encoding="utf-8", errors="replace") if (SIM / "router_dhcp.log").is_file() else ""
+        srv_log.flush()
+        srv_txt = (SIM / "stl_server.log").read_text(encoding="utf-8", errors="replace")
+
+        assert pxe_client_ack is not None, (
+            f"Diskless KVM VM did not receive ProxyDHCP reply for 118.efi!\n"
+            f"PXE_STATUS={json.dumps(st_final, ensure_ascii=False)}\nROUTER_LOG={router_log}\n"
+            f"VM_SERIAL={vm_serial[-2000:]}\nSRV_LOG={srv_txt[-1500:]}"
+        )
+        assert "Station IP address is 10.99.77." in vm_serial, f"Missing competing router IP in OVMF output:\n{vm_serial[-2000:]}"
+        assert "Server IP address is 10.99.77.1" in vm_serial, f"Missing ProxyDHCP server IP 10.99.77.1:\n{vm_serial[-2000:]}"
+        assert "NBP filename is 118.efi" in vm_serial, f"Missing NBP 118.efi:\n{vm_serial[-2000:]}"
+        assert "NBP file downloaded successfully" in vm_serial, f"TFTP download of 118.efi failed:\n{vm_serial[-2000:]}"
+        assert "BdsDxe: starting" in vm_serial, f"OVMF did not start downloaded 118.efi:\n{vm_serial[-2000:]}"
+        assert f"ACK mac=52:54:00:aa:bb:cc ip=10.99.77." in router_log, f"Competing router did not lease IP to VM:\n{router_log}"
+        assert qemu_proc.poll() is None, "Diskless KVM VM crashed immediately after NBP execution"
+
+        result = {
+            "ok": True,
+            "office_pc_offer": offers[0],
+            "packets_ignored_non_pxe": st_final.get("packets_ignored_non_pxe"),
+            "probe_detected_router": ext_srvs,
+            "probe_recommended_mode": probe_res.get("recommended_mode"),
+            "diskless_pxe_client": pxe_client_ack,
+            "http_boot_efi_sha256": efi_sha256,
+            "efi_bytes": len(efi_bytes),
+            "vm_serial_excerpt": vm_serial[-1200:],
+            "router_log": router_log.strip(),
+        }
+        (SIM / "tier3b_result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
+        print("TIER3B_SUCCESS")
+    finally:
+        (SIM / "stop_router").write_text("1", encoding="utf-8")
+        for p in (qemu_proc, srv_proc, rtr_proc):
+            if p is not None and p.poll() is None:
+                p.terminate()
+                try:
+                    p.wait(timeout=3)
+                except Exception:
+                    p.kill()
+        srv_log.close()
+
+
+if __name__ == "__main__":
+    main()
+'''
+
+
+def collect_non_glibc_libs(binary: Path) -> List[Path]:
+    env = dict(os.environ)
+    env.pop("LD_LIBRARY_PATH", None)
+    out = subprocess.run(["ldd", str(binary)], check=True, capture_output=True, text=True, env=env).stdout
+    libs: List[Path] = []
+    seen = set()
+    for line in out.splitlines():
+        m = re.search(r"=>\s+(/\S+)\s+\(", line)
+        if not m:
+            continue
+        p = Path(m.group(1))
+        if any(p.name.startswith(pref) for pref in SKIP_SO_PREFIXES):
+            continue
+        real = p.resolve()
+        if real.is_file() and p.name not in seen:
+            seen.add(p.name)
+            libs.append((p.name, real))  # type: ignore[arg-type]
+    return libs  # type: ignore[return-value]
+
+
+def run_tier3b_diskless_pxe() -> Dict[str, Any]:
+    t0 = time.monotonic()
+    run_tag = f"xjkj-stl-pxe3b-{os.getpid()}-{int(time.time())}"
+    remote_dir = f"/tmp/{run_tag}"
+
+    print(f"[Tier3B] Bundling stl_native_server + runtime libs for 100% diskless KVM+OVMF ProxyDHCP test on {REMOTE_HOST}...", flush=True)
+    with tempfile.TemporaryDirectory(prefix="xjkj_tier3b_") as ltmp:
+        tar_path = Path(ltmp) / "bundle.tar"
+        runner_path = Path(ltmp) / "in_container_pxe_runner.py"
+        runner_path.write_text(IN_CONTAINER_RUNNER, encoding="utf-8")
+
+        libs = collect_non_glibc_libs(STL_SERVER_BIN)
+        with tarfile.open(tar_path, "w") as tf:
+            tf.add(STL_SERVER_BIN, arcname="stl_native_server")
+            tf.add(runner_path, arcname="in_container_pxe_runner.py")
+            tf.add(CONTRACTS_PATH, arcname="contracts/firmware-vd012.json")
+            tf.add(WEB_DIR / "index.html", arcname="web/index.html")
+            for soname, real_path in libs:  # type: ignore[misc]
+                tf.add(real_path, arcname=f"libs/{soname}")
+
+        try:
+            # Upload tarball to remote tmp dir
+            with open(tar_path, "rb") as fp:
+                subprocess.run(
+                    [
+                        "ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}",
+                        f"mkdir -p {remote_dir} && tar -xf - -C {remote_dir} && "
+                        f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/code.fd {remote_dir}/code.fd && "
+                        f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/vars.fd {remote_dir}/vars.fd && "
+                        f"cp /opt/edk2-uefi-lab/work/qemu/memtest86plus/mt86plus.efi {remote_dir}/mt86plus.efi",
+                    ],
+                    stdin=fp,
+                    check=True,
+                    timeout=60,
+                )
+
+            print("[Tier3B] Executing isolated L2 LAN (Competing Router + ProxyDHCP + Office PC + 100% Diskless KVM OVMF)...", flush=True)
+            run_cmd = (
+                f"podman run --rm --name {run_tag} "
+                f"--privileged --network=none "
+                f"--device /dev/kvm --device /dev/net/tun "
+                f"-v {remote_dir}:/sim:rw "
+                f"{PODMAN_IMAGE} "
+                f"python3 /sim/in_container_pxe_runner.py"
+            )
+            proc = subprocess.run(
+                ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", run_cmd],
+                capture_output=True,
+                text=True,
+                timeout=120,
+            )
+            if proc.returncode != 0 or "TIER3B_SUCCESS" not in proc.stdout:
+                raise RuntimeError(
+                    f"Tier3B Diskless KVM PXE failed (rc={proc.returncode}):\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}"
+                )
+
+            res_raw = subprocess.run(
+                ["ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}", f"cat {remote_dir}/tier3b_result.json"],
+                check=True,
+                capture_output=True,
+                text=True,
+                timeout=15,
+            ).stdout
+            inner = json.loads(res_raw)
+        finally:
+            subprocess.run(
+                [
+                    "ssh", "-o", "BatchMode=yes", f"{REMOTE_USER}@{REMOTE_HOST}",
+                    f"podman rm -f {run_tag} >/dev/null 2>&1 || true; rm -rf {remote_dir}",
+                ],
+                timeout=15,
+                capture_output=True,
+            )
+
+    elapsed_s = round(time.monotonic() - t0, 2)
+    summary = {
+        "tier": "Tier3B_Diskless_KVM_OVMF_ProxyDHCP_CompetingRouter_E2E",
+        "ok": True,
+        "elapsed_s": elapsed_s,
+        **inner,
+    }
+    print(
+        f"[Tier3B] 100% DISKLESS KVM+OVMF PXE UNDER COMPETING LAN DHCP ROUTER PASSED in {elapsed_s}s!\n"
+        f"         OfficePC -> {inner['office_pc_offer']['from']} ({inner['office_pc_offer']['yiaddr']}), "
+        f"ignored_non_pxe={inner['packets_ignored_non_pxe']}\n"
+        f"         Diskless VM -> Router IP + ProxyDHCP 10.99.77.1 -> TFTP 118.efi ({inner['efi_bytes']}B) downloaded & booted!",
+        flush=True,
+    )
+    return summary
+
+
+if __name__ == "__main__":
+    res = run_tier3b_diskless_pxe()
+    out_file = ROOT_DIR / "build" / "sim" / "tier3b_diskless_pxe_report.json"
+    out_file.parent.mkdir(parents=True, exist_ok=True)
+    out_file.write_text(json.dumps(res, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

+ 5 - 2
sim/run_all_tiers.py

@@ -198,12 +198,15 @@ def main() -> None:
     tiers.append(run_tier1(skip_native_rebuild=args.skip_native_rebuild))
     tiers.append(run_tier1(skip_native_rebuild=args.skip_native_rebuild))
     tiers.append(run_step("Tier2 Multi-Station HIL Full-Stack E2E", [PY_BIN, str(ROOT_DIR / "sim" / "hil_cluster" / "test_tier2_hil_e2e.py")], timeout_s=360))
     tiers.append(run_step("Tier2 Multi-Station HIL Full-Stack E2E", [PY_BIN, str(ROOT_DIR / "sim" / "hil_cluster" / "test_tier2_hil_e2e.py")], timeout_s=360))
     if not args.skip_kvm:
     if not args.skip_kvm:
-        tiers.append(run_step("Tier3 Real KVM + OVMF UEFI + mt86plus.efi E2E", [PY_BIN, str(ROOT_DIR / "sim" / "kvm_uefi_tier" / "test_tier3_kvm_uefi_e2e.py")], timeout_s=300))
+        tiers.append(run_step("Tier3A Real KVM + OVMF UEFI + mt86plus.efi E2E", [PY_BIN, str(ROOT_DIR / "sim" / "kvm_uefi_tier" / "test_tier3_kvm_uefi_e2e.py")], timeout_s=300))
+        tiers.append(run_step("Tier3B Real 100% Diskless KVM+OVMF ProxyDHCP under Competing LAN Router", [PY_BIN, str(ROOT_DIR / "sim" / "kvm_uefi_tier" / "test_tier3b_diskless_pxe.py")], timeout_s=240))
     tiers.append(run_step("Tier4 Headless Chrome 156 CDP Web E2E", [PY_BIN, str(ROOT_DIR / "sim" / "web_e2e" / "test_tier4_chrome_web_e2e.py")], timeout_s=300))
     tiers.append(run_step("Tier4 Headless Chrome 156 CDP Web E2E", [PY_BIN, str(ROOT_DIR / "sim" / "web_e2e" / "test_tier4_chrome_web_e2e.py")], timeout_s=300))
+    tiers.append(run_step("Tier5 6-Tier ISA Kernels & 200-Station Scale Benchmark", [PY_BIN, str(ROOT_DIR / "sim" / "bench_scale_performance.py")], timeout_s=240))
 
 
     total_s = round(time.monotonic() - t_all, 2)
     total_s = round(time.monotonic() - t_all, 2)
     report = {
     report = {
-        "schema": "xjkj-stl-4tier-web-only-sim-v2",
+        "schema": "xjkj-stl-5tier-full-sim-v3",
+        "version": (ROOT_DIR / "VERSION").read_text(encoding="utf-8").strip(),
         "completed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
         "completed_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
         "all_passed": True,
         "all_passed": True,
         "total_elapsed_s": total_s,
         "total_elapsed_s": total_s,

+ 64 - 4
sim/web_e2e/test_tier4_chrome_web_e2e.py

@@ -258,7 +258,7 @@ async def run_tier4_web_suite() -> Dict[str, Any]:
                     """(() => {
                     """(() => {
                         document.getElementById('wd-link-lost-s').value = '180';
                         document.getElementById('wd-link-lost-s').value = '180';
                         document.getElementById('wd-dense-silence-s').value = '95';
                         document.getElementById('wd-dense-silence-s').value = '95';
-                        document.getElementById('wd-reboot-on-hang').checked = true;
+                        document.getElementById('wd-hang-action').value = 'retry_current_task';
                         document.getElementById('wd-max-hangs').value = '3';
                         document.getElementById('wd-max-hangs').value = '3';
                         document.getElementById('btn-save-watchdog').click();
                         document.getElementById('btn-save-watchdog').click();
                         return true;
                         return true;
@@ -268,7 +268,7 @@ async def run_tier4_web_suite() -> Dict[str, Any]:
                 async def _wd_persisted():
                 async def _wd_persisted():
                     ctrl = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
                     ctrl = await stack.admin_ws.call("GetStationControl", {"station_id": "S1"})
                     wd = ctrl.get("watchdog") or {}
                     wd = ctrl.get("watchdog") or {}
-                    return wd if wd.get("link_lost_timeout_ms") == 180000 and wd.get("dense_stage_silence_timeout_ms") == 95000 and wd.get("max_consecutive_hangs") == 3 else None
+                    return wd if wd.get("link_lost_timeout_ms") == 180000 and wd.get("dense_stage_silence_timeout_ms") == 95000 and wd.get("hang_action") == "retry_current_task" and wd.get("max_consecutive_hangs") == 3 else None
 
 
                 await wait_until(_wd_persisted, timeout_s=8.0, desc="Watchdog config persisted via Web UI")
                 await wait_until(_wd_persisted, timeout_s=8.0, desc="Watchdog config persisted via Web UI")
                 # Switch back to Overview tab (`overview`)
                 # Switch back to Overview tab (`overview`)
@@ -363,7 +363,7 @@ async def run_tier4_web_suite() -> Dict[str, Any]:
 
 
                 hang_dom = await wait_until(_dom_hang_alert, timeout_s=25.0, desc="Chrome #watchdog-alert-banner stage_hang_timeout")
                 hang_dom = await wait_until(_dom_hang_alert, timeout_s=25.0, desc="Chrome #watchdog-alert-banner stage_hang_timeout")
                 assert "stage_hang_timeout" in hang_dom["wdText"]
                 assert "stage_hang_timeout" in hang_dom["wdText"]
-                assert "主板保持死机现场" in hang_dom["wdText"]
+                assert "保留死机现场" in hang_dom["wdText"]
                 assert "0x08 00" in hang_dom["wdText"]
                 assert "0x08 00" in hang_dom["wdText"]
                 assert hang_dom["dimmBannerVisible"] is True, f"G27 regression: #dimm-replacement-banner hidden on hang fault! {hang_dom}"
                 assert hang_dom["dimmBannerVisible"] is True, f"G27 regression: #dimm-replacement-banner hidden on hang fault! {hang_dom}"
                 assert not cdp.js_exceptions, f"Uncaught JS exceptions during Web E2E: {cdp.js_exceptions}"
                 assert not cdp.js_exceptions, f"Uncaught JS exceptions during Web E2E: {cdp.js_exceptions}"
@@ -484,12 +484,72 @@ async def run_tier4_web_suite() -> Dict[str, Any]:
                 assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 6: {cdp.js_exceptions}"
                 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")})
                 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)
                 print(f"      -> PASS (fe_events={trace_st.get('frontend_events_ingested')}, tar={tar_ok.get('size')}B)", flush=True)
+
+                # ============================================================
+                # Scenario 7: Phase 4 Built-in PXE/ProxyDHCP UI, Full BMC Sensor Table & Console-Expand Tab Fix
+                # ============================================================
+                print("[Tier4][7/7] Verifying Phase 4 BMC Full Sensor Table, Console-Expand Tab Fix & Built-in PXE/ProxyDHCP UI...", flush=True)
+                # 7a. Full BMC sensor table on Overview shows Voltage/Fan/Power from live RMCP+ SDR
+                bmc_dom = await wait_until(
+                    lambda: cdp.eval_js(
+                        """(() => {
+                            const tb = document.getElementById('bmc-sensors-tbody');
+                            if (!tb) return null;
+                            const txt = tb.textContent || '';
+                            return (txt.includes('P12V') && txt.includes('FAN1_RPM') && txt.includes('PSU1_PIN_W')) ? txt.length : null;
+                        })()"""
+                    ),
+                    timeout_s=10.0,
+                    desc="BMC full sensor table (P12V, FAN1_RPM, PSU1_PIN_W) in Chrome",
+                )
+                assert bmc_dom and bmc_dom > 50
+                # 7b. Console expand on Overview must NOT hide Testing page when switching tabs!
+                await cdp.eval_js(
+                    """(() => {
+                        document.getElementById('btn-console-expand')?.click();
+                        document.querySelector('[data-page="testing"]')?.click();
+                        return true;
+                    })()"""
+                )
+                pxe_ui_ok = await wait_until(
+                    lambda: cdp.eval_js(
+                        """(() => {
+                            const left = document.querySelector('.workspace-left');
+                            const card = document.getElementById('pxe-dhcp-card');
+                            const modeSel = document.getElementById('pxe-dhcp-mode');
+                            const portTxt = document.getElementById('pxe-port-status')?.textContent || '';
+                            if (!left || !card || !modeSel) return null;
+                            const visible = getComputedStyle(left).display !== 'none';
+                            return (visible && portTxt.includes('HTTP Boot:')) ? { visible, mode: modeSel.value, portTxt } : null;
+                        })()"""
+                    ),
+                    timeout_s=8.0,
+                    desc="Built-in PXE/ProxyDHCP panel visible after console-expand tab switch",
+                )
+                assert pxe_ui_ok and pxe_ui_ok.get("visible") is True
+                # 7c. Trigger 1-click LAN DHCP/PXE self-check in Chrome and verify result renders
+                await cdp.eval_js("document.getElementById('btn-probe-pxe-network')?.click(); true")
+                probe_txt = await wait_until(
+                    lambda: cdp.eval_js(
+                        """(() => {
+                            const b = document.getElementById('pxe-probe-result');
+                            if (!b || b.classList.contains('hidden')) return null;
+                            return b.textContent.includes('诊断结论:') ? b.textContent : null;
+                        })()"""
+                    ),
+                    timeout_s=10.0,
+                    desc="LAN DHCP/PXE self-check output in Chrome",
+                )
+                assert "诊断结论:" in probe_txt
+                assert not cdp.js_exceptions, f"Uncaught JS exceptions during Scenario 7: {cdp.js_exceptions}"
+                results.append({"scenario": "7_phase4_bmc_sensors_console_tab_fix_and_builtin_pxe_ui", "status": "PASS"})
+                print("      -> PASS", 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 6 HEADLESS CHROME 156 WEB E2E SCENARIOS PASSED in {elapsed_s}s!", flush=True)
+        print(f"\n[Tier4] ALL 7 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:

+ 1 - 1
web/amt-controls.js

@@ -240,5 +240,5 @@
     api.bind('btn-reload-amt',async()=>{const id=api.stationId();await window.stlFirmware.refresh();drafts.delete(id);formStation='';render();});
     api.bind('btn-reload-amt',async()=>{const id=api.stationId();await window.stlFirmware.refresh();drafts.delete(id);formStation='';render();});
     fill();
     fill();
   }
   }
-  window.stlAmt={init,render,isDirty:()=>!!current()?.dirty};
+  window.stlAmt={init,render,isDirty:()=>!!current()?.dirty,resetDrafts:()=>{drafts.clear();formStation='';}};
 })();
 })();

+ 64 - 15
web/app.js

@@ -542,7 +542,33 @@
     }
     }
   }
   }
 
 
-  function renderDimms(s) { window.stlDimms?.render(window.stlFirmware.snapshot(s.station_id) || {}); }
+  function renderBmcSensors(s) {
+    const tbody = $('bmc-sensors-tbody');
+    if (!tbody) return;
+    const ctrl = window.stlFirmware.snapshot(s?.station_id || stationId) || {};
+    const sensors = Array.isArray(ctrl.bmc_sensors) ? ctrl.bmc_sensors : [];
+    const cnt = $('bmc-sensors-count');
+    if (cnt) cnt.textContent = `${sensors.length} 项`;
+    const sig = JSON.stringify(sensors);
+    if (tbody.dataset.sig === sig) return;
+    tbody.dataset.sig = sig;
+    const catMap = { temp: '温度', temperature: '温度', voltage: '电压', fan: '风扇', current: '电流', power: '功率', discrete: '离散状态', other: '其他' };
+    tbody.innerHTML = sensors.map(item => {
+      const valTxt = typeof item.value === 'number' && Number.isFinite(item.value)
+        ? `${Number.isInteger(item.value) ? item.value : item.value.toFixed(2)} ${item.unit || ''}`.trim()
+        : (item.status || item.raw_hex || '-');
+      const stLower = String(item.status || '').toLowerCase();
+      const isOk = !stLower || stLower === 'ok' || stLower === 'nominal' || stLower.includes('ok');
+      const isBad = stLower.includes('crit') || stLower.includes('fail') || stLower.includes('warn') || stLower.includes('non-rec');
+      const stCls = isBad ? 'error' : isOk ? 'connected' : '';
+      return `<tr><td><code>${escape(item.name || '-')}</code></td><td>${escape(catMap[item.category] || item.sensor_type || item.category || '-')}</td><td><strong>${escape(valTxt)}</strong></td><td><span class="badge ${stCls}">${escape(item.status || 'OK')}</span></td></tr>`;
+    }).join('') || '<tr><td colspan="4">等待 BMC SDR 全量采集数据...</td></tr>';
+  }
+
+  function renderDimms(s) {
+    window.stlDimms?.render(window.stlFirmware.snapshot(s.station_id) || {});
+    renderBmcSensors(s);
+  }
 
 
   function renderBoot(s, d) {
   function renderBoot(s, d) {
     const control = window.stlFirmware.snapshot(s.station_id) || {};
     const control = window.stlFirmware.snapshot(s.station_id) || {};
@@ -712,6 +738,9 @@
       $('sys-mode').textContent = info.mode === 'hardware' ? '硬件实机' : (info.mode || '未知');
       $('sys-mode').textContent = info.mode === 'hardware' ? '硬件实机' : (info.mode || '未知');
       $('sys-heartbeat').textContent = stamp();
       $('sys-heartbeat').textContent = stamp();
       $('refresh-indicator').textContent = 'WebSocket 已连接';
       $('refresh-indicator').textContent = 'WebSocket 已连接';
+      const authOn = info.web_auth_enabled !== false;
+      $('btn-change-password')?.classList.toggle('hidden', !authOn);
+      $('btn-web-logout')?.classList.toggle('hidden', !authOn);
       if (!lightweight || !stations.length) {
       if (!lightweight || !stations.length) {
         stations = list.stations || [];
         stations = list.stations || [];
         window.stlStore?.set?.('stations', stations, 'poll');
         window.stlStore?.set?.('stations', stations, 'poll');
@@ -735,7 +764,6 @@
         }
         }
       }
       }
       window.stlStore?.set?.('stationId', stationId, 'sync');
       window.stlStore?.set?.('stationId', stationId, 'sync');
-      renderCards();
       const curPage = window.stlNavigation?.current?.() || 'overview';
       const curPage = window.stlNavigation?.current?.() || 'overview';
       const tasks = [pollDiagnostic(), window.stlFirmware.refresh(), pollAlarms()];
       const tasks = [pollDiagnostic(), window.stlFirmware.refresh(), pollAlarms()];
       if (curPage === 'records' || curPage === 'queue' || pending.size > 0) {
       if (curPage === 'records' || curPage === 'queue' || pending.size > 0) {
@@ -745,8 +773,8 @@
         tasks.push(pollDeviceEvents(), pollAuditLogs());
         tasks.push(pollDeviceEvents(), pollAuditLogs());
       }
       }
       await Promise.all(tasks);
       await Promise.all(tasks);
+      renderCards();
       renderDetail();
       renderDetail();
-      window.stlUi?.renderProductionDashboard?.(stations);
     } catch (error) {
     } catch (error) {
       connected = false;
       connected = false;
       window.stlStore?.set?.('connected', false, 'poll_error');
       window.stlStore?.set?.('connected', false, 'poll_error');
@@ -949,17 +977,36 @@
     onSelectStation: sid => void selectStation(sid, true),
     onSelectStation: sid => void selectStation(sid, true),
     onStartStation: async (sid, { targetTemp, profileId }) => {
     onStartStation: async (sid, { targetTemp, profileId }) => {
       try {
       try {
-        if (targetTemp > 0) {
-          await window.stlBootPlan.awaitCommand('ConfigureThermalPolicy', {
-            station_id: sid,
-            thermal_policy: { auto_enabled: true, target_temp_c: targetTemp, require_online: true },
-          }, `设置 ${sid} 目标温度 ${targetTemp}℃`);
-        }
+        let chosenProfile = null;
         if (profileId && profileId !== '__current__') {
         if (profileId && profileId !== '__current__') {
+          const ctrl = window.stlFirmware.snapshot(sid) || {};
+          const list = Array.isArray(ctrl.saved_profiles) ? ctrl.saved_profiles : [];
+          chosenProfile = list.find(p => (p.profile_id || p.name) === profileId) || null;
           await window.stlBootPlan.awaitCommand('LoadProfileToWorkspace', { station_id: sid, profile_id: profileId }, `加载 ${sid} 配置`);
           await window.stlBootPlan.awaitCommand('LoadProfileToWorkspace', { station_id: sid, profile_id: profileId }, `加载 ${sid} 配置`);
         }
         }
-        await window.stlBootPlan.awaitCommand('ControlBootPlan', { station_id: sid, action: 'restart', skip_thermal_check: false }, `产线启动工位 ${sid}`);
-        status(`工位 ${sid} 已启动高温测试(目标 ${targetTemp}℃)。`);
+        const useTemp = Number.isFinite(Number(targetTemp)) ? Math.max(0, Math.min(254, Number(targetTemp))) : 0;
+        await window.stlBootPlan.awaitCommand('ConfigureThermalPolicy', {
+          station_id: sid,
+          thermal_policy: { auto_enabled: useTemp > 0, target_temp_c: useTemp, require_online: useTemp > 0 },
+        }, useTemp > 0 ? `设置 ${sid} 目标温度 ${useTemp}℃` : `关闭 ${sid} 自动温控`);
+        if (chosenProfile && (Number(chosenProfile.repeat) === 0 || Number(chosenProfile.repeat) > 1)) {
+          const runProf = {
+            ...JSON.parse(JSON.stringify(chosenProfile)),
+            target_temp_c: useTemp,
+            thermal_auto_enabled: useTemp > 0,
+            require_thermal_online: useTemp > 0,
+          };
+          await window.stlBootPlan.awaitCommand('SubmitTaskBatch', {
+            station_id: sid,
+            profiles: [runProf],
+            stop_on_fail: true,
+            auto_start: true,
+            skip_thermal_check: false,
+          }, `产线启动工位 ${sid} 多轮队列`);
+        } else {
+          await window.stlBootPlan.awaitCommand('ControlBootPlan', { station_id: sid, action: 'restart', skip_thermal_check: false }, `产线启动工位 ${sid}`);
+        }
+        status(useTemp > 0 ? `工位 ${sid} 已启动高温测试(目标 ${useTemp}℃)。` : `工位 ${sid} 已启动常温测试(不控温)。`);
         await poll();
         await poll();
       } catch (err) {
       } catch (err) {
         status(`工位 ${sid} 启动被拦截或失败:${err.message}`, true);
         status(`工位 ${sid} 启动被拦截或失败:${err.message}`, true);
@@ -1014,17 +1061,19 @@
       if (dirtyPollTimer) { clearTimeout(dirtyPollTimer); dirtyPollTimer = null; }
       if (dirtyPollTimer) { clearTimeout(dirtyPollTimer); dirtyPollTimer = null; }
       void poll(false);
       void poll(false);
     } else if (ev === 'station_dirty') {
     } else if (ev === 'station_dirty') {
-      if (Array.isArray(detail.stations) && detail.stations.length) {
-        stations = detail.stations;
+      const payload = detail.result || detail;
+      const stArr = Array.isArray(payload.stations) ? payload.stations : [];
+      if (stArr.length) {
+        stations = stArr;
         window.stlStore?.set?.('stations', stations, 'ws_dirty');
         window.stlStore?.set?.('stations', stations, 'ws_dirty');
         renderCards();
         renderCards();
       }
       }
-      const dirtyList = Array.isArray(detail.dirty_stations) ? detail.dirty_stations : [];
+      const dirtyList = Array.isArray(payload.dirty_stations) ? payload.dirty_stations : [];
       const curDirty = !dirtyList.length || dirtyList.includes(stationId);
       const curDirty = !dirtyList.length || dirtyList.includes(stationId);
       if (curDirty && !dirtyPollTimer) {
       if (curDirty && !dirtyPollTimer) {
         dirtyPollTimer = setTimeout(() => {
         dirtyPollTimer = setTimeout(() => {
           dirtyPollTimer = null;
           dirtyPollTimer = null;
-          void poll(Array.isArray(detail.stations) && detail.stations.length > 0);
+          void poll(stArr.length > 0);
         }, 350);
         }, 350);
       }
       }
     }
     }

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 54 - 25
web/boot-plan-controls.js


+ 148 - 6
web/firmware-controls.js

@@ -267,7 +267,7 @@
     $('connection-console-host').disabled = !enabled || transport === 'tcp_serial_server';
     $('connection-console-host').disabled = !enabled || transport === 'tcp_serial_server';
     for (const key of ['connection-bmc-host','connection-bmc-user','connection-bmc-password']) $(key).disabled = !bmcEnabled && ['tcp_serial','tcp_serial_server','local_serial'].includes(transport);
     for (const key of ['connection-bmc-host','connection-bmc-user','connection-bmc-password']) $(key).disabled = !bmcEnabled && ['tcp_serial','tcp_serial_server','local_serial'].includes(transport);
     $('connection-transport-note').textContent = transport === 'local_serial'
     $('connection-transport-note').textContent = transport === 'local_serial'
-      ? '使用控制主机本地物理串口(默认 /dev/ttyUSB0,115200 8N1 无流控;严禁使用 /dev/ttyUSB1)。不要求启用 BMC 网络连接。'
+      ? '使用控制主机本地物理串口(默认 /dev/ttyUSB0,115200 8N1 无流控,支持任意 /dev/ttyUSB* 或 /dev/serial/by-path/*)。不要求启用 BMC 网络连接。'
       : transport === 'tcp_serial'
       : transport === 'tcp_serial'
       ? 'N540 TCP Server 模式:后端直连 N540 端口(P1~P4 默认 9000~9003,经 192.168.2.61 转发至 192.168.8.8)。'
       ? 'N540 TCP Server 模式:后端直连 N540 端口(P1~P4 默认 9000~9003,经 192.168.2.61 转发至 192.168.8.8)。'
       : transport === 'tcp_serial_server'
       : transport === 'tcp_serial_server'
@@ -412,7 +412,81 @@
     if (!connectionDirty) $('connection-edit-status').textContent = '已读取配置 · 保存后立即生效(控制台在线时将自动重连)';
     if (!connectionDirty) $('connection-edit-status').textContent = '已读取配置 · 保存后立即生效(控制台在线时将自动重连)';
     document.querySelectorAll('.catalog-query, .catalog-action').forEach(button => {button.disabled = !online || !writable || observed !== 'uip';});
     document.querySelectorAll('.catalog-query, .catalog-action').forEach(button => {button.disabled = !online || !writable || observed !== 'uip';});
   }
   }
-  let pxeFormStation = '';
+  let pxeFormStation = '', pxeDhcpDirty = false, pxeStatusLoaded = false;
+
+  function updatePxeDhcpFieldsState() {
+    const mode = $('pxe-dhcp-mode')?.value || 'proxy';
+    const isoOnly = mode !== 'isolated';
+    if ($('pxe-dhcp-range-start')) $('pxe-dhcp-range-start').disabled = isoOnly;
+    if ($('pxe-dhcp-range-end')) $('pxe-dhcp-range-end').disabled = isoOnly;
+  }
+
+  function renderPxeDhcpStatus(st) {
+    if (!st || !$('pxe-dhcp-card')) return;
+    pxeStatusLoaded = true;
+    const badge = $('pxe-dhcp-live-badge');
+    const modeNames = { proxy: '同网段共存 ProxyDHCP', isolated: '独立专网 DHCP', disabled: '内置 DHCP 已关闭' };
+    if (badge) {
+      const ok = st.pxe_mode === 'disabled' || (st.dhcp67_bound && (st.pxe_mode !== 'proxy' || st.proxy4011_bound));
+      badge.textContent = `${modeNames[st.pxe_mode] || st.pxe_mode} · ${st.effective_server_ip || '-'}`;
+      badge.classList.toggle('connected', ok && st.pxe_mode !== 'disabled');
+      badge.classList.toggle('error', !ok && st.pxe_mode !== 'disabled');
+    }
+    const ifaceSel = $('pxe-dhcp-iface');
+    if (ifaceSel && Array.isArray(st.ifaces)) {
+      const sig = JSON.stringify(st.ifaces.map(i => [i.name, i.ip, i.is_up]));
+      if (ifaceSel.dataset.sig !== sig) {
+        const prev = pxeDhcpDirty ? ifaceSel.value : (st.pxe_iface || '');
+        ifaceSel.dataset.sig = sig;
+        ifaceSel.innerHTML = '<option value="">自动选择可用业务网卡</option>' + st.ifaces.map(i => `<option value="${esc(i.name)}">${esc(i.name)} (${esc(i.ip)}${i.is_up ? '' : ' · DOWN'})</option>`).join('');
+        ifaceSel.value = prev;
+      }
+    }
+    if (!pxeDhcpDirty) {
+      if ($('pxe-dhcp-mode') && st.pxe_mode) $('pxe-dhcp-mode').value = st.pxe_mode;
+      if ($('pxe-dhcp-iface')) $('pxe-dhcp-iface').value = st.pxe_iface || '';
+      if ($('pxe-dhcp-server-ip')) $('pxe-dhcp-server-ip').value = st.pxe_server_ip || '';
+      if ($('pxe-dhcp-range-start') && st.pxe_dhcp_range_start) $('pxe-dhcp-range-start').value = st.pxe_dhcp_range_start;
+      if ($('pxe-dhcp-range-end') && st.pxe_dhcp_range_end) $('pxe-dhcp-range-end').value = st.pxe_dhcp_range_end;
+      if ($('pxe-dhcp-mac-whitelist') && Array.isArray(st.pxe_mac_whitelist)) $('pxe-dhcp-mac-whitelist').value = st.pxe_mac_whitelist.join(', ');
+    }
+    updatePxeDhcpFieldsState();
+    const portEl = $('pxe-port-status');
+    if (portEl) {
+      const parts = [
+        `网卡: ${st.active_iface || 'auto'} (${st.effective_server_ip || '-'})`,
+        `UDP 67: ${st.dhcp67_bound ? '已监听' : '未监听'}`,
+        `UDP 4011: ${st.proxy4011_bound ? '已监听' : '未监听'}`,
+        `UDP 69 TFTP: ${st.tftp69_bound ? '已监听' : '未监听'}`,
+        `118.efi: ${st.efi_present ? Math.round((st.efi_bytes || 0) / 1024) + ' KiB' : '缺失'}`,
+        `HTTP Boot: ${st.http_boot_url || '-'}`,
+        `收包 ${st.packets_rx || 0} / 回复 ${st.packets_replied || 0} / 忽略非PXE ${st.packets_ignored_non_pxe || 0}`,
+      ];
+      if (st.last_error) parts.push(`错误: ${st.last_error}`);
+      portEl.textContent = parts.join(' · ');
+    }
+    const clients = Array.isArray(st.discovered_clients) ? st.discovered_clients : [];
+    if ($('pxe-clients-count')) $('pxe-clients-count').textContent = String(clients.length);
+    if ($('pxe-clients-tbody')) {
+      $('pxe-clients-tbody').innerHTML = clients.map(c => `<tr>
+        <td><code>${esc(c.mac)}</code></td>
+        <td>${esc(c.arch_label || c.arch)}</td>
+        <td>${esc(c.boot_mode)}</td>
+        <td><code>${esc(c.last_stage)}</code></td>
+        <td><code>${esc(c.last_ip || '-')}</code></td>
+        <td><code>${esc(c.boot_target || '-')}</code></td>
+        <td>${esc(c.reply_count || 0)}</td>
+      </tr>`).join('') || '<tr><td colspan="7">尚无 PXE / HTTP Boot 请求记录</td></tr>';
+    }
+  }
+
+  async function refreshPxeStatus() {
+    if (!api || !api.connected()) return;
+    try {
+      const st = await api.callApi('GetPxeStatus', {});
+      renderPxeDhcpStatus(st);
+    } catch (_) {}
+  }
 
 
   function renderPxePreviewFromDom() {
   function renderPxePreviewFromDom() {
     if (!$('pxe-stage1-preview') || !$('pxe-cfg-preview')) return;
     if (!$('pxe-stage1-preview') || !$('pxe-cfg-preview')) return;
@@ -535,7 +609,7 @@
     api = services;
     api = services;
     api.bind('btn-reload-catalog',() => refresh(true));
     api.bind('btn-reload-catalog',() => refresh(true));
     api.bind('btn-reload-connections',async () => { await refresh(); fillForms(); });
     api.bind('btn-reload-connections',async () => { await refresh(); fillForms(); });
-    for (const key of ['connection-console-enabled','connection-transport','connection-console-host','connection-console-port','connection-write-chunk-bytes','connection-write-gap-ms','connection-bmc-enabled','connection-bmc-host','connection-bmc-user','connection-bmc-password','connection-os-mac']) {
+    for (const key of ['connection-console-enabled','connection-transport','connection-console-host','connection-console-port','connection-write-chunk-bytes','connection-write-gap-ms','connection-bmc-enabled','connection-bmc-host','connection-bmc-user','connection-bmc-password','connection-os-mac','n540-http-host','n540-http-port','n540-channel','n540-mode']) {
       if ($(key)) for (const evt of ['input','change']) $(key).addEventListener(evt,() => {connectionDirty = true; $('connection-edit-status').textContent = '有未保存的连接修改'; connectionFields();});
       if ($(key)) for (const evt of ['input','change']) $(key).addEventListener(evt,() => {connectionDirty = true; $('connection-edit-status').textContent = '有未保存的连接修改'; connectionFields();});
     }
     }
     $('connection-bmc-host').addEventListener('input',() => {
     $('connection-bmc-host').addEventListener('input',() => {
@@ -553,7 +627,6 @@
     api.bind('btn-save-connections',async () => {
     api.bind('btn-save-connections',async () => {
       const transport = $('connection-transport').value, enabled = $('connection-console-enabled').checked;
       const transport = $('connection-transport').value, enabled = $('connection-console-enabled').checked;
       const hostVal = $('connection-console-host').value.trim() || (transport === 'local_serial' ? '/dev/ttyUSB0' : '');
       const hostVal = $('connection-console-host').value.trim() || (transport === 'local_serial' ? '/dev/ttyUSB0' : '');
-      if (hostVal.includes('ttyUSB1')) throw new Error('禁止使用 /dev/ttyUSB1(温控专用串口),物理串口请使用 /dev/ttyUSB0');
       const console = {enabled,transport,host:hostVal};
       const console = {enabled,transport,host:hostVal};
       const portText = $('connection-console-port').value;
       const portText = $('connection-console-port').value;
       if (transport === 'ipmi_sol' || transport === 'local_serial') console.port = 0;
       if (transport === 'ipmi_sol' || transport === 'local_serial') console.port = 0;
@@ -827,6 +900,66 @@
         if ($('pxe-save-status')) $('pxe-save-status').textContent = '已生效:118.efi';
         if ($('pxe-save-status')) $('pxe-save-status').textContent = '已生效:118.efi';
       });
       });
     }
     }
+    for (const pid of ['pxe-dhcp-mode','pxe-dhcp-iface','pxe-dhcp-server-ip','pxe-dhcp-range-start','pxe-dhcp-range-end','pxe-dhcp-mac-whitelist']) {
+      if ($(pid)) $(pid).addEventListener(pid.includes('mode') || pid.includes('iface') ? 'change' : 'input', () => {
+        pxeDhcpDirty = true;
+        updatePxeDhcpFieldsState();
+        if ($('pxe-dhcp-save-note')) $('pxe-dhcp-save-note').textContent = '有未保存的引导服务修改';
+      });
+    }
+    if ($('btn-save-pxe-dhcp')) {
+      api.bind('btn-save-pxe-dhcp', async () => {
+        const wlRaw = ($('pxe-dhcp-mac-whitelist')?.value || '').trim();
+        const wl = wlRaw ? wlRaw.split(/[\s,;]+/).filter(Boolean) : [];
+        const res = await api.callApi('ConfigurePxe', {
+          pxe_mode: $('pxe-dhcp-mode')?.value || 'proxy',
+          pxe_iface: ($('pxe-dhcp-iface')?.value || '').trim(),
+          pxe_server_ip: ($('pxe-dhcp-server-ip')?.value || '').trim(),
+          pxe_dhcp_range_start: ($('pxe-dhcp-range-start')?.value || '').trim(),
+          pxe_dhcp_range_end: ($('pxe-dhcp-range-end')?.value || '').trim(),
+          pxe_mac_whitelist: wl,
+        });
+        pxeDhcpDirty = false;
+        renderPxeDhcpStatus(res);
+        if ($('pxe-dhcp-save-note')) $('pxe-dhcp-save-note').textContent = '已热生效(无需重启服务)';
+        api.status('内置 PXE / ProxyDHCP 引导服务配置已生效。');
+      });
+    }
+    if ($('btn-refresh-pxe-status')) {
+      api.bind('btn-refresh-pxe-status', async () => {
+        pxeDhcpDirty = false;
+        await refreshPxeStatus();
+        api.status('已刷新内置引导服务状态。');
+      });
+    }
+    if ($('btn-probe-pxe-network')) {
+      api.bind('btn-probe-pxe-network', async () => {
+        const box = $('pxe-probe-result');
+        if (box) { box.classList.remove('hidden', 'is-ok', 'is-warn'); box.textContent = '正在向局域网广播 PXE 探测包并检查端口与外部 DHCP 路由器(约 1 秒)...'; }
+        const res = await api.callApi('ProbePxeNetwork', {
+          iface: ($('pxe-dhcp-iface')?.value || '').trim(),
+          timeout_ms: 1000,
+        }, 12000);
+        if (box) {
+          const srvs = Array.isArray(res.external_dhcp_servers) ? res.external_dhcp_servers : [];
+          const hasConflict = !!res.has_pxe_conflict;
+          const srvLines = srvs.length
+            ? srvs.map(s => `• 发现外部 DHCP 服务器 ${s.server_ip}(分配示例 IP: ${s.offered_ip || '-'} · ${s.has_pxe_options ? '携带 PXE 引导字段 — 存在冲突!' : '普通路由 DHCP,无 PXE 字段 — 可安全使用 ProxyDHCP 共存'})`).join('\n')
+            : '• 未探测到其他外部 DHCP 服务器(如处于隔离专网,可使用「独立专网 DHCP」模式)。';
+          const lines = [
+            `探测网卡: ${res.probed_iface || '默认'} (${res.probed_ip || '-'}) · 推荐模式: ${res.recommended_mode || 'proxy'}`,
+            `诊断结论: ${res.diagnosis || '-'}`,
+            srvLines,
+          ];
+          if (res.probe_error) lines.push(`提示: ${res.probe_error}`);
+          box.classList.toggle('is-warn', hasConflict || !!res.probe_error);
+          box.classList.toggle('is-ok', !hasConflict && !res.probe_error);
+          box.style.whiteSpace = 'pre-line';
+          box.textContent = lines.join('\n');
+        }
+        api.status('局域网 DHCP / PXE 环境自检已完成。');
+      });
+    }
     // Load authoritative firmware contract from /contracts/firmware-vd012.json
     // Load authoritative firmware contract from /contracts/firmware-vd012.json
     fetch('/contracts/firmware-vd012.json').then(r => r.ok ? r.json() : null).then(data => {
     fetch('/contracts/firmware-vd012.json').then(r => r.ok ? r.json() : null).then(data => {
       if (data) {
       if (data) {
@@ -838,7 +971,16 @@
     }).catch(() => {});
     }).catch(() => {});
     fillForms();
     fillForms();
     renderPxePreviewFromDom();
     renderPxePreviewFromDom();
-    window.addEventListener('stl:page-change',() => {render(); if (api.connected()) refresh();});
+    window.addEventListener('stl:page-change', ev => {
+      render();
+      if (api.connected()) {
+        refresh();
+        if (ev.detail?.page === 'testing' || !pxeStatusLoaded) void refreshPxeStatus();
+      }
+    });
+    window.addEventListener('stl:transport-state', ev => {
+      if (ev.detail?.state === 'open') void refreshPxeStatus();
+    });
   }
   }
-  window.stlFirmware = {init,refresh,render,snapshot,saveSettings,isDirty:()=>!!draft()?.modified,catalogSnapshot:(station=currentId())=>catalogs.get(station)||window.STL_DEFAULT_CATALOG||{},capabilities:station => controls.get(station)?.capabilities || null,previewMt};
+  window.stlFirmware = {init,refresh,render,snapshot,saveSettings,refreshPxeStatus,resetDrafts:()=>{drafts.clear();formStation='';pxeFormStation='';},isDirty:()=>!!draft()?.modified,catalogSnapshot:(station=currentId())=>catalogs.get(station)||window.STL_DEFAULT_CATALOG||{},capabilities:station => controls.get(station)?.capabilities || null,previewMt};
 })();
 })();

+ 72 - 17
web/index.html

@@ -5,7 +5,7 @@
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta name="theme-color" content="#f4f7fa">
   <meta name="theme-color" content="#f4f7fa">
   <title>内存高温测试工作台 · 新见科技</title>
   <title>内存高温测试工作台 · 新见科技</title>
-  <link rel="stylesheet" href="style.css?v=1.0.0.0">
+  <link rel="stylesheet" href="style.css?v=0.9.5-preview.1">
 </head>
 </head>
 <body>
 <body>
   <header class="app-header">
   <header class="app-header">
@@ -142,6 +142,14 @@
             <div class="cpu-group"><div class="cpu-title"><span>CPU 1</span><span>通道 A — L</span></div><div class="dimm-grid" id="cpu1-grid"></div></div>
             <div class="cpu-group"><div class="cpu-title"><span>CPU 1</span><span>通道 A — L</span></div><div class="dimm-grid" id="cpu1-grid"></div></div>
             <div class="temp-legend"><span><i class="dot dot-normal"></i> &lt;65°C</span><span><i class="dot dot-warn"></i> 65–80°C</span><span><i class="dot dot-hot"></i> &gt;80°C</span><span><i class="dot dot-empty"></i> 无读数</span></div>
             <div class="temp-legend"><span><i class="dot dot-normal"></i> &lt;65°C</span><span><i class="dot dot-warn"></i> 65–80°C</span><span><i class="dot dot-hot"></i> &gt;80°C</span><span><i class="dot dot-empty"></i> 无读数</span></div>
             <details class="sensor-reference"><summary>传感器读数时间</summary><div id="bmc-temperature-reference">无记录</div></details>
             <details class="sensor-reference"><summary>传感器读数时间</summary><div id="bmc-temperature-reference">无记录</div></details>
+            <details class="sensor-reference" id="bmc-sensors-panel"><summary>BMC 全量传感器遥测(温度 / 电压 / 风扇 / 电流 / 功率 / 离散状态 · <span id="bmc-sensors-count">0 项</span>)</summary>
+              <div class="bmc-sensors-wrap">
+                <table class="bmc-sensors-table">
+                  <thead><tr><th>传感器名称</th><th>类别</th><th>数值</th><th>状态</th></tr></thead>
+                  <tbody id="bmc-sensors-tbody"><tr><td colspan="4">等待 BMC SDR 采集数据...</td></tr></tbody>
+                </table>
+              </div>
+            </details>
           </section>
           </section>
 
 
           <section class="firmware-panel alarms-panel" id="station-alarms-panel" data-pages="overview records" aria-labelledby="alarms-panel-title">
           <section class="firmware-panel alarms-panel" id="station-alarms-panel" data-pages="overview records" aria-labelledby="alarms-panel-title">
@@ -366,13 +374,60 @@
           <section class="firmware-panel pxe-control-panel" id="pxe-control-panel" data-pages="testing" aria-labelledby="pxe-panel-title">
           <section class="firmware-panel pxe-control-panel" id="pxe-control-panel" data-pages="testing" aria-labelledby="pxe-panel-title">
             <div class="panel-heading">
             <div class="panel-heading">
               <div>
               <div>
-                <h3 id="pxe-panel-title">PXE 网络引导与 MemTest86 (118.efi) 配置</h3>
-                <p>单机一体化部署 (192.168.2.68 · LAN2 eno1 192.168.0.10):内置 UDP :69 TFTP + 同机 pxednsmasq DHCP-PXE,自动分发 118.efi / mt86.cfg 并接收 HTML/XML 报告。</p>
+                <h3 id="pxe-panel-title">无盘 PXE / 同网段 ProxyDHCP / UEFI HTTP Boot 与 MemTest86 (118.efi)</h3>
+                <p>引导服务已直接内置进后端主程序:支持完全无盘仅插网线启动。默认同网段 ProxyDHCP(UDP 67/4011)与现有局域网 DHCP 路由器共存且不分配 IP;独立专网可切换为隔离 DHCP 模式;同步支持 UEFI HTTP Boot(<code>/pxe/118.efi</code>)与按 MAC 动态下发独立 <code>mt86.cfg</code>。</p>
               </div>
               </div>
               <span class="badge" id="pxe-active-badge">固定唯一正式版: 118.efi</span>
               <span class="badge" id="pxe-active-badge">固定唯一正式版: 118.efi</span>
             </div>
             </div>
+            <div class="pxe-dhcp-card" id="pxe-dhcp-card">
+              <div class="subpanel-title" style="margin-bottom:8px">
+                <strong>内置网络引导服务(UDP 67/4011 ProxyDHCP + UDP 69 TFTP + UEFI HTTP Boot)</strong>
+                <span class="badge" id="pxe-dhcp-live-badge">读取状态中...</span>
+              </div>
+              <div class="connection-form-grid">
+                <label>引导服务模式
+                  <select id="pxe-dhcp-mode">
+                    <option value="proxy" selected>同网段共存 ProxyDHCP(默认 · 局域网已有路由器 DHCP 时使用)</option>
+                    <option value="isolated">独立专网 DHCP(无外部路由器时分配 IP 并引导)</option>
+                    <option value="disabled">关闭内置 DHCP / ProxyDHCP(仅保留 TFTP 与 HTTP Boot)</option>
+                  </select>
+                </label>
+                <label>绑定监听网卡
+                  <select id="pxe-dhcp-iface"><option value="">自动选择可用业务网卡</option></select>
+                </label>
+                <label>本机引导服务器 IP(留空=自动取网卡 IP)
+                  <input id="pxe-dhcp-server-ip" value="" placeholder="留空自动识别" spellcheck="false">
+                </label>
+                <label>允许引导的 MAC 白名单(可选,逗号分隔,留空=不限)
+                  <input id="pxe-dhcp-mac-whitelist" value="" placeholder="留空允许所有 UEFI 机子" spellcheck="false">
+                </label>
+                <label>独立模式 IP 起始地址(仅 isolated 模式生效)
+                  <input id="pxe-dhcp-range-start" value="192.168.0.100" spellcheck="false">
+                </label>
+                <label>独立模式 IP 结束地址(仅 isolated 模式生效)
+                  <input id="pxe-dhcp-range-end" value="192.168.0.220" spellcheck="false">
+                </label>
+              </div>
+              <div class="th-rec-stats" id="pxe-port-status" style="margin-top:8px">正在检查 UDP 67 / 4011 / 69 与 HTTP Boot 状态...</div>
+              <div class="form-actions" style="margin-top:8px">
+                <button type="button" class="btn btn-primary btn-sm" id="btn-save-pxe-dhcp">保存并热生效引导服务设置</button>
+                <button type="button" class="btn btn-secondary btn-sm" id="btn-probe-pxe-network">局域网 DHCP / PXE 环境一键自检</button>
+                <button type="button" class="btn btn-quiet btn-sm" id="btn-refresh-pxe-status">刷新引导状态</button>
+                <span class="field-note" id="pxe-dhcp-save-note"></span>
+              </div>
+              <div class="pxe-probe-box hidden" id="pxe-probe-result"></div>
+              <details class="raw-uip-editor" style="margin-top:8px">
+                <summary>已观测到的无盘 PXE / HTTP Boot 接入客户端(<span id="pxe-clients-count">0</span> 台)</summary>
+                <div class="bmc-sensors-wrap" style="margin-top:6px">
+                  <table class="bmc-sensors-table">
+                    <thead><tr><th>MAC 地址</th><th>架构</th><th>模式</th><th>最近阶段</th><th>分配 / 来源 IP</th><th>下发引导目标</th><th>次数</th></tr></thead>
+                    <tbody id="pxe-clients-tbody"><tr><td colspan="7">尚无 PXE / HTTP Boot 请求记录</td></tr></tbody>
+                  </table>
+                </div>
+              </details>
+            </div>
             <div class="pxe-options-row">
             <div class="pxe-options-row">
-              <label class="check-label"><input type="checkbox" id="pxe-stage1-enabled"><strong>启用 ICT Stage 1 静态 PXE 命令注入(可选 · 默认不勾选,直接走标准 DHCP PXE)</strong></label>
+              <label class="check-label"><input type="checkbox" id="pxe-stage1-enabled"><strong>启用 ICT Stage 1 静态 PXE 命令注入(可选 · 默认不勾选,直接走标准 DHCP / ProxyDHCP)</strong></label>
               <label class="check-label"><input type="checkbox" id="pxe-apply-uip" checked>保存时同步更新 ICT 附加命令列表</label>
               <label class="check-label"><input type="checkbox" id="pxe-apply-uip" checked>保存时同步更新 ICT 附加命令列表</label>
               <label class="check-label"><input type="checkbox" id="pxe-sync-remote">可选外部 PXE 主机同步 IP:<input id="pxe-remote-host" value="" placeholder="留空=单机内置TFTP" style="width:140px;padding:3px 6px"></label>
               <label class="check-label"><input type="checkbox" id="pxe-sync-remote">可选外部 PXE 主机同步 IP:<input id="pxe-remote-host" value="" placeholder="留空=单机内置TFTP" style="width:140px;padding:3px 6px"></label>
             </div>
             </div>
@@ -423,14 +478,14 @@
           </details>
           </details>
           <details class="last-firmware-response hidden" id="mt-last-launch"><summary><span id="mt-last-launch-summary"></span></summary><pre id="mt-last-launch-output"></pre></details>
           <details class="last-firmware-response hidden" id="mt-last-launch"><summary><span id="mt-last-launch-summary"></span></summary><pre id="mt-last-launch-output"></pre></details>
 
 
-          <details class="firmware-panel rmt-panel hidden" id="rmt-results-panel">
+          <details class="firmware-panel rmt-panel" id="rmt-results-panel" data-pages="overview testing">
             <summary class="rmt-panel-summary"><strong>RMT 裕量结果表</strong><span id="rmt-result-summary">无记录</span></summary>
             <summary class="rmt-panel-summary"><strong>RMT 裕量结果表</strong><span id="rmt-result-summary">无记录</span></summary>
             <div id="rmt-cpu-results" class="rmt-cpu-results"></div>
             <div id="rmt-cpu-results" class="rmt-cpu-results"></div>
             <p class="field-note" id="rmt-measurement-count"></p>
             <p class="field-note" id="rmt-measurement-count"></p>
             <div class="rmt-measurements-wrap"><table class="catalog-table rmt-measurements-table"><thead><tr><th>槽位</th><th>裕量数值</th><th>原始行</th></tr></thead><tbody id="rmt-measurements"><tr><td colspan="3">无数据</td></tr></tbody></table></div>
             <div class="rmt-measurements-wrap"><table class="catalog-table rmt-measurements-table"><thead><tr><th>槽位</th><th>裕量数值</th><th>原始行</th></tr></thead><tbody id="rmt-measurements"><tr><td colspan="3">无数据</td></tr></tbody></table></div>
           </details>
           </details>
 
 
-          <details class="firmware-panel training-panel hidden" aria-labelledby="training-title">
+          <details class="firmware-panel training-panel" data-pages="overview testing" aria-labelledby="training-title">
             <summary class="rmt-panel-summary"><strong id="training-title">Training 槽位启用 / 禁用状态</strong><span class="badge" id="training-summary">未收到训练结果</span></summary>
             <summary class="rmt-panel-summary"><strong id="training-title">Training 槽位启用 / 禁用状态</strong><span class="badge" id="training-summary">未收到训练结果</span></summary>
             <div class="training-results" id="training-results" style="margin-top:10px">无记录</div>
             <div class="training-results" id="training-results" style="margin-top:10px">无记录</div>
           </details>
           </details>
@@ -814,16 +869,16 @@
 
 
     <footer class="app-footer">新见科技 · 内存测试工作台</footer>
     <footer class="app-footer">新见科技 · 内存测试工作台</footer>
   </main>
   </main>
-  <script src="trace.js?v=1.0.0.0"></script>
-  <script src="transport.js?v=1.0.0.0"></script>
-  <script src="store-and-ui.js?v=1.0.0.0"></script>
-  <script src="boot-plan-controls.js?v=1.0.0.0"></script>
-  <script src="amt-controls.js?v=1.0.0.0"></script>
-  <script src="dimm-overview.js?v=1.0.0.0"></script>
-  <script src="ui-navigation.js?v=1.0.0.0"></script>
-  <script src="firmware-controls.js?v=1.0.0.0"></script>
-  <script src="stage-progress.js?v=1.0.0.0"></script>
-  <script src="thermal-console.js?v=1.0.0.0"></script>
-  <script src="app.js?v=1.0.0.0"></script>
+  <script src="trace.js?v=0.9.5-preview.1"></script>
+  <script src="transport.js?v=0.9.5-preview.1"></script>
+  <script src="store-and-ui.js?v=0.9.5-preview.1"></script>
+  <script src="boot-plan-controls.js?v=0.9.5-preview.1"></script>
+  <script src="amt-controls.js?v=0.9.5-preview.1"></script>
+  <script src="dimm-overview.js?v=0.9.5-preview.1"></script>
+  <script src="ui-navigation.js?v=0.9.5-preview.1"></script>
+  <script src="firmware-controls.js?v=0.9.5-preview.1"></script>
+  <script src="stage-progress.js?v=0.9.5-preview.1"></script>
+  <script src="thermal-console.js?v=0.9.5-preview.1"></script>
+  <script src="app.js?v=0.9.5-preview.1"></script>
 </body>
 </body>
 </html>
 </html>

+ 15 - 4
web/stage-progress.js

@@ -33,9 +33,10 @@
     Object.assign(container.dataset, {source:station.run_id ? 'run' : 'diagnostic',runId:station.run_id || '',context:live ? 'current' : 'historical_session',bootId:progress.boot_id || '',mainPhase:main.id || 'unknown'});
     Object.assign(container.dataset, {source:station.run_id ? 'run' : 'diagnostic',runId:station.run_id || '',context:live ? 'current' : 'historical_session',bootId:progress.boot_id || '',mainPhase:main.id || 'unknown'});
     const stageErrors = firmware.stage_errors || {};
     const stageErrors = firmware.stage_errors || {};
     container.innerHTML = stages.map(row => {
     container.innerHTML = stages.map(row => {
-      const observed = row.state !== 'unobserved', current = row.state === 'current';
-      const status = current ? live ? '已到此阶段' : '最后到达' : observed ? '已观测' : '未观测';
-      const details = count(row.step_count) ? `${count(row.step_count)} 个步骤 · 结束 ${count(row.completed_count)}` : '尚无步骤记录';
+      const isSkipped = row.state === 'skipped';
+      const observed = row.state !== 'unobserved' && !isSkipped, current = row.state === 'current';
+      const status = isSkipped ? '已跳过 (未启用)' : current ? (live ? '已到此阶段' : '最后到达') : observed ? '已观测' : '未观测';
+      const details = isSkipped ? '本轮未执行 RMT 扫描' : (count(row.step_count) ? `${count(row.step_count)} 个步骤 · 结束 ${count(row.completed_count)}` : '尚无步骤记录');
       const errRecords = list(stageErrors[row.id]).length;
       const errRecords = list(stageErrors[row.id]).length;
       const issues = (count(row.failed_count) || errRecords) ? ` · 异常 ${Math.max(count(row.failed_count), errRecords)}` : '';
       const issues = (count(row.failed_count) || errRecords) ? ` · 异常 ${Math.max(count(row.failed_count), errRecords)}` : '';
       return `<div class="boot-stage ${observed ? 'observed' : ''} ${current && live ? 'current' : ''}" data-phase="${esc(row.id)}" data-stage-state="${esc(row.state)}"><div class="boot-stage-name">${esc(row.label || row.id)}<span class="boot-stage-state">${status}</span></div><div class="boot-stage-time">${details}${issues}</div></div>`;
       return `<div class="boot-stage ${observed ? 'observed' : ''} ${current && live ? 'current' : ''}" data-phase="${esc(row.id)}" data-stage-state="${esc(row.state)}"><div class="boot-stage-name">${esc(row.label || row.id)}<span class="boot-stage-state">${status}</span></div><div class="boot-stage-time">${details}${issues}</div></div>`;
@@ -65,10 +66,14 @@
       ];
       ];
       compStrip.innerHTML = '<strong style="color:#475569">7 阶段独立完成判定:</strong>' + compDefs.map(([key, labelText]) => {
       compStrip.innerHTML = '<strong style="color:#475569">7 阶段独立完成判定:</strong>' + compDefs.map(([key, labelText]) => {
         const isMtFail = key === 'mt_pass_complete' && sc.mt_fail_complete === true && sc[key] !== true;
         const isMtFail = key === 'mt_pass_complete' && sc.mt_fail_complete === true && sc[key] !== true;
+        const isRmtSkipped = key === 'rmt_complete' && (sc.rmt_status === 'skipped' || firmware.rmt_status === 'skipped') && sc[key] !== true;
         const done = sc[key] === true;
         const done = sc[key] === true;
         if (isMtFail) {
         if (isMtFail) {
           return `<span class="badge error" data-completion-flag="mt_fail_complete" style="background:#fee2e2;color:#991b1b;border-color:#fca5a5">✗ 7. MT FAIL</span>`;
           return `<span class="badge error" data-completion-flag="mt_fail_complete" style="background:#fee2e2;color:#991b1b;border-color:#fca5a5">✗ 7. MT FAIL</span>`;
         }
         }
+        if (isRmtSkipped) {
+          return `<span class="badge" data-completion-flag="rmt_skipped" style="background:#f1f5f9;color:#64748b;border-color:#cbd5e1">— 3. RMT 已跳过</span>`;
+        }
         return `<span class="badge ${done ? 'connected' : ''}" data-completion-flag="${esc(key)}" style="${done ? 'background:#dcfce7;color:#166534;border-color:#86efac' : 'opacity:0.75'}">${done ? '✓ ' : '○ '}${esc(labelText)}</span>`;
         return `<span class="badge ${done ? 'connected' : ''}" data-completion-flag="${esc(key)}" style="${done ? 'background:#dcfce7;color:#166534;border-color:#86efac' : 'opacity:0.75'}">${done ? '✓ ' : '○ '}${esc(labelText)}</span>`;
       }).join('');
       }).join('');
     }
     }
@@ -124,11 +129,17 @@
         wdBanner.className = '';
         wdBanner.className = '';
         wdBanner.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;margin-bottom:8px;background:#fef2f2;border:1px solid #dc2626;border-radius:6px;color:#991b1b;font-size:13px;flex-wrap:wrap';
         wdBanner.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;margin-bottom:8px;background:#fef2f2;border:1px solid #dc2626;border-radius:6px;color:#991b1b;font-size:13px;flex-wrap:wrap';
         wdBanner.dataset.alertKind = faultCode;
         wdBanner.dataset.alertKind = faultCode;
+        const hangAct = wd.hang_action || (wd.reboot_on_hang ? 'retry_current_task' : 'stop');
+        const hangActBadge = preserved
+          ? '🔒 已停机保留死机现场(未自动重启,可查最后串口/SEL)'
+          : hangAct === 'restart_full_plan'
+          ? '🔄 已触发自动重启 · 从头重做整个测试计划'
+          : '🔄 已触发自动重启 · 重新执行当前未完成的完整任务';
         wdBanner.innerHTML = `<div>
         wdBanner.innerHTML = `<div>
           <strong>${esc(faultTitles[faultCode] || ('🛑 保护规则触发 (' + faultCode + ')'))}</strong>
           <strong>${esc(faultTitles[faultCode] || ('🛑 保护规则触发 (' + faultCode + ')'))}</strong>
           <div style="margin-top:3px;font-size:12px">${esc(faultMsg)}</div>
           <div style="margin-top:3px;font-size:12px">${esc(faultMsg)}</div>
           <div style="margin-top:4px;display:flex;gap:6px;flex-wrap:wrap;font-size:12px">
           <div style="margin-top:4px;display:flex;gap:6px;flex-wrap:wrap;font-size:12px">
-            <span class="badge error" style="background:#fee2e2;color:#991b1b;border-color:#fca5a5">${preserved ? '🔒 主板保持死机现场(默认未发 BMC 重启,可查最后串口/SEL)' : '🔄 已触发无人值守自动复位恢复'}</span>
+            <span class="badge error" style="background:#fee2e2;color:#991b1b;border-color:#fca5a5">${hangActBadge}</span>
             <span class="badge" style="background:#eff6ff;color:#1d4ed8;border-color:#93c5fd">❄️ 已推送 task_complete 联动高温罩停热吹扫 (0x08 00)</span>
             <span class="badge" style="background:#eff6ff;color:#1d4ed8;border-color:#93c5fd">❄️ 已推送 task_complete 联动高温罩停热吹扫 (0x08 00)</span>
             ${serialGap ? `<span class="badge" style="background:#fef3c7;color:#92400e;border-color:#fcd34d">⚠️ 期间曾发生 ${gapCount} 次串口断联 (${gapSec}s)</span>` : ''}
             ${serialGap ? `<span class="badge" style="background:#fef3c7;color:#92400e;border-color:#fcd34d">⚠️ 期间曾发生 ${gapCount} 次串口断联 (${gapSec}s)</span>` : ''}
           </div>
           </div>

+ 34 - 5
web/store-and-ui.js

@@ -102,6 +102,7 @@
 
 
   // ---- Single-DIMM Temperature Curve Modal ----
   // ---- Single-DIMM Temperature Curve Modal ----
   let curveState = { stationId: 'S1', slot: 0, label: 'CPU0 CH A' };
   let curveState = { stationId: 'S1', slot: 0, label: 'CPU0 CH A' };
+  let curveRefreshTimer = null;
 
 
   function drawDimmCurveCanvas(canvas, points) {
   function drawDimmCurveCanvas(canvas, points) {
     if (!canvas) return;
     if (!canvas) return;
@@ -126,7 +127,7 @@
       ctx.fillStyle = '#64748b';
       ctx.fillStyle = '#64748b';
       ctx.font = '13px sans-serif';
       ctx.font = '13px sans-serif';
       ctx.textAlign = 'center';
       ctx.textAlign = 'center';
-      ctx.fillText('当前高温罩会话尚未采集到该槽位温度数据(需连接高温罩 MCU 0x82)', w / 2, h / 2);
+      ctx.fillText('当前尚未采集到该槽位温度数据(接入高温罩 MCU 0x82 或 BMC SDR 后自动记录)', w / 2, h / 2);
       return;
       return;
     }
     }
 
 
@@ -199,9 +200,10 @@
         const minV = Math.min(...vals), maxV = Math.max(...vals);
         const minV = Math.min(...vals), maxV = Math.max(...vals);
         const avgV = vals.reduce((a, b) => a + b, 0) / vals.length;
         const avgV = vals.reduce((a, b) => a + b, 0) / vals.length;
         const curV = vals[vals.length - 1];
         const curV = vals[vals.length - 1];
-        $('dimm-curve-stats').textContent = `采样点 ${pts.length} · 当前 ${curV.toFixed(1)}°C · 最低 ${minV.toFixed(1)}°C · 最高 ${maxV.toFixed(1)}°C · 均值 ${avgV.toFixed(1)}°C`;
+        const srcTag = data.source === 'bmc_sdr_fallback' ? ' · 来源: BMC SDR' : ' · 来源: MCU 0x82';
+        $('dimm-curve-stats').textContent = `采样点 ${pts.length} · 当前 ${curV.toFixed(1)}°C · 最低 ${minV.toFixed(1)}°C · 最高 ${maxV.toFixed(1)}°C · 均值 ${avgV.toFixed(1)}°C${srcTag}`;
       } else {
       } else {
-        $('dimm-curve-stats').textContent = '暂无该槽位历史温度采样点(连接高温罩并开启采集后自动记录)';
+        $('dimm-curve-stats').textContent = '暂无该槽位历史温度采样点(连接高温罩或启用 BMC 温度轮询后自动记录)';
       }
       }
       drawDimmCurveCanvas($('dimm-curve-canvas'), pts);
       drawDimmCurveCanvas($('dimm-curve-canvas'), pts);
     } catch (err) {
     } catch (err) {
@@ -218,9 +220,22 @@
     curveState = { stationId, slot: slotIdx, label: slotLabel || `CPU${cpu} CH ${ch}` };
     curveState = { stationId, slot: slotIdx, label: slotLabel || `CPU${cpu} CH ${ch}` };
     modal.classList.remove('hidden');
     modal.classList.remove('hidden');
     void refreshDimmCurve();
     void refreshDimmCurve();
+    if (curveRefreshTimer) clearInterval(curveRefreshTimer);
+    curveRefreshTimer = setInterval(() => {
+      if (modal.classList.contains('hidden')) {
+        clearInterval(curveRefreshTimer);
+        curveRefreshTimer = null;
+        return;
+      }
+      void refreshDimmCurve();
+    }, 2000);
   }
   }
 
 
   function closeDimmCurveModal() {
   function closeDimmCurveModal() {
+    if (curveRefreshTimer) {
+      clearInterval(curveRefreshTimer);
+      curveRefreshTimer = null;
+    }
     $('stl-dimm-curve-modal')?.classList.add('hidden');
     $('stl-dimm-curve-modal')?.classList.add('hidden');
   }
   }
 
 
@@ -242,6 +257,7 @@
   // ---- Production Dashboard Renderer (Unlimited Dynamic Stations) ----
   // ---- Production Dashboard Renderer (Unlimited Dynamic Stations) ----
   let prodCallbacks = {};
   let prodCallbacks = {};
   const prodTargetDraft = new Map();
   const prodTargetDraft = new Map();
+  const prodProfileDraft = new Map();
 
 
   function renderProductionDashboard(stations = []) {
   function renderProductionDashboard(stations = []) {
     const grid = $('prod-stations-grid');
     const grid = $('prod-stations-grid');
@@ -257,6 +273,10 @@
         `<span class="badge" style="background:#dcfce7;color:#166534;border-color:#86efac">PASS ${passed}</span>` +
         `<span class="badge" style="background:#dcfce7;color:#166534;border-color:#86efac">PASS ${passed}</span>` +
         `<span class="badge ${failed ? 'error' : ''}">异常 / FAIL ${failed}</span>`;
         `<span class="badge ${failed ? 'error' : ''}">异常 / FAIL ${failed}</span>`;
     }
     }
+    const activeEl = document.activeElement;
+    if (activeEl && grid.contains(activeEl) && (activeEl.matches('[data-prod-target]') || activeEl.matches('[data-prod-profile]'))) {
+      return;
+    }
 
 
     grid.innerHTML = stations.map(s => {
     grid.innerHTML = stations.map(s => {
       const sid = s.station_id;
       const sid = s.station_id;
@@ -286,8 +306,12 @@
         return `<button type="button" class="prod-dimm-cell is-${esc(st)}" data-prod-curve="${esc(sid)}:${d.slot}" title="${esc(sid)} CPU${d.slot < 12 ? 0 : 1} CH ${ch} · ${esc(st.toUpperCase())}${tVal ? ' · ' + tVal + 'C' : ''}(点击查看单槽温度曲线)"><b>${ch}</b><span>${esc(tVal || (st === 'pass' ? 'OK' : st === 'fail' ? 'NG' : '-'))}</span></button>`;
         return `<button type="button" class="prod-dimm-cell is-${esc(st)}" data-prod-curve="${esc(sid)}:${d.slot}" title="${esc(sid)} CPU${d.slot < 12 ? 0 : 1} CH ${ch} · ${esc(st.toUpperCase())}${tVal ? ' · ' + tVal + 'C' : ''}(点击查看单槽温度曲线)"><b>${ch}</b><span>${esc(tVal || (st === 'pass' ? 'OK' : st === 'fail' ? 'NG' : '-'))}</span></button>`;
       }).join('')}</div>`;
       }).join('')}</div>`;
       const alarmCnt = Number(s.alarm_count || 0);
       const alarmCnt = Number(s.alarm_count || 0);
-      const profOptions = `<option value="__current__">当前工位激活配置</option>` +
-        profiles.map(p => `<option value="${esc(p.profile_id || p.name)}">${esc(p.name)} (×${p.repeat === 0 ? '无限' : (p.repeat || 1)})</option>`).join('');
+      const chosenProf = prodProfileDraft.get(sid) || '__current__';
+      const profOptions = `<option value="__current__" ${chosenProf === '__current__' ? 'selected' : ''}>当前工位激活配置</option>` +
+        profiles.map(p => {
+          const val = p.profile_id || p.name;
+          return `<option value="${esc(val)}" ${chosenProf === val ? 'selected' : ''}>${esc(p.name)} (×${p.repeat === 0 ? '无限' : (p.repeat || 1)})</option>`;
+        }).join('');
 
 
       return `<article class="prod-station-card ${isFail ? 'is-fail' : isPass ? 'is-pass' : isRunning ? 'is-running' : ''}" data-prod-station="${esc(sid)}">
       return `<article class="prod-station-card ${isFail ? 'is-fail' : isPass ? 'is-pass' : isRunning ? 'is-running' : ''}" data-prod-station="${esc(sid)}">
         <div class="prod-card-head">
         <div class="prod-card-head">
@@ -328,6 +352,11 @@
         prodTargetDraft.set(inp.dataset.prodTarget, v);
         prodTargetDraft.set(inp.dataset.prodTarget, v);
       });
       });
     });
     });
+    grid.querySelectorAll('[data-prod-profile]').forEach(sel => {
+      sel.addEventListener('change', () => {
+        prodProfileDraft.set(sel.dataset.prodProfile, sel.value);
+      });
+    });
     grid.querySelectorAll('[data-prod-curve]').forEach(btn => {
     grid.querySelectorAll('[data-prod-curve]').forEach(btn => {
       btn.addEventListener('click', () => {
       btn.addEventListener('click', () => {
         const [sid, slotStr] = btn.dataset.prodCurve.split(':');
         const [sid, slotStr] = btn.dataset.prodCurve.split(':');

+ 16 - 4
web/style.css

@@ -124,6 +124,9 @@ input[readonly] { background: var(--surface-soft); }
 .boot-stage.observed .boot-stage-name { color: #536c83; }
 .boot-stage.observed .boot-stage-name { color: #536c83; }
 .boot-stage.current { background: var(--primary-soft); border-color: #93cfc4; }
 .boot-stage.current { background: var(--primary-soft); border-color: #93cfc4; }
 .boot-stage.current .boot-stage-name, .boot-stage.current .boot-stage-time { color: #167b70; }
 .boot-stage.current .boot-stage-name, .boot-stage.current .boot-stage-time { color: #167b70; }
+.boot-stage[data-stage-state="skipped"] { background: #f4f6f8; border-color: #dde3ea; opacity: 0.78; }
+.boot-stage[data-stage-state="skipped"] .boot-stage-name { color: #7b8794; }
+.boot-stage[data-stage-state="skipped"] .boot-stage-state { color: #8c98a6; }
 .boot-footnote { font-size: 10px; color: #94a0b0; margin-top: 7px; }
 .boot-footnote { font-size: 10px; color: #94a0b0; margin-top: 7px; }
 .algorithm-progress { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 10px; margin: 12px 0 8px; }
 .algorithm-progress { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 10px; margin: 12px 0 8px; }
 .algorithm-cpu { min-width: 0; border: 1px solid var(--line); background: #f8fbfc; border-radius: 8px; padding: 12px 14px; }
 .algorithm-cpu { min-width: 0; border: 1px solid var(--line); background: #f8fbfc; border-radius: 8px; padding: 12px 14px; }
@@ -790,10 +793,19 @@ body[data-ui-mode="production"] #station-detail-section { display:none !importan
 .dimm-slot-clickable { cursor:pointer;transition:border-color .15s,transform .12s; }
 .dimm-slot-clickable { cursor:pointer;transition:border-color .15s,transform .12s; }
 .dimm-slot-clickable:hover { border-color:var(--primary);transform:translateY(-1px);box-shadow:0 2px 8px rgba(13,139,128,.12); }
 .dimm-slot-clickable:hover { border-color:var(--primary);transform:translateY(-1px);box-shadow:0 2px 8px rgba(13,139,128,.12); }
 
 
-.workspace-split.console-expanded { grid-template-columns:1fr !important; }
-.workspace-split.console-expanded .workspace-left { display:none; }
-.workspace-split.console-expanded .workspace-right { position:static;max-height:none; }
-.workspace-split.console-expanded .sol-terminal { height:72vh;min-height:480px; }
+body[data-current-page="overview"] .workspace-split.console-expanded { grid-template-columns:1fr !important; }
+body[data-current-page="overview"] .workspace-split.console-expanded .workspace-left { display:none; }
+body[data-current-page="overview"] .workspace-split.console-expanded .workspace-right { position:static;max-height:none; }
+body[data-current-page="overview"] .workspace-split.console-expanded .sol-terminal { height:72vh;min-height:480px; }
+
+.pxe-dhcp-card { margin:10px 0 12px;padding:12px 14px;background:#f7fbfc;border:1px solid #d7e6ec;border-radius:8px; }
+.pxe-probe-box { margin-top:8px;padding:8px 10px;border-radius:6px;background:#fff;border:1px solid #dce6ec;font-size:12px;line-height:1.65; }
+.pxe-probe-box.is-warn { background:#fffbeb;border-color:#f59e0b;color:#92400e; }
+.pxe-probe-box.is-ok { background:#f0fdf4;border-color:#86efac;color:#166534; }
+.bmc-sensors-wrap { max-height:260px;overflow:auto;margin-top:8px;border:1px solid var(--line);border-radius:7px; }
+.bmc-sensors-table { width:100%;border-collapse:collapse;font-size:11.5px; }
+.bmc-sensors-table th, .bmc-sensors-table td { padding:6px 9px;border-bottom:1px solid #edf1f5;text-align:left; }
+.bmc-sensors-table th { background:#f3f7fa;position:sticky;top:0;color:#5f7488; }
 
 
 .stl-modal-backdrop { position:fixed;inset:0;z-index:999;background:rgba(15,28,38,.48);display:flex;align-items:center;justify-content:center;padding:16px; }
 .stl-modal-backdrop { position:fixed;inset:0;z-index:999;background:rgba(15,28,38,.48);display:flex;align-items:center;justify-content:center;padding:16px; }
 .stl-modal-backdrop.hidden { display:none !important; }
 .stl-modal-backdrop.hidden { display:none !important; }

+ 53 - 27
web/trace.js

@@ -139,42 +139,67 @@
     } catch (_) {}
     } catch (_) {}
   }
   }
 
 
-  async function drainIdbSpool() {
-    if (!isActive() || !nativeFetch) return;
+  async function syncSpooledCount() {
     const db = await openIdb();
     const db = await openIdb();
     if (!db) return;
     if (!db) return;
     try {
     try {
-      const records = await new Promise(resolve => {
+      spooledCount = await new Promise(resolve => {
         const tx = db.transaction(DB_STORE, 'readonly');
         const tx = db.transaction(DB_STORE, 'readonly');
-        const req = tx.objectStore(DB_STORE).getAll(null, 10);
-        req.onsuccess = () => resolve(req.result || []);
-        req.onerror = () => resolve([]);
+        const req = tx.objectStore(DB_STORE).count();
+        req.onsuccess = () => resolve(Number(req.result || 0));
+        req.onerror = () => resolve(0);
       });
       });
-      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();
+    } catch (_) {}
+  }
+
+  async function drainIdbSpool() {
+    if (!isActive() || !nativeFetch) return;
+    const db = await openIdb();
+    if (!db) return;
+    try {
+      while (true) {
+        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([]);
         });
         });
-        spooledCount = Math.max(0, spooledCount - 1);
+        if (!records.length) {
+          spooledCount = 0;
+          return;
+        }
+        let stopped = false;
+        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) { stopped = true; 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);
+        }
+        if (stopped || records.length < 10) break;
       }
       }
     } catch (_) {}
     } catch (_) {}
   }
   }
 
 
   async function exportOfflineJsonl() {
   async function exportOfflineJsonl() {
-    const all = [...recentRing];
+    const all = [];
+    const seen = new Set();
+    const pushUnique = ev => {
+      if (!ev || typeof ev !== 'object') return;
+      const key = `${ev.session_id || ''}:${ev.seq || ''}:${ev.ts_ms || ''}`;
+      if (seen.has(key)) return;
+      seen.add(key);
+      all.push(ev);
+    };
     const db = await openIdb();
     const db = await openIdb();
     if (db) {
     if (db) {
       const records = await new Promise(resolve => {
       const records = await new Promise(resolve => {
@@ -188,9 +213,10 @@
         }
         }
       });
       });
       for (const rec of records) {
       for (const rec of records) {
-        if (Array.isArray(rec.events)) all.push(...rec.events);
+        if (Array.isArray(rec.events)) rec.events.forEach(pushUnique);
       }
       }
     }
     }
+    recentRing.forEach(pushUnique);
     const text = all.map(e => JSON.stringify(e)).join('\n') + '\n';
     const text = all.map(e => JSON.stringify(e)).join('\n') + '\n';
     const url = URL.createObjectURL(new Blob([text], { type: 'application/x-ndjson' }));
     const url = URL.createObjectURL(new Blob([text], { type: 'application/x-ndjson' }));
     const a = document.createElement('a');
     const a = document.createElement('a');
@@ -657,7 +683,7 @@
       });
       });
     }, 30000);
     }, 30000);
 
 
-    void refreshTraceStatus();
+    void syncSpooledCount().then(() => refreshTraceStatus());
   }
   }
 
 
   window.stlTrace = {
   window.stlTrace = {

+ 8 - 0
web/ui-navigation.js

@@ -5,6 +5,14 @@
     const normalized = value === 'plans' ? 'plan' : value;
     const normalized = value === 'plans' ? 'plan' : value;
     const page = pages.has(normalized) ? normalized : 'overview';
     const page = pages.has(normalized) ? normalized : 'overview';
     document.body.dataset.currentPage = page;
     document.body.dataset.currentPage = page;
+    if (page !== 'overview') {
+      const split = document.querySelector('.workspace-split.console-expanded');
+      if (split) {
+        split.classList.remove('console-expanded');
+        const expandBtn = document.getElementById('btn-console-expand');
+        if (expandBtn) expandBtn.textContent = '放大终端';
+      }
+    }
     window.stlStore?.set?.('page', page, 'nav');
     window.stlStore?.set?.('page', page, 'nav');
     document.querySelectorAll('[data-pages]').forEach(node => {
     document.querySelectorAll('[data-pages]').forEach(node => {
       node.hidden = !node.dataset.pages.split(' ').includes(page);
       node.hidden = !node.dataset.pages.split(' ').includes(page);