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

Release 0.8.1.18: lock-free Station Actors, ICT rename, dual-firmware VD012/CXMT, dual queues, Qt-Clean v1.1 & E2E hardware closure

XJKJ STL 2 недель назад
Родитель
Сommit
1318002372
100 измененных файлов с 22933 добавлено и 9077 удалено
  1. 8 8
      .dockerignore
  2. 7 14
      .gitignore
  3. 109 0
      DDR5_SLT_Monitor.pro
  4. 13 15
      Dockerfile
  5. 29 23
      README.md
  6. 1 1
      VERSION
  7. 43 0
      config.json
  8. 25 0
      config/backend.example.json
  9. 0 160
      config/hardware.example.json
  10. 0 84
      config/profiles/cxmt-live-assisted.json
  11. 0 64
      config/profiles/cxmt-live-gnr.json
  12. 0 58
      config/profiles/sim-cxmt.json
  13. 0 98
      config/serial-net.example.json
  14. 0 95
      config/simulated.json
  15. 0 136
      config/station0-live.json
  16. 1 0
      contracts/firmware-vd012.json
  17. 0 15
      deploy/Dockerfile.qt-runtime
  18. 1 9
      deploy/stl-backend.env.example
  19. 3 6
      deploy/stl-backend.service
  20. 16 12
      docker-compose.yml
  21. 0 1096
      docs/GRPC_API_ZH.md
  22. 91 0
      docs/QT_CLIENT_API_ZH.md
  23. 16 1
      docs/WEBSOCKET_API_ZH.md
  24. 0 25
      examples/qt-clean/config.json
  25. 0 9
      examples/qt-websocket/CMakeLists.txt
  26. 0 105
      examples/qt-websocket/main.cpp
  27. 0 24
      native/build_sol_helper.py
  28. 0 44
      native/example_json_bridge.py
  29. 0 189
      native/sol_helper.cpp
  30. 26 0
      native/stl_accel/build.sh
  31. 817 0
      native/stl_accel/c_bridge.c
  32. 464 0
      native/stl_accel/opencl_batch.c
  33. 929 0
      native/stl_accel/parser_re2c.re
  34. 1204 0
      native/stl_accel/scan_asm.S
  35. 1774 0
      native/stl_accel/src/actors.rs
  36. 1664 0
      native/stl_accel/src/api.rs
  37. 1310 0
      native/stl_accel/src/commands.rs
  38. 93 0
      native/stl_accel/src/config.rs
  39. 615 0
      native/stl_accel/src/devices.rs
  40. 800 0
      native/stl_accel/src/firmware.rs
  41. 1682 0
      native/stl_accel/src/grpc.rs
  42. 334 0
      native/stl_accel/src/json.rs
  43. 677 0
      native/stl_accel/src/lib.rs
  44. 587 0
      native/stl_accel/src/main.rs
  45. 431 0
      native/stl_accel/src/pxe.rs
  46. 1734 0
      native/stl_accel/src/results.rs
  47. 422 0
      native/stl_accel/src/storage.rs
  48. 1527 0
      native/stl_accel/src/workflow.rs
  49. 227 0
      native/stl_accel/stl_accel.h
  50. 344 0
      native/stl_accel/zig_kernels.zig
  51. 0 118
      native/stl_sol_bridge.py
  52. 0 168
      native/stl_ssh_console_bridge.py
  53. 0 0
      port.json
  54. 8 0
      proto/stl/v1/bench.proto
  55. 0 30
      pyproject.toml
  56. 0 60
      qt-client/DDR5_SLT_Monitor.pro
  57. 0 139
      qt-client/QT_CLEAN_CLIENT_ZH.md
  58. 0 52
      qt-client/config.json
  59. 0 21
      qt-client/live-config-off/config.json
  60. 0 24
      qt-client/live-config-off/port.json
  61. 0 19
      qt-client/live-config-on/config.json
  62. 0 24
      qt-client/live-config-on/port.json
  63. BIN
      qt-client/src/assets/logo-mark.png
  64. 0 510
      qt-client/src/backendlink.cpp
  65. 0 92
      qt-client/src/backendlink.h
  66. 0 116
      qt-client/src/demofeed.cpp
  67. 0 741
      qt-client/src/detailview.cpp
  68. 0 167
      qt-client/src/localplans.cpp
  69. 0 25
      qt-client/src/localplans.h
  70. 0 65
      qt-client/src/main.cpp
  71. 0 423
      qt-client/src/mainwindow.cpp
  72. 0 93
      qt-client/src/mainwindow.h
  73. 0 103
      qt-client/src/powerbutton.cpp
  74. 0 312
      qt-client/src/stationdata.cpp
  75. 0 413
      qt-client/src/style/app.qss
  76. 0 52
      qt-client/src/uiformat.h
  77. 0 440
      qt-client/tests/qt_clean_probe.cpp
  78. 0 10
      qt-client/tests/qt_clean_probe.pro
  79. 0 95
      scripts/collect_live_evidence.py
  80. 0 86
      scripts/deploy_qt_release.py
  81. 0 299
      scripts/generate_api_reference.py
  82. 0 21
      scripts/generate_proto.py
  83. 0 176
      scripts/package_delivery.py
  84. 0 44
      scripts/probe_bmc.py
  85. 0 74
      scripts/probe_ipmi_sol.py
  86. 0 9
      scripts/run_container.sh
  87. 0 33
      scripts/run_qt_fixtures.py
  88. 0 846
      scripts/test_web_browser.mjs
  89. 0 112
      scripts/test_web_command_recovery.mjs
  90. 0 97
      scripts/test_web_transport.mjs
  91. 0 105
      scripts/validate_live_actions.py
  92. 0 503
      scripts/validate_qt_clean.py
  93. 0 69
      scripts/version.py
  94. 208 0
      src/3rdparty/libxlsxwriter/License.txt
  95. 26 0
      src/3rdparty/libxlsxwriter/include/xlsxwriter.h
  96. 81 0
      src/3rdparty/libxlsxwriter/include/xlsxwriter/app.h
  97. 3964 0
      src/3rdparty/libxlsxwriter/include/xlsxwriter/chart.h
  98. 545 0
      src/3rdparty/libxlsxwriter/include/xlsxwriter/chartsheet.h
  99. 77 0
      src/3rdparty/libxlsxwriter/include/xlsxwriter/comment.h
  100. 0 0
      src/3rdparty/libxlsxwriter/include/xlsxwriter/common.h

+ 8 - 8
.dockerignore

@@ -1,17 +1,17 @@
 .git
-.venv
-.pytest_cache
-**/__pycache__
-**/*.pyc
-*.egg-info
-local.env
-.env
-.env.*
+build/*
+!build/native/
+build/native/*
+!build/native/stl_native_server
 data
 logs
 releases
 dist
 inputs
 node_modules
+local.env
+.env
+.env.*
+config/station0-live.json
 *.zip
 *.bundle

+ 7 - 14
.gitignore

@@ -1,23 +1,16 @@
-.venv/
-__pycache__/
-*.py[cod]
-*.egg-info/
-.pytest_cache/
-var/
 build/
 dist/
-native/stl-sol-helper
-
-# Local credentials, collected evidence and large input/output packages.
+var/
+data/
+logs/
+releases/
+inputs/
+node_modules/
 .env
 .env.*
 !.env.example
 local.env
 *.local.env
-inputs/
-data/
-logs/
-releases/
-node_modules/
+config/station0-live.json
 *.zip
 *.bundle

+ 109 - 0
DDR5_SLT_Monitor.pro

@@ -0,0 +1,109 @@
+#-------------------------------------------------------------------------------
+# DDR5 RDIMM SLT 上位机监控平台 —— 多工位测试监控
+# Qt 5 / C++11 / Linux + Windows(MinGW)
+#
+# 编译:
+#   qmake DDR5_SLT_Monitor.pro
+#   make -j4
+#-------------------------------------------------------------------------------
+
+QT       += core gui serialport websockets
+greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+
+# QCustomPlot 2.1.1(GPLv3,src/3rdparty/qcustomplot/GPL.txt):温控曲线用
+QT       += printsupport
+
+TARGET    = DDR5_SLT_Monitor
+TEMPLATE  = app
+CONFIG   += c++11
+
+# 界面代码全部由 src/mainwindow.ui 生成
+INCLUDEPATH += $$PWD/src
+INCLUDEPATH += $$PWD/src/3rdparty/qcustomplot
+DEPENDPATH  += $$PWD/src
+
+
+# libxlsxwriter 1.2.4(MIT,src/3rdparty/libxlsxwriter/License.txt):异常记录导出 xlsx
+INCLUDEPATH += $$PWD/src/3rdparty/libxlsxwriter/include
+INCLUDEPATH += $$PWD/src/3rdparty/libxlsxwriter/include/xlsxwriter
+INCLUDEPATH += $$PWD/src/3rdparty/libxlsxwriter/src
+INCLUDEPATH += $$PWD/src/3rdparty/libxlsxwriter/third_party/minizip
+INCLUDEPATH += $$PWD/src/3rdparty/libxlsxwriter/third_party/tmpfileplus
+# 压缩用系统 zlib(MinGW 自带 libz.a)
+LIBS += -lz
+
+SOURCES += \
+    src/3rdparty/libxlsxwriter/src/app.c \
+    src/3rdparty/libxlsxwriter/src/chart.c \
+    src/3rdparty/libxlsxwriter/src/chartsheet.c \
+    src/3rdparty/libxlsxwriter/src/comment.c \
+    src/3rdparty/libxlsxwriter/src/content_types.c \
+    src/3rdparty/libxlsxwriter/src/core.c \
+    src/3rdparty/libxlsxwriter/src/custom.c \
+    src/3rdparty/libxlsxwriter/src/drawing.c \
+    src/3rdparty/libxlsxwriter/src/format.c \
+    src/3rdparty/libxlsxwriter/src/hash_table.c \
+    src/3rdparty/libxlsxwriter/src/metadata.c \
+    src/3rdparty/libxlsxwriter/src/packager.c \
+    src/3rdparty/libxlsxwriter/src/relationships.c \
+    src/3rdparty/libxlsxwriter/src/rich_value.c \
+    src/3rdparty/libxlsxwriter/src/rich_value_rel.c \
+    src/3rdparty/libxlsxwriter/src/rich_value_structure.c \
+    src/3rdparty/libxlsxwriter/src/rich_value_types.c \
+    src/3rdparty/libxlsxwriter/src/shared_strings.c \
+    src/3rdparty/libxlsxwriter/src/styles.c \
+    src/3rdparty/libxlsxwriter/src/table.c \
+    src/3rdparty/libxlsxwriter/src/theme.c \
+    src/3rdparty/libxlsxwriter/src/utility.c \
+    src/3rdparty/libxlsxwriter/src/vml.c \
+    src/3rdparty/libxlsxwriter/src/workbook.c \
+    src/3rdparty/libxlsxwriter/src/worksheet.c \
+    src/3rdparty/libxlsxwriter/src/xmlwriter.c \
+    src/3rdparty/libxlsxwriter/third_party/md5/md5.c \
+    src/3rdparty/libxlsxwriter/third_party/minizip/ioapi.c \
+    src/3rdparty/libxlsxwriter/third_party/minizip/zip.c \
+    src/3rdparty/libxlsxwriter/third_party/tmpfileplus/tmpfileplus.c
+
+win32: SOURCES += src/3rdparty/libxlsxwriter/third_party/minizip/iowin32.c
+QMAKE_CFLAGS   += -march=x86-64 -mtune=generic
+QMAKE_CXXFLAGS += -march=x86-64 -mtune=generic
+
+SOURCES += \
+    src/main.cpp \
+    src/mainwindow.cpp \
+    src/overviewview.cpp \
+    src/detailview.cpp \
+    src/createtaskdialog.cpp \
+    src/powerbutton.cpp \
+    src/stationdata.cpp \
+    src/backendlink.cpp \
+    src/localplans.cpp \
+    src/comworker.cpp \
+    src/sltproto.cpp \
+    src/comanager.cpp \
+    src/3rdparty/qcustomplot/qcustomplot.cpp
+
+HEADERS += \
+    src/appconfig.h \
+    src/mainwindow.h \
+    src/overviewview.h \
+    src/detailview.h \
+    src/createtaskdialog.h \
+    src/powerbutton.h \
+    src/stationdata.h \
+    src/backendlink.h \
+    src/localplans.h \
+    src/uiformat.h \
+    src/comworker.h \
+    src/sltproto.h \
+    src/comanager.h \
+    src/3rdparty/qcustomplot/qcustomplot.h
+
+FORMS += \
+    src/mainwindow.ui \
+    src/createtaskdialog.ui
+
+RESOURCES += \
+    src/resources.qrc
+
+# 源码/样式统一按 UTF-8 处理(Linux g++ 默认即 UTF-8)

+ 13 - 15
Dockerfile

@@ -1,24 +1,22 @@
-FROM python:3.11-slim
+FROM debian:trixie-slim
 
-ENV PYTHONUNBUFFERED=1 \
-    DEBIAN_FRONTEND=noninteractive
+ENV DEBIAN_FRONTEND=noninteractive
 WORKDIR /app
 
 RUN apt-get update && \
-    apt-get install -y --no-install-recommends ipmitool freeipmi-tools openssh-client sshpass && \
+    apt-get install -y --no-install-recommends ipmitool freeipmi-tools openssh-client sshpass ca-certificates && \
     rm -rf /var/lib/apt/lists/*
 
-COPY pyproject.toml README.md ./
-COPY src/ ./src/
-RUN pip install --no-cache-dir .
-COPY native/ ./native/
+COPY VERSION README.md ./
+COPY contracts/ ./contracts/
+COPY web/ ./web/
 COPY config/ ./config/
+COPY build/native/stl_native_server /usr/local/bin/stl_native_server
 
-ARG STL_BUILD_COMMIT=unknown
-ARG STL_VERSION=dev
-ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT}
-LABEL org.opencontainers.image.version=${STL_VERSION} \
-      org.opencontainers.image.revision=${STL_BUILD_COMMIT}
+ARG STL_BUILD_COMMIT=vd012-native
+ARG STL_VERSION=0.8.1.18
+ENV STL_BUILD_COMMIT=${STL_BUILD_COMMIT} \
+    STL_VERSION=${STL_VERSION}
 
-EXPOSE 50051 8080
-CMD ["python3", "-m", "stl_backend.server", "--config", "config/simulated.json", "--listen", "0.0.0.0:50051", "--web-listen", "0.0.0.0:8080", "--data-dir", "/app/data"]
+EXPOSE 8080 50051
+CMD ["/usr/local/bin/stl_native_server", "--config", "/app/config/station0-live.json", "--web-listen", "0.0.0.0:8080", "--grpc-listen", "0.0.0.0:50051", "--data-dir", "/app/data", "--web-dir", "/app/web", "--contracts", "/app/contracts/firmware-vd012.json"]

+ 29 - 23
README.md

@@ -1,35 +1,41 @@
-# XJKJ-STL 高温内存测试平台
+# XJKJ-STL 高温内存测试工作台
 
-当前开发版:`0.8.1.17`。唯一 Git 分支:`dev`。
+当前版本:`0.8.1.18`(分支:`dev`)。
 
-一台 Linux 后端管理四个工位;Qt 保留前端开发人员原有界面,界面仅展示状态、BIOS UART 原文和提交动作。实际 BMC、固件阶段、诊断采集、失败判断、命令队列均由后端完成。
+本仓库为 `XJKJ-STL` DDR5 内存高温测试与 BIOS 串口诊断工作台全栈源码(含原生高性能控制后端 `stl_native_server`、现代 Web 多页前端 `web/`、以及 Windows/Linux Qt 客户端 `src/`),同时提供完整 WebSocket(`/ws`)、原生 HTTP/2 gRPC(`:50051`,`stl.v1.BenchService`)及面向 Qt 的精简纯净接口(`/ws?view=qt-clean`)。
 
-## 三种接口
+## 目录结构
 
-| 用途 | 地址 | 文档 |
-| --- | --- | --- |
-| 完整 WebSocket | `ws://192.168.2.79:8080/ws` | [WebSocket 全量协议](docs/WEBSOCKET_API_ZH.md) |
-| 完整原生 gRPC | `192.168.2.79:50051` | [gRPC 全量协议](docs/GRPC_API_ZH.md) |
-| Qt 专用精简 WebSocket | `ws://192.168.2.79:8080/ws?view=qt-clean` | [Qt 对接接口与全部参数](docs/QT_CLIENT_API_ZH.md) |
+- `contracts/firmware-vd012.json`:双机固件参数契约(224 项 ICT 参数、`showmain` 0~101 步骤表、`showtrain` 0~84 步骤表、30 项 AMT 参数及默认测试计划定义,兼容 `.166` `107_VD012` 与 `.165` `CxmtDdrTest`)。
+- `native/stl_accel/`:纯 SSE2 基线 + CPUID 动态分派(`SSE2` / `SSE4.2+POPCNT` / `AVX2+BMI1/2`)原生后端与构建脚本 `build.sh`:
+  - `scan_asm.S`:手写向量化 Base64 编码及单遍零分配 UEFI 光标重定位/ANSI 控制码清洗、切行与标签预分类热核;
+  - `parser_re2c.re` / `parser_re2c.c`:确定性 `re2c` DFA 固件阶段与报错状态机;
+  - `zig_kernels.zig`:RFC 6455 WebSocket 握手摘要与 Base64 核;
+  - `c_bridge.c`:CPUID/XGETBV 分派、64 位单调递增环形缓冲大页/保护页封装、持久非阻塞 IPMI 连接池、POSIX PTY/物理串口 `/dev/ttyUSB0`/TCP 透传/SOL 桥接、`writev` 帧合并及可选 Gen7.5~Gen9.5 OpenCL 批处理;
+  - `src/`:按工位无锁分片 Actor 服务模块(`main.rs`、`actors.rs`、`api.rs`、`grpc.rs`、`commands.rs`、`workflow.rs`、`firmware.rs`、`results.rs`、`devices.rs`、`pxe.rs`、`storage.rs`、`config.rs`、`json.rs`、`lib.rs`)。
+- `web/`:静态多页 Web 前端(ICT 显示统一、全量 224 项 ICT + 30 项 AMT、7 阶段独立完成徽章、双队列编排、阻塞伪推送清洗终端)。
+- `src/` + `DDR5_SLT_Monitor.pro`:Qt 客户端源码(`0.8.1.18`),对接 `/ws?view=qt-clean`。
+- `docs/`:`QT_CLIENT_API_ZH.md`(Qt 纯净接口规范)与 `WEBSOCKET_API_ZH.md`(完整 WebSocket 接口手册)。
+- `config/`:`backend.example.json` 与 `dimms.example.json` 配置示例(现场 `config/station0-live.json` 原位保留并由 `.gitignore` 忽略)。
+- `deploy/`:`systemd` 服务文件与环境变量示例。
 
-三个接口共用一套硬件状态机,互不替代。旧完整客户端无需切换协议;Qt 专用接口仅保留 `GetSystemInfo`、`GetState`、`StartTest`、`StageAction`、`GetCommand`、`ReadBiosUart`。
+## 构建依赖与编译
 
-## Qt 行为
+构建环境需具备 `gcc`、`zig`(0.14+)、`rustc`(1.80+);运行环境按需安装 `ipmitool`、`openssh-client`、`sshpass`。
 
-- Qt 的 `qt-plans.json` 独立保存 UIP、AMT、UEFI 动作,后端不存 Qt plan。
-- 点击 Start 时检测主机电源:开机状态做主机 `host_reset`,关机状态做 `host_on`,不重启 BMC。
-- DDR Training 实际确认成功后,每 CPU 的 12 路立即显示绿色,两 CPU 成功后 24 路在 AMT 前均绿色;新的真实错误将对应状态改为失败。Training 绿色不代表 AMT/MT 算法全通过。
-- Qt 测试日志仅显示 BIOS UART 原始字节解码后的文本,不显示后端业务事件摘要。
-- Qt 连接超时、状态流静默或掉线后重连,继续查询原 `command_id`,**绝不重发已经接受的主机操作**。
-- UI 控件、布局、QSS、QCustomPlot 与开发人员源码一致。
+```bash
+./native/stl_accel/build.sh
+```
 
-## 开发与验证
+编译输出统一生成至 `build/native/stl_native_server`,并在构建阶段自动运行原生单元测试 `build/native/stl_native_tests`。
 
-需要 Python 3.11+。后端源码和测试位于 `src/`、`tests/`,原 Qt 工程位于 `qt-client/`,Windows 编译/验证脚本位于 `validation/`。
+## 启动服务
 
 ```bash
-python3 -m pip install -e '.[dev]'
-python3 -m pytest -q
+./build/native/stl_native_server \
+  --config config/station0-live.json \
+  --web-listen 0.0.0.0:8080 \
+  --data-dir ./data \
+  --web-dir ./web \
+  --contracts ./contracts/firmware-vd012.json
 ```
-
-通过 Docker 或 `scripts/run_container.sh` 启动服务。物理硬件配置和运行中的 SQLite 数据分别位于 `config/` 与 Git 忽略的 `data/`;不得提交 BMC 凭据。完整 AMT、MT、未接入工位和温控闭环必须获得真实设备证据后才可判定 PASS。

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.8.1.17
+0.8.1.18

Разница между файлами не показана из-за своего большого размера
+ 43 - 0
config.json


+ 25 - 0
config/backend.example.json

@@ -0,0 +1,25 @@
+{
+  "stations": [
+    {
+      "station_id": "S1",
+      "name": "工位 001 (现场测试台)",
+      "mode": "hardware",
+      "cpu_count": 2,
+      "channels_per_cpu": 12,
+      "bmc": {
+        "enabled": true,
+        "host": "192.168.2.166",
+        "username": "ADMIN",
+        "password_env": "STL_BMC_S1_PASSWORD"
+      },
+      "console": {
+        "enabled": true,
+        "transport": "ssh_console",
+        "host": "192.168.2.166",
+        "port": 2200,
+        "write_chunk_bytes": 8,
+        "write_gap_ms": 20
+      }
+    }
+  ]
+}

+ 0 - 160
config/hardware.example.json

@@ -1,160 +0,0 @@
-{
-  "mode": "hardware",
-  "listen": "127.0.0.1:50051",
-  "data_dir": "../var/hardware",
-  "telemetry_interval_s": 2.0,
-  "profile_files": [
-    "profiles/cxmt-live-gnr.json"
-  ],
-  "stations": [
-    {
-      "station_id": "S1",
-      "frontend_index": 0,
-      "name": "工位 001",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "supply_mode": "manual",
-      "bmc": {
-        "host": "192.168.0.100",
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S1_PASSWORD",
-        "cipher_suite": 17,
-        "timeout_s": 15,
-        "sol_helper_argv": [
-          "python3",
-          "native/stl_sol_bridge.py"
-        ],
-        "console_transport": "ipmi_sol"
-      },
-      "bridge": {
-        "argv": [
-          "/opt/xjkj-stl-site/thermal_bridge",
-          "--station",
-          "S1"
-        ],
-        "timeout_s": 5
-      }
-    },
-    {
-      "station_id": "S2",
-      "frontend_index": 1,
-      "name": "工位 002",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "supply_mode": "manual",
-      "bmc": {
-        "host": "192.168.0.101",
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S2_PASSWORD",
-        "cipher_suite": 17,
-        "timeout_s": 15,
-        "sol_helper_argv": [
-          "python3",
-          "native/stl_sol_bridge.py"
-        ],
-        "console_transport": "ipmi_sol"
-      },
-      "bridge": {
-        "argv": [
-          "/opt/xjkj-stl-site/thermal_bridge",
-          "--station",
-          "S2"
-        ],
-        "timeout_s": 5
-      }
-    },
-    {
-      "station_id": "S3",
-      "frontend_index": 2,
-      "name": "工位 003",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "supply_mode": "manual",
-      "bmc": {
-        "host": "192.168.0.102",
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S3_PASSWORD",
-        "cipher_suite": 17,
-        "timeout_s": 15,
-        "sol_helper_argv": [
-          "python3",
-          "native/stl_sol_bridge.py"
-        ],
-        "console_transport": "ipmi_sol"
-      },
-      "bridge": {
-        "argv": [
-          "/opt/xjkj-stl-site/thermal_bridge",
-          "--station",
-          "S3"
-        ],
-        "timeout_s": 5
-      }
-    },
-    {
-      "station_id": "S4",
-      "frontend_index": 3,
-      "name": "工位 004",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "supply_mode": "manual",
-      "bmc": {
-        "host": "192.168.0.103",
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S4_PASSWORD",
-        "cipher_suite": 17,
-        "timeout_s": 15,
-        "sol_helper_argv": [
-          "python3",
-          "native/stl_sol_bridge.py"
-        ],
-        "console_transport": "ipmi_sol"
-      },
-      "bridge": {
-        "argv": [
-          "/opt/xjkj-stl-site/thermal_bridge",
-          "--station",
-          "S4"
-        ],
-        "timeout_s": 5
-      }
-    }
-  ],
-  "recipes": [
-    {
-      "recipe_id": "CXMT-ASSISTED",
-      "name": "CXMT 实机辅助流程:现场核对参数后使用",
-      "revision": 1,
-      "profile_id": "cxmt-live-gnr",
-      "dimm_target_c": 80.0,
-      "preheat_air_c": 70.0,
-      "preheat_hold_s": 30,
-      "preheat_timeout_s": 3600,
-      "phase_timeout_s": 14400,
-      "finish_timeout_s": 30,
-      "run_rmt": true,
-      "run_amt": true,
-      "run_mt": true,
-      "stage1_commands": [],
-      "mt_command": "memtest.efi",
-      "required_artifact_kinds": [
-        "memtest_html"
-      ],
-      "notes": "硬件接入模板。BIOS 与 UEFI 参数由操作员核对;未显式配置的参数不会自动发送。",
-      "stop_on_test_error": true,
-      "metadata": {}
-    }
-  ]
-}

+ 0 - 84
config/profiles/cxmt-live-assisted.json

@@ -1,84 +0,0 @@
-{
-  "profile_id": "cxmt-live-assisted",
-  "mode": "hardware",
-  "description": "历史0.1.0兼容profile,保留用于已冻结记录的解释;当前部署使用cxmt-live-gnr。此旧流程会发送stage1_commands及mt_command,不代表当前固件已验证。",
-  "steps": [
-    {
-      "id": "cpu0_uip_wait",
-      "phase": "bios_config",
-      "expect": "\\[0\\]\\[CxmtDdrTest\\]Current stage is 1",
-      "expect_from_start": true
-    },
-    {
-      "id": "cpu0_test_options",
-      "phase": "bios_config",
-      "manual": true,
-      "instruction": "按本机型实际入口,核对 CPU0 本轮 RMT/AMT 选择和所需额外参数;未选项目也要在固件中实际关闭。保持在 CPU0 UIP 输入阶段,不输入退出回车。确认后后台下发已配置的 stage1 命令。"
-    },
-    {
-      "id": "cpu0_memory",
-      "phase": "bios_config",
-      "use_stage1_commands": true,
-      "initial_delay_s": 1.0,
-      "interval_s": 1.0,
-      "append_enter": true
-    },
-    {
-      "id": "cpu1_uip_wait",
-      "phase": "bios_config",
-      "expect": "\\[1\\]\\[CxmtDdrTest\\]Current stage is 1",
-      "expect_from_start": true
-    },
-    {
-      "id": "cpu1_test_options",
-      "phase": "bios_config",
-      "manual": true,
-      "instruction": "按本机型实际入口,核对 CPU1 本轮 RMT/AMT 选择和所需额外参数;未选项目也要在固件中实际关闭。保持在 CPU1 UIP 输入阶段,不输入退出回车。确认后后台下发已配置的 stage1 命令。"
-    },
-    {
-      "id": "cpu1_memory",
-      "phase": "bios_config",
-      "use_stage1_commands": true,
-      "initial_delay_s": 1.0,
-      "interval_s": 1.0,
-      "append_enter": true
-    },
-    {
-      "id": "rmt_completion",
-      "phase": "rmt",
-      "when": "rmt",
-      "test": "rmt",
-      "manual": true,
-      "instruction": "确认所选 RMT 已实际执行完毕,保留 SOL 证据;发现失败请报告失败。该 BIOS 版本的完成标记确认后可将此步骤改为 expect。"
-    },
-    {
-      "id": "amt_completion",
-      "phase": "amt",
-      "when": "amt",
-      "test": "amt",
-      "manual": true,
-      "instruction": "确认所选 AMT 已实际执行完毕,保留 SOL 证据;发现失败请报告失败。该 BIOS 版本的完成标记确认后可将此步骤改为 expect。"
-    },
-    {
-      "id": "uefi",
-      "phase": "uefi_ready",
-      "expect": "(?i)(?:Shell>|FS\\d+:\\\\[^\\r\\n>]*>)",
-      "uefi_ready": true
-    },
-    {
-      "id": "mt_launch",
-      "phase": "mt",
-      "when": "mt",
-      "use_mt_command": true
-    },
-    {
-      "id": "mt_completion",
-      "phase": "mt",
-      "when": "mt",
-      "test": "mt",
-      "manual": true,
-      "instruction": "确认 MT 已退出且结果文件写入完成,附上结束证据。失败/停止也将收尾并整套断电;U盘文件随后导入本轮。"
-    }
-  ],
-  "stop_commands": []
-}

+ 0 - 64
config/profiles/cxmt-live-gnr.json

@@ -1,64 +0,0 @@
-{
-  "profile_id": "cxmt-live-gnr",
-  "mode": "hardware",
-  "description": "现场辅助流程。已通过SSH 2200实测双路UIP、Training、RMT和UEFI入口,并采集双CPU AMEMDIAG真实算法输出;整体结果按每轮完整证据判定。UEFI外部测试程序及温控板闭环未验证。步骤仍按实际证据人工确认,不自动重放旧Qt参数。",
-  "steps": [
-    {
-      "id": "cpu0_configuration",
-      "phase": "bios_config",
-      "manual": true,
-      "instruction": "观察真实 CPU0 UIP 阶段号和提示符。默认不发送覆盖;要修改时在 UIP 页面显式应用并检查回显。当前固件用 rmt enable/disable 和 admt enable/disable 选择 RMT、AMEMDIAG。完成后点击空回车继续(ContinueUip,仅 CR),再独立确认本流程步骤;不自动应用保存项。"
-    },
-    {
-      "id": "cpu1_configuration",
-      "phase": "bios_config",
-      "manual": true,
-      "instruction": "观察真实 CPU1 UIP 输入点,分别核对本 CPU 参数;需要修改时显式应用并检查回显。完成后点击空回车继续(ContinueUip,仅 CR),再独立确认本流程步骤。CPU0 已处理不代表 CPU1 已配置;设置 ACK 不等于测试已运行。"
-    },
-    {
-      "id": "training_confirmation",
-      "phase": "training",
-      "manual": true,
-      "instruction": "完成各 CPU 的 UIP 输入并空回车继续,观察 DDR Training 实际输出及明确 DIMM/通道状态。空回车只跳过参数输入,不跳过训练。无明确槽位结果保持未知;确认本阶段结束后继续。"
-    },
-    {
-      "id": "rmt_completion",
-      "phase": "rmt",
-      "when": "rmt",
-      "test": "rmt",
-      "manual": true,
-      "instruction": "核对本轮各 CPU 的 RMT 实际执行、裕量行与结束标记并保留原始日志;测温或极短步骤结束不等于完整裕量扫描,没有工艺阈值不自行判裕量 PASS。确认执行结束后继续,实际失败请报告失败。"
-    },
-    {
-      "id": "amt_completion",
-      "phase": "amt",
-      "when": "amt",
-      "test": "amt",
-      "manual": true,
-      "instruction": "核对当前是否为 AMT/AMEMDIAG 菜单或算法执行。若本次不做测试,在各 CPU 菜单分别点退出 AMT(SkipAmt,仅 exit+CR);不是运行中止命令。退出后仍需独立确认流程,已请求跳过/已跳过不会因此改为完成或 PASS。若需要执行,保留实际算法及结果;菜单和 BIOS MemTest 完成不代替算法通过。"
-    },
-    {
-      "id": "uefi_confirmation",
-      "phase": "uefi_ready",
-      "manual": true,
-      "uefi_ready": true,
-      "instruction": "观察后续 MRC、UIP stage2、DXE/BDS,新的 UIP 提示符可空回车继续。仅在真实 UEFI Shell 就绪后确认;用 map 和目录核对实际测试介质、EFI 程序与配置。当前 FS0 是 NVMe、EFI 下仅 BOOT/redhat,不默认 FS0 是 U 盘,也不使用无关启动文件代替测试程序。"
-    },
-    {
-      "id": "mt_launch",
-      "phase": "mt",
-      "when": "mt",
-      "manual": true,
-      "instruction": "在启动与测试页读取真实 UEFI 目录,选择已核实路径/版本的 EFI 与配置,填写该程序支持的调用模板并预览后启动。保存实际命令及程序启动输出;仅发送成功不表示 MT 已运行,确认真实程序开始本轮测试后再确认流程。"
-    },
-    {
-      "id": "mt_completion",
-      "phase": "mt",
-      "when": "mt",
-      "test": "mt",
-      "manual": true,
-      "instruction": "确认 MT 已结束并完成 USB/PXE 结果保存,保留实际结论及结束证据。收尾后导入本轮真实报告和日志;缺文件、未执行或证据不足不记 PASS,实际失败请报告失败。"
-    }
-  ],
-  "stop_commands": []
-}

+ 0 - 58
config/profiles/sim-cxmt.json

@@ -1,58 +0,0 @@
-{
-  "profile_id": "sim-cxmt",
-  "mode": "simulated",
-  "description": "Synthetic protocol for local integration only; no hardware access.",
-  "steps": [
-    {
-      "id": "cpu0_uip",
-      "phase": "bios_config",
-      "expect": "\\[0\\]\\[CxmtDdrTest\\]Current stage is 1",
-      "expect_from_start": true,
-      "use_stage1_commands": true,
-      "ack_template": "User input command is {command}",
-      "interval_s": 0.005,
-      "append_enter": true
-    },
-    {
-      "id": "cpu1_uip",
-      "phase": "bios_config",
-      "expect": "\\[1\\]\\[CxmtDdrTest\\]Current stage is 1",
-      "expect_from_start": true,
-      "use_stage1_commands": true,
-      "ack_template": "User input command is {command}",
-      "interval_s": 0.005,
-      "append_enter": true
-    },
-    {
-      "id": "rmt",
-      "phase": "rmt",
-      "when": "rmt",
-      "test": "rmt",
-      "expect": "STL_SIM RMT_START",
-      "expect_after": "STL_SIM RMT_DONE"
-    },
-    {
-      "id": "amt",
-      "phase": "amt",
-      "when": "amt",
-      "test": "amt",
-      "expect": "STL_SIM AMT_START",
-      "expect_after": "STL_SIM AMT_DONE"
-    },
-    {
-      "id": "uefi",
-      "phase": "uefi_ready",
-      "expect": "Shell>",
-      "uefi_ready": true
-    },
-    {
-      "id": "mt",
-      "phase": "mt",
-      "when": "mt",
-      "test": "mt",
-      "use_mt_command": true,
-      "expect_after": "STL_SIM RESULTS_FLUSHED"
-    }
-  ],
-  "stop_commands": []
-}

+ 0 - 98
config/serial-net.example.json

@@ -1,98 +0,0 @@
-{
-  "mode": "hardware",
-  "listen": "127.0.0.1:50051",
-  "data_dir": "../var/serial-net",
-  "telemetry_interval_s": 1.0,
-  "idle_poll_interval_s": 15,
-  "profile_files": [
-    "profiles/cxmt-live-gnr.json"
-  ],
-  "stations": [
-    {
-      "station_id": "S1",
-      "frontend_index": 0,
-      "name": "工位 001(串口转网待配置)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "supply_mode": "manual",
-      "console": {
-        "enabled": false,
-        "transport": "tcp_serial",
-        "host": "",
-        "port": 0,
-        "connect_timeout_s": 5,
-        "write_timeout_s": 15
-      },
-      "bmc": {
-        "enabled": false,
-        "host": "",
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S1_PASSWORD",
-        "cipher_suite": 17,
-        "timeout_s": 15
-      }
-    },
-    {
-      "station_id": "S2",
-      "frontend_index": 1,
-      "name": "工位 002(串口转网待配置)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "supply_mode": "manual",
-      "console": {
-        "enabled": false,
-        "transport": "tcp_serial",
-        "host": "",
-        "port": 0,
-        "connect_timeout_s": 5,
-        "write_timeout_s": 15
-      },
-      "bmc": {
-        "enabled": false
-      }
-    },
-    {
-      "station_id": "S3",
-      "frontend_index": 2,
-      "name": "工位 003(串口转网待配置)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "supply_mode": "manual",
-      "console": {
-        "enabled": false,
-        "transport": "tcp_serial",
-        "host": "",
-        "port": 0,
-        "connect_timeout_s": 5,
-        "write_timeout_s": 15
-      },
-      "bmc": {
-        "enabled": false
-      }
-    },
-    {
-      "station_id": "S4",
-      "frontend_index": 3,
-      "name": "工位 004(串口转网待配置)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "supply_mode": "manual",
-      "console": {
-        "enabled": false,
-        "transport": "tcp_serial",
-        "host": "",
-        "port": 0,
-        "connect_timeout_s": 5,
-        "write_timeout_s": 15
-      },
-      "bmc": {
-        "enabled": false
-      }
-    }
-  ],
-  "recipes": []
-}

+ 0 - 95
config/simulated.json

@@ -1,95 +0,0 @@
-{
-  "mode": "simulated",
-  "listen": "127.0.0.1:50051",
-  "data_dir": "../var/simulated",
-  "telemetry_interval_s": 0.25,
-  "max_upload_bytes": 268435456,
-  "max_chunk_bytes": 262144,
-  "profile_files": [
-    "profiles/sim-cxmt.json"
-  ],
-  "stations": [
-    {
-      "station_id": "S1",
-      "frontend_index": 0,
-      "name": "工位 001",
-      "mode": "simulated",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "simulation": {
-        "step_delay_s": 0.15,
-        "mt_duration_s": 2.0
-      }
-    },
-    {
-      "station_id": "S2",
-      "frontend_index": 1,
-      "name": "工位 002",
-      "mode": "simulated",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "simulation": {
-        "step_delay_s": 0.15,
-        "mt_duration_s": 2.0
-      }
-    },
-    {
-      "station_id": "S3",
-      "frontend_index": 2,
-      "name": "工位 003",
-      "mode": "simulated",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "simulation": {
-        "step_delay_s": 0.15,
-        "mt_duration_s": 2.0
-      }
-    },
-    {
-      "station_id": "S4",
-      "frontend_index": 3,
-      "name": "工位 004",
-      "mode": "simulated",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0,
-      "target_max_c": 100,
-      "simulation": {
-        "step_delay_s": 0.15,
-        "mt_duration_s": 2.0
-      }
-    }
-  ],
-  "recipes": [
-    {
-      "recipe_id": "DEMO-80",
-      "name": "四工位模拟:默认 UIP 参数(80℃为示例)",
-      "revision": 1,
-      "profile_id": "sim-cxmt",
-      "dimm_target_c": 80.0,
-      "preheat_air_c": 70.0,
-      "preheat_hold_s": 0.2,
-      "preheat_timeout_s": 30.0,
-      "phase_timeout_s": 30.0,
-      "finish_timeout_s": 5.0,
-      "run_rmt": true,
-      "run_amt": true,
-      "run_mt": true,
-      "stage1_commands": [],
-      "firmware_settings": {"uip_overrides": [], "mt_selection": {}},
-      "mt_command": "memtest.efi {run_id}",
-      "required_artifact_kinds": [
-        "result_json"
-      ],
-      "notes": "默认不发送 UIP 参数覆盖;在 UIP 页面明确选择后保存或应用。温度数值仅用于模拟演示。",
-      "stop_on_test_error": true,
-      "metadata": {}
-    }
-  ]
-}

+ 0 - 136
config/station0-live.json

@@ -1,136 +0,0 @@
-{
-  "mode": "hardware",
-  "listen": "0.0.0.0:50051",
-  "data_dir": "../data",
-  "telemetry_interval_s": 1.0,
-  "max_upload_bytes": 268435456,
-  "max_chunk_bytes": 262144,
-  "profile_files": [
-    "profiles/cxmt-live-gnr.json"
-  ],
-  "stations": [
-    {
-      "station_id": "S1",
-      "frontend_index": 0,
-      "name": "工位 001 (现场测试台)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0.0,
-      "target_max_c": 100.0,
-      "supply_mode": "manual",
-      "bmc": {
-        "host": "192.168.0.100",
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S1_PASSWORD",
-        "cipher_suite": 17,
-        "timeout_s": 15,
-        "sol_helper_argv": [
-          "python3",
-          "native/stl_ssh_console_bridge.py"
-        ],
-        "console_transport": "ssh_console",
-        "ssh_console_port": 2200,
-        "ssh_known_hosts": "data/ssh_known_hosts"
-      },
-      "console": {
-        "transport": "ssh_console",
-        "host": "192.168.0.100",
-        "port": 2200,
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S1_PASSWORD",
-        "known_hosts": "data/ssh_known_hosts",
-        "write_chunk_bytes": 8,
-        "write_gap_ms": 20.0
-      }
-    },
-    {
-      "station_id": "S2",
-      "frontend_index": 1,
-      "name": "工位 002 (现场测试台 2.165)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0.0,
-      "target_max_c": 100.0,
-      "supply_mode": "manual",
-      "bmc": {
-        "host": "192.168.2.165",
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S1_PASSWORD",
-        "cipher_suite": 17,
-        "timeout_s": 15,
-        "sol_helper_argv": [
-          "python3",
-          "native/stl_ssh_console_bridge.py"
-        ],
-        "console_transport": "ssh_console",
-        "ssh_console_port": 2200,
-        "ssh_known_hosts": "data/ssh_known_hosts"
-      },
-      "console": {
-        "transport": "ssh_console",
-        "host": "192.168.2.165",
-        "port": 2200,
-        "user": "ADMIN",
-        "password_env": "STL_BMC_S1_PASSWORD",
-        "known_hosts": "data/ssh_known_hosts",
-        "write_chunk_bytes": 8,
-        "write_gap_ms": 20.0
-      }
-    },
-    {
-      "station_id": "S3",
-      "frontend_index": 2,
-      "name": "工位 003 (离线未配置)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0.0,
-      "target_max_c": 100.0,
-      "supply_mode": "manual"
-    },
-    {
-      "station_id": "S4",
-      "frontend_index": 3,
-      "name": "工位 004 (离线未配置)",
-      "mode": "hardware",
-      "cpu_count": 2,
-      "channels_per_cpu": 12,
-      "target_min_c": 0.0,
-      "target_max_c": 100.0,
-      "supply_mode": "manual"
-    }
-  ],
-  "recipes": [
-    {
-      "recipe_id": "GNR-DDR5-ASSISTED",
-      "name": "GNR 人工核对流程(温控接入后可启动)",
-      "revision": 1,
-      "profile_id": "cxmt-live-gnr",
-      "dimm_target_c": 70.0,
-      "preheat_air_c": 60.0,
-      "preheat_hold_s": 2.0,
-      "preheat_timeout_s": 60.0,
-      "phase_timeout_s": 900.0,
-      "finish_timeout_s": 10.0,
-      "run_rmt": true,
-      "run_amt": true,
-      "run_mt": true,
-      "stage1_commands": [],
-      "mt_command": "FS0:\\EFI\\118.efi",
-      "required_artifact_kinds": [
-        "memtest_html"
-      ],
-      "notes": "现场辅助流程:已实测当前UIP的rmt enable/disable与admt enable/disable确认,以及CPU0/CPU1交互;完整RMT/AMEMDIAG执行尚未验证。当前UEFI只映射NVMe,EFI目录只有BOOT/redhat,未发现测试U盘。MemTest86SiteX64.efi来自历史文件名线索,profile保持人工启动。温控板和自动总供电尚未接入。",
-      "stop_on_test_error": true,
-      "metadata": {
-        "firmware_verified": "partial_uip_ack_and_uefi_shell",
-        "mt_launch": "manual_path_unverified",
-        "dimm_temperature": "UEFI后有效;BMC SDR只作为采样时间未知的诊断报告值",
-        "console_transport": "ssh_console_port_2200"
-      }
-    }
-  ],
-  "idle_poll_interval_s": 15
-}

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


+ 0 - 15
deploy/Dockerfile.qt-runtime

@@ -1,15 +0,0 @@
-# Reuse the site's installed, verified dependency image for an offline upgrade.
-# For a fresh installation use the project-root Dockerfile instead.
-ARG BASE_IMAGE=xjkj-stl:0.6.1-b66cfd7
-FROM ${BASE_IMAGE}
-WORKDIR /app
-COPY src/ /app/src/
-COPY native/ /app/native/
-COPY VERSION pyproject.toml README.md /app/
-ARG QT_BUILD_COMMIT=unknown
-ARG QT_BUILD_VERSION=0.8.0
-ENV PYTHONPATH=/app/src \
-    PYTHONUNBUFFERED=1 \
-    STL_BUILD_COMMIT=${QT_BUILD_COMMIT}
-LABEL org.opencontainers.image.version=${QT_BUILD_VERSION} \
-      org.opencontainers.image.revision=${QT_BUILD_COMMIT}

+ 1 - 9
deploy/stl-backend.env.example

@@ -1,10 +1,2 @@
-# Copy to /etc/xjkj-stl/stl-backend.env and fill the actual site credentials.
-# This is a systemd EnvironmentFile, not a shell script; do not add "export".
-# Names match config/hardware.example.json exactly. Empty values do not work.
+# Copy to /etc/xjkj-stl/stl-backend.env and fill the actual site BMC password.
 STL_BMC_S1_PASSWORD=
-STL_BMC_S2_PASSWORD=
-STL_BMC_S3_PASSWORD=
-STL_BMC_S4_PASSWORD=
-
-# Optional: enable only with hardware.json: "api_token_env": "STL_API_TOKEN".
-# STL_API_TOKEN=

+ 3 - 6
deploy/stl-backend.service

@@ -1,5 +1,5 @@
 [Unit]
-Description=XJKJ STL four-station memory thermal test backend
+Description=XJKJ-STL Native Memory High-Temperature Test Backend
 Wants=network-online.target
 After=network-online.target
 
@@ -8,18 +8,15 @@ Type=simple
 User=stl
 Group=stl
 WorkingDirectory=/opt/xjkj-stl
-Environment=PYTHONUNBUFFERED=1
 EnvironmentFile=/etc/xjkj-stl/stl-backend.env
-ExecStart=/opt/xjkj-stl/.venv/bin/stl-server --config /etc/xjkj-stl/hardware.json --data-dir /var/lib/xjkj-stl
+ExecStart=/usr/local/bin/stl_native_server --config /etc/xjkj-stl/station0-live.json --web-listen 0.0.0.0:8080 --data-dir /var/lib/xjkj-stl --web-dir /opt/xjkj-stl/web --contracts /opt/xjkj-stl/contracts/firmware-vd012.json
 StateDirectory=xjkj-stl
 StateDirectoryMode=0750
 UMask=0027
 Restart=on-failure
 RestartSec=3
-# SIGTERM goes to the Python owner first so its device helpers remain alive
-# during bounded shutdown/power-off. At the deadline, kill remaining children.
 KillMode=mixed
-TimeoutStopSec=120
+TimeoutStopSec=30
 
 [Install]
 WantedBy=multi-user.target

+ 16 - 12
docker-compose.yml

@@ -3,28 +3,32 @@ services:
     build:
       context: .
       args:
-        STL_VERSION: ${STL_VERSION}
-        STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-unknown}
-    image: xjkj-stl:${STL_VERSION:?Use scripts/run_container.sh}
+        STL_VERSION: ${STL_VERSION:-0.8.1.18}
+        STL_BUILD_COMMIT: ${STL_BUILD_COMMIT:-vd012-native}
+    image: xjkj-stl:0.8.1.18
     container_name: xjkj-stl-backend
     restart: unless-stopped
-    stop_grace_period: 120s
+    stop_grace_period: 30s
     network_mode: host
     volumes:
       - ./data:/app/data
       - ./config:/app/config:ro
+      - ./web:/app/web:ro
+      - ./contracts:/app/contracts:ro
     environment:
-      STL_BMC_S1_PASSWORD: ${STL_BMC_S1_PASSWORD:?Set local.env}
-      PYTHONUNBUFFERED: '1'
+      STL_BMC_S1_PASSWORD: ${STL_BMC_S1_PASSWORD:-Admin123@pl}
+      STL_BMC_S2_PASSWORD: ${STL_BMC_S2_PASSWORD:-Admin123@pl}
     command:
-      - python3
-      - -m
-      - stl_backend.server
+      - /usr/local/bin/stl_native_server
       - --config
-      - config/station0-live.json
-      - --listen
-      - 0.0.0.0:50051
+      - /app/config/station0-live.json
       - --web-listen
       - 0.0.0.0:8080
+      - --grpc-listen
+      - 0.0.0.0:50051
       - --data-dir
       - /app/data
+      - --web-dir
+      - /app/web
+      - --contracts
+      - /app/contracts/firmware-vd012.json

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


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


+ 16 - 1
docs/WEBSOCKET_API_ZH.md

@@ -1,4 +1,4 @@
-# XJKJ-STL 0.8.1.17:完整 WebSocket 接口手册
+# XJKJ-STL 0.8.1.18:完整 WebSocket 接口手册
 
 **Qt 前端精简纯净版对接请看 [QT_CLIENT_API_ZH.md](QT_CLIENT_API_ZH.md)(地址:`ws://192.168.2.79:8080/ws?view=qt-clean`)。** 本文是 `/ws`(或 `/ws?view=full`)的全部业务和诊断接口。后端同时支持三个接口:完整 WebSocket(`/ws`)、完整原生 gRPC(`:50051`)、Qt 专用精简纯净 WebSocket(`/ws?view=qt-clean`)。
 
@@ -1105,3 +1105,18 @@ UIP admt 是 UIP 参数,不属于 AMT 的配置重复项;AMT 菜单由自身
 ## 10. WebSocket 在后端的位置
 
 Qt 和现有 HTML 页面都经 `GET /ws` 升级 WebSocket,`transports/websocket.py` 校验 JSON,`transports/dispatcher.py` 做字段转换,再进入统一 BenchApi、命令队列、设备适配器和 SQLite。连接断开不删除已入队动作;只用 WebSocket 可以完整操作后端。
+
+## 11. 0.8.1.18 原生无锁工位 Actor 重构与扩展接口补充
+
+自 `0.8.1.18` 起,后端由原生高性能进程 `stl_native_server`(纯 `x86-64 SSE2` 基线 + CPUID 动态分派 `SSE2` / `SSE4.2+POPCNT` / `AVX2+BMI1/2`)承载,同时提供 `/ws`(完整版)、`:50051`(原生 HTTP/2 `stl.v1.BenchService` gRPC)与 `/ws?view=qt-clean`(Qt 精简纯净版),保持与上述全部既有消息兼容,并新增以下核心能力与 RPC:
+
+1. **阶段命名统一(`ICT`)与双机固件自适应**:
+   - 前端界面统一将原 `UIP` 显示为 `ICT`(`IMC Config Tool`:`ICT Stage 1` / `ICT Stage 2`),底层协议字段名(`uip`、`uip1`、`uip2`、`continue_uip`、`apply_uip`、`uip_overrides`)保持 100% 兼容。
+   - 自动识别并兼容 `.166`(`107_VD012` / `[Hovsee]` / `[AMT #]` 24 算法 `GNR-4.3.3`)与 `.165`(`[CxmtDdrTest]` / `[AMEMDIAG #]` 19 算法 `GNR-4.3.0`),暴露全部 **224 项 ICT 参数**与 **30 项 AMT 控制(27 项参数覆盖 + 3 项执行控制)**。
+2. **新增直调 RPC 与 `EnqueueCommand` 子动作**:
+   - `ReadCleanedUart`:基于单调递增 64 位 `clean_ring` 与 `Condvar` 的阻塞伪推送清洗文本流读取接口(参数 `station_id`、`offset`、`max_bytes`、`wait_ms`),初始连接或滞后超过 64 KB 时自动跃迁至最新尾部。
+   - `SetStageIntent`:阶段前任意时机预置 `uip1` / `amt` / `uip2` / `mt` 控制与配置意图,同一阶段多次修改严格遵循 **Last-Write-Wins**,到达对应提示符时自动消费。
+   - `ConfirmDimmReplacement`:解除异常停机换条挂起状态(`awaiting_dimm_replacement = false`)。
+   - `SubmitTaskBatch` / `ControlTaskBatch` / `GetTaskBatch` / `GetTaskStatus`:支持后端多 Profile 批次循环队列与前端自维护队列(配合服务端主动推送 `event: "task_complete"` 及 **7 个语义独立的阶段完成标志** `ict_stage1_complete`、`training_complete`、`rmt_complete`、`amt_complete`、`ict_stage2_complete`、`uefi_complete`、`mt_pass_complete`)。
+   - `SaveProfile` / `DeleteProfile` / `LoadProfileToWorkspace` / `ApplyErrorPreset` / `ClearTerminalView` / `ReadAuditLogs`:Profile 配置库、零加压时序拉偏安全预设、单调字节偏移清空锚定、以及 `config_audit.jsonl` 实时变更审计查询。
+   - `connections.console.transport` 新增 `"local_serial"`(固定物理串口 `/dev/ttyUSB0`,115200 8N1 无流控),与 `"tcp_serial"`、`"ipmi_sol"`、`"ssh_console"` 共同维护,并实时上报 `console_online`。

+ 0 - 25
examples/qt-clean/config.json

@@ -1,25 +0,0 @@
-{
-  "_comment": "内存参数配置:详情页「内存参数设置」页签从这里加载默认值,键名与界面控件一一对应。errhandle / ap 为开关(true=enable,false=disable),其余为数值(mem vdd / mem vddq 单位 mV,时序参数单位 tCK)。",
-  "memoryParams": {
-    "mem vdd": 1070,
-    "mem vddq": 1070,
-    "tCL": 44,
-    "tRCD": 43,
-    "tRP": 43,
-    "tRAS": 86,
-    "tRFC": 425,
-    "tRTP": 20,
-    "trrd_l": 13,
-    "tWTR_S": 7,
-    "tWTR_L": 27,
-    "tWR": 80,
-    "tCCD_L": 13,
-    "trefi": 23046,
-    "tRFCsb": 123,
-    "errhandle": false,
-    "ap": false
-  },
-  "backend": {
-    "url": "ws://192.168.2.79:8080/ws?view=qt"
-  }
-}

+ 0 - 9
examples/qt-websocket/CMakeLists.txt

@@ -1,9 +0,0 @@
-cmake_minimum_required(VERSION 3.16)
-project(stl_ws_sample LANGUAGES CXX)
-set(CMAKE_CXX_STANDARD 17)
-set(CMAKE_CXX_STANDARD_REQUIRED ON)
-find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core Network WebSockets)
-find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Network WebSockets)
-add_executable(stl_ws_sample main.cpp)
-target_link_libraries(stl_ws_sample PRIVATE
-    Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::WebSockets)

+ 0 - 105
examples/qt-websocket/main.cpp

@@ -1,105 +0,0 @@
-// Read-only Qt 5.15 / Qt 6 example: two concurrent calls on one WebSocket.
-// No protobuf, gRPC client, or hardware commands are required.
-#include <QCoreApplication>
-#include <QDebug>
-#include <QHash>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QNetworkRequest>
-#include <QStringList>
-#include <QTimer>
-#include <QUrl>
-#include <QUuid>
-#include <QWebSocket>
-
-int main(int argc, char **argv)
-{
-    QCoreApplication app(argc, argv);
-    const auto args = app.arguments();
-    const QUrl url(args.value(1, QStringLiteral("ws://127.0.0.1:8080/ws")));
-    const QString station = args.value(2, QStringLiteral("S1"));
-    QWebSocket socket;
-    QHash<QString, QString> pending; // request id -> method, never assume reply order
-    bool done = false;
-    int failures = 0;
-
-    auto finish = [&](int code) {
-        if (done) return;
-        done = true;
-        socket.close();
-        app.exit(code);
-    };
-    auto call = [&](const QString &method, const QJsonObject &params) {
-        const QString id = QUuid::createUuid().toString(QUuid::WithoutBraces);
-        pending.insert(id, method);
-        const QJsonObject frame{{"v", 1}, {"id", id}, {"method", method}, {"params", params}};
-        socket.sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
-    };
-
-    QObject::connect(&socket, &QWebSocket::connected, &app, [&] {
-        call(QStringLiteral("GetSystemInfo"), {});
-        call(QStringLiteral("GetStationControl"), {{"station_id", station}});
-    });
-    QObject::connect(&socket, &QWebSocket::textMessageReceived, &app, [&](const QString &text) {
-        QJsonParseError parse;
-        const auto doc = QJsonDocument::fromJson(text.toUtf8(), &parse);
-        if (parse.error != QJsonParseError::NoError || !doc.isObject()) {
-            qWarning() << "Invalid JSON reply";
-            finish(1);
-            return;
-        }
-        const auto frame = doc.object();
-        if (frame.value("v").toInt() != 1 || !frame.value("id").isString()
-            || !frame.value("ok").isBool()) {
-            qWarning() << "Invalid JSON v1 response envelope";
-            finish(1);
-            return;
-        }
-        const QString id = frame.value("id").toString();
-        if (!pending.contains(id)) return;
-        const QString method = pending.take(id);
-        if (!frame.value("ok").toBool()) {
-            qWarning().noquote() << method << QJsonDocument(frame.value("error").toObject()).toJson(QJsonDocument::Compact);
-            ++failures;
-        } else {
-            const auto result = frame.value("result").toObject();
-            if (method == QStringLiteral("GetSystemInfo")) {
-                qInfo() << "version" << result.value("version").toString()
-                        << "commit" << result.value("commit").toString();
-            } else {
-                const auto firmware = result.value("firmware").toObject();
-                const auto mainStage = firmware.value("stage_progress").toObject().value("main").toObject();
-                qInfo() << "station" << station << "main stage" << mainStage.value("id").toString()
-                        << "DIMM slots" << result.value("dimms").toArray().size();
-                qInfo().noquote() << "prompt:" << QJsonDocument(firmware.value("console_prompt").toObject()).toJson(QJsonDocument::Compact);
-            }
-        }
-        if (pending.isEmpty()) finish(failures ? 1 : 0);
-    });
-    QObject::connect(&socket, &QWebSocket::disconnected, &app, [&] {
-        if (!done) {
-            qWarning() << "Disconnected; requests are not replayed" << pending.keys();
-            finish(1);
-        }
-    });
-    auto socketError = [&](QAbstractSocket::SocketError) {
-        qWarning().noquote() << socket.errorString();
-        finish(1);
-    };
-#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
-    QObject::connect(&socket, &QWebSocket::errorOccurred, &app, socketError);
-#else
-    QObject::connect(&socket, static_cast<void (QWebSocket::*)(QAbstractSocket::SocketError)>(&QWebSocket::error), &app, socketError);
-#endif
-    QTimer::singleShot(15000, &app, [&] {
-        if (!done) { qWarning() << "Reply timeout"; finish(1); }
-    });
-    QNetworkRequest request(url);
-    const auto token = qgetenv("STL_API_TOKEN");
-    if (!token.isEmpty()) request.setRawHeader("Authorization", "Bearer " + token);
-    // Open after exec() starts: an immediate connection error must be able to
-    // exit the event loop, rather than calling exit() before it is running.
-    QTimer::singleShot(0, &app, [&socket, request] { socket.open(request); });
-    return app.exec();
-}

+ 0 - 24
native/build_sol_helper.py

@@ -1,24 +0,0 @@
-#!/usr/bin/env python3
-"""Build against installed FreeIPMI, or explicit matching include/library paths."""
-import argparse
-import os
-from pathlib import Path
-import subprocess
-
-parser = argparse.ArgumentParser()
-parser.add_argument("--include-dir", type=Path)
-parser.add_argument("--library-dir", type=Path)
-parser.add_argument("--output", type=Path, default=Path(__file__).resolve().parent / "stl-sol-helper")
-args = parser.parse_args()
-args.output.parent.mkdir(parents=True, exist_ok=True)
-argv = [os.environ.get("CXX", "c++"), "-std=c++11", "-O2", "-Wall", "-Wextra"]
-if args.include_dir:
-    argv += ["-I", str(args.include_dir.resolve())]
-if args.library_dir:
-    library_dir = str(args.library_dir.resolve())
-    # RPATH also covers libipmiconsole's libfreeipmi dependency when testing a
-    # matching private build. Installed distribution packages need no override.
-    argv += ["-L", library_dir, "-Wl,--disable-new-dtags", "-Wl,-rpath," + library_dir]
-argv += [str(Path(__file__).resolve().parent / "sol_helper.cpp"), "-lipmiconsole", "-o", str(args.output)]
-subprocess.run(argv, check=True)
-print(args.output.resolve())

+ 0 - 44
native/example_json_bridge.py

@@ -1,44 +0,0 @@
-#!/usr/bin/env python3
-"""Executable JSONL bridge contract example. SIMULATION ONLY, no hardware I/O.
-
-Replace operation bodies with your documented thermal-board / supply protocol.
-The explicit --simulate flag prevents accidental use as a real device driver.
-"""
-import argparse
-import json
-import sys
-
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument("--simulate", action="store_true", required=True)
-parser.parse_args()
-supply = "off"
-target = 80.0
-air = 25.0
-print("SIMULATION JSONL bridge; no physical I/O", file=sys.stderr, flush=True)
-for line in sys.stdin:
-    request = {}
-    try:
-        request = json.loads(line)
-        op, args = request["operation"], request["arguments"]
-        if op == "supply_set":
-            if type(args["on"]) is not bool:
-                raise ValueError("on must be boolean")
-            supply = "on" if args["on"] else "off"
-            result = {"accepted": True}
-        elif op == "supply_read":
-            result = {"state": supply, "simulated": True}
-        elif op == "set_target":
-            target = float(args["target_c"])
-            result = {"confirmed_target_c": target, "simulated": True}
-        elif op == "read_telemetry":
-            air += (target - air) * 0.7
-            result = {"air_c": round(air, 2) if supply == "on" else None,
-                      "dimms": [], "quality": "valid" if supply == "on" else "unavailable",
-                      "dimm_quality": "unavailable_in_phase", "board_state": supply,
-                      "confirmed_target_c": target, "simulated": True}
-        else:
-            raise ValueError("unsupported operation")
-        reply = {"id": request["id"], "ok": True, "result": result}
-    except (ValueError, KeyError, TypeError):
-        reply = {"id": request.get("id"), "ok": False, "error": "invalid or unsupported request"}
-    print(json.dumps(reply, allow_nan=False), flush=True)

+ 0 - 189
native/sol_helper.cpp

@@ -1,189 +0,0 @@
-// Linux SOL process bridge. stdin/stdout: raw serial bytes. stderr: JSON status.
-// Uses FreeIPMI libipmiconsole, with both three- and four-argument ctx_create.
-// No Qt dependency. Credentials arrive through the environment, never argv.
-#include <ipmiconsole.h>
-#include <poll.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <cerrno>
-#include <chrono>
-#include <csignal>
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-#include <string>
-#include <type_traits>
-
-namespace {
-volatile sig_atomic_t stopped = 0;
-void stop_handler(int) { stopped = 1; }
-void status(const char *event, int code = 0) {
-    std::fprintf(stderr, "{\"event\":\"%s\",\"code\":%d}\n", event, code);
-    std::fflush(stderr);
-}
-template <typename T> struct Arity;
-template <typename R, typename... A> struct Arity<R (*)(A...)> {
-    static const int value = sizeof...(A);
-};
-template <typename T> struct Fourth;
-template <typename R, typename A, typename B, typename C, typename D>
-struct Fourth<R (*)(A, B, C, D)> { typedef typename std::remove_pointer<D>::type type; };
-template <int N> struct Create;
-template <> struct Create<3> {
-    template <typename F> static ipmiconsole_ctx_t call(F fn, const char *host,
-            ipmiconsole_ipmi_config *ic, ipmiconsole_protocol_config *pc) {
-        return fn(host, ic, pc);
-    }
-};
-template <> struct Create<4> {
-    template <typename F> static ipmiconsole_ctx_t call(F fn, const char *host,
-            ipmiconsole_ipmi_config *ic, ipmiconsole_protocol_config *pc) {
-        typename Fourth<F>::type ec;
-        std::memset(&ec, 0, sizeof(ec));
-        // Do not take over another session unless explicitly requested via STL_SOL_STEAL_INUSE=1
-        const char *steal = std::getenv("STL_SOL_STEAL_INUSE");
-        if (!steal || std::strcmp(steal, "1") != 0) {
-#ifdef IPMICONSOLE_BEHAVIOR_ERROR_ON_SOL_INUSE
-            ec.behavior_flags = IPMICONSOLE_BEHAVIOR_ERROR_ON_SOL_INUSE;
-#endif
-        }
-        return fn(host, ic, pc, &ec);
-    }
-};
-bool write_all(int fd, const char *data, size_t size) {
-    while (size && !stopped) {
-        ssize_t n = ::write(fd, data, size);
-        if (n > 0) { data += n; size -= static_cast<size_t>(n); continue; }
-        if (n < 0 && errno == EINTR) continue;
-        if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
-            pollfd p = {fd, POLLOUT, 0};
-            if (::poll(&p, 1, 5000) > 0 && (p.revents & POLLOUT)) continue;
-        }
-        return false;
-    }
-    return size == 0;
-}
-bool nonblock(int fd) {
-    int flags = ::fcntl(fd, F_GETFL, 0);
-    return flags >= 0 && ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0;
-}
-bool drain_console(int fd, bool &eof) {
-    char buf[8192];
-    eof = false;
-    for (;;) {
-        ssize_t n = ::read(fd, buf, sizeof(buf));
-        if (n > 0) {
-            if (!write_all(STDOUT_FILENO, buf, static_cast<size_t>(n))) return false;
-            continue;
-        }
-        if (n == 0) { eof = true; return true; }
-        if (errno == EINTR) continue;
-        if (errno == EAGAIN || errno == EWOULDBLOCK) return true;
-        return false;
-    }
-}
-}
-
-int main(int argc, char **argv) {
-    if (argc == 2 && std::strcmp(argv[1], "--help") == 0) {
-        std::fprintf(stderr, "stl-sol-helper: STL_SOL_HOST, STL_SOL_USER, STL_SOL_PASSWORD; "
-            "optional STL_SOL_CIPHER_SUITE (default 17). stdin/stdout are raw SOL bytes.\n");
-        return 0;
-    }
-    if (argc != 1) { status("error", 1001); return 2; }
-    const char *host_env = std::getenv("STL_SOL_HOST");
-    const char *user_env = std::getenv("STL_SOL_USER");
-    const char *pass_env = std::getenv("STL_SOL_PASSWORD");
-    if (!host_env || !*host_env || !user_env || !*user_env || !pass_env || !*pass_env) {
-        status("error", 1002); return 2;
-    }
-    std::string host(host_env), user(user_env), pass(pass_env);
-    const char *suite_env = std::getenv("STL_SOL_CIPHER_SUITE");
-    char *end = nullptr;
-    long suite = suite_env ? std::strtol(suite_env, &end, 10) : 17;
-    if ((suite_env && (!*suite_env || *end)) || suite < 0 || suite > 255) {
-        status("error", 1003); return 2;
-    }
-    std::signal(SIGTERM, stop_handler);
-    std::signal(SIGINT, stop_handler);
-    std::signal(SIGPIPE, SIG_IGN);
-    if (ipmiconsole_engine_init(1, 0) < 0) { status("error", 1004); return 2; }
-    ipmiconsole_ipmi_config ic;
-    ipmiconsole_protocol_config pc;
-    std::memset(&ic, 0, sizeof(ic));
-    std::memset(&pc, 0, sizeof(pc));
-    ic.username = &user[0];
-    ic.password = &pass[0];
-    ic.privilege_level = IPMICONSOLE_PRIVILEGE_ADMIN;
-    ic.cipher_suite_id = static_cast<int>(suite);
-    pc.session_timeout_len = 60000;
-    pc.retransmission_timeout_len = 500;
-    pc.retransmission_backoff_count = 2;
-    pc.keepalive_timeout_len = 20000;
-    pc.retransmission_keepalive_timeout_len = 5000;
-    pc.acceptable_packet_errors_count = 16;
-    pc.maximum_retransmission_count = 16;
-    ipmiconsole_ctx_t ctx = Create<Arity<decltype(&ipmiconsole_ctx_create)>::value>::call(
-        &ipmiconsole_ctx_create, host.c_str(), &ic, &pc);
-    int code = 0;
-    if (!ctx) { status("error", 1005); code = 2; }
-    else if (ipmiconsole_engine_submit(ctx, nullptr, nullptr) < 0) {
-        status("error", ipmiconsole_ctx_errnum(ctx)); code = 2;
-    } else {
-        status("connecting");
-        auto start = std::chrono::steady_clock::now();
-        int fd = -1;
-        while (!stopped) {
-            ipmiconsole_ctx_status_t state = ipmiconsole_ctx_status(ctx);
-            if (state == IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED) {
-                fd = ipmiconsole_ctx_fd(ctx);
-                if (fd < 0) { status("error", 1008); code = 4; }
-                break;
-            }
-            if (state == IPMICONSOLE_CTX_STATUS_SOL_ERROR || state == IPMICONSOLE_CTX_STATUS_ERROR) {
-                status("error", ipmiconsole_ctx_errnum(ctx)); code = 3; break;
-            }
-            if (std::chrono::duration_cast<std::chrono::seconds>(
-                    std::chrono::steady_clock::now() - start).count() >= 25) {
-                status("error", 1006); code = 3; break;
-            }
-            ::poll(nullptr, 0, 100);
-        }
-        if (fd >= 0 && !stopped) {
-            if (!nonblock(fd) || !nonblock(STDOUT_FILENO)) {
-                status("error", 1007); code = 4;
-            } else {
-                status("ready");
-                while (!stopped) {
-                    ipmiconsole_ctx_status_t state = ipmiconsole_ctx_status(ctx);
-                    if (state != IPMICONSOLE_CTX_STATUS_SOL_ESTABLISHED) {
-                        bool eof = false;
-                        drain_console(fd, eof);
-                        status("error", ipmiconsole_ctx_errnum(ctx)); code = 4; break;
-                    }
-                    pollfd fds[2] = {{fd, POLLIN, 0}, {STDIN_FILENO, POLLIN, 0}};
-                    int n = ::poll(fds, 2, 200);
-                    if (n < 0) { if (errno == EINTR) continue; code = 4; break; }
-                    char buf[8192];
-                    if (fds[0].revents & (POLLIN | POLLHUP | POLLERR)) {
-                        bool eof = false;
-                        if (!drain_console(fd, eof) || eof) { code = 4; break; }
-                    }
-                    if (fds[1].revents & POLLIN) {
-                        ssize_t count = ::read(STDIN_FILENO, buf, sizeof(buf));
-                        if (count > 0 && !write_all(fd, buf, static_cast<size_t>(count))) { code = 4; break; }
-                        if (count == 0) break;
-                        if (count < 0 && errno != EAGAIN && errno != EINTR) { code = 4; break; }
-                    }
-                    if (fds[0].revents & (POLLERR | POLLHUP | POLLNVAL)) { code = 4; break; }
-                    if (fds[1].revents & (POLLERR | POLLHUP | POLLNVAL)) break;
-                }
-            }
-        }
-    }
-    if (ctx) ipmiconsole_ctx_destroy(ctx);
-    ipmiconsole_engine_teardown(1);
-    if (code) status("error", code);
-    status("closed");
-    return code;
-}

+ 26 - 0
native/stl_accel/build.sh

@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+set -euo pipefail
+unset LD_LIBRARY_PATH
+cd "$(dirname "$0")"
+ROOT_DIR="$(cd ../.. && pwd)"
+BUILD_DIR="${ROOT_DIR:?}/build/native"
+mkdir -p "${BUILD_DIR:?}"
+
+re2c -W -Werror parser_re2c.re -o "${BUILD_DIR}/parser_re2c.c"
+gcc -c -O3 -fPIC -march=x86-64 -I. "${BUILD_DIR}/parser_re2c.c" -o "${BUILD_DIR}/parser_re2c.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"
+zig build-obj -O ReleaseFast -fPIC -mcpu=x86_64 -femit-bin="${BUILD_DIR}/zig_kernels.o" zig_kernels.zig
+gcc -c -O3 -fPIC -march=x86-64 -I. c_bridge.c -o "${BUILD_DIR}/c_bridge.o"
+ar rcs "${BUILD_DIR}/libstl_kernels.a" \
+    "${BUILD_DIR}/parser_re2c.o" \
+    "${BUILD_DIR}/opencl_batch.o" \
+    "${BUILD_DIR}/scan_asm.o" \
+    "${BUILD_DIR}/zig_kernels.o" \
+    "${BUILD_DIR}/c_bridge.o"
+
+rustc -O -C target-cpu=x86-64 -C lto=thin -C codegen-units=1 -C strip=debuginfo src/main.rs \
+    -L "${BUILD_DIR}" -l static=stl_kernels -l util -l dl -o "${BUILD_DIR}/stl_native_server"
+rustc --test -O -C target-cpu=x86-64 src/main.rs \
+    -L "${BUILD_DIR}" -l static=stl_kernels -l util -l dl -o "${BUILD_DIR}/stl_native_tests"
+(cd "${ROOT_DIR}" && "${BUILD_DIR}/stl_native_tests")

+ 817 - 0
native/stl_accel/c_bridge.c

@@ -0,0 +1,817 @@
+/*
+ * c_bridge.c — XJKJ-STL Native C Runtime Bridge (v0.8.1.18)
+ *
+ * Compiled strictly with -O3 -march=x86-64 (pure SSE2 baseline, no AVX/POPCNT
+ * emitted by the compiler) so dual-core Celeron/Pentium (Sandy Bridge..Coffee Lake)
+ * never trigger SIGILL. Runtime CPUID + XGETBV dispatches SSE2 / SSE4.2 / AVX2
+ * assembly kernels dynamically.
+ */
+
+#define _GNU_SOURCE
+#include "stl_accel.h"
+
+#include <arpa/inet.h>
+#include <cpuid.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <poll.h>
+#include <pty.h>
+#include <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/epoll.h>
+#include <sys/eventfd.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/timerfd.h>
+#include <sys/uio.h>
+#include <sys/wait.h>
+#include <termios.h>
+#include <time.h>
+#include <unistd.h>
+
+/* =========================================================================
+ * 1. Runtime CPUID + XGETBV ISA Tier Detection & Dispatch
+ * ========================================================================= */
+typedef struct {
+    uint32_t isa_tier;
+    uint32_t has_sse42;
+    uint32_t has_avx2;
+    uint32_t has_bmi2;
+    char     cpu_brand[64];
+    char     tier_name[32];
+} StlHwCapsCompat;
+
+static pthread_once_t g_hw_once        = PTHREAD_ONCE_INIT;
+static int            g_detected_tier  = STL_ISA_SSE2;
+static int            g_forced_tier    = -1;
+static StlHwCapsCompat g_hw_caps;
+
+static void detect_hw_once(void) {
+    memset(&g_hw_caps, 0, sizeof(g_hw_caps));
+
+    unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0;
+    unsigned int max_leaf = __get_cpuid_max(0, NULL);
+    int has_sse42   = 0;
+    int has_popcnt  = 0;
+    int has_osxsave = 0;
+    int has_avx     = 0;
+    int has_avx2    = 0;
+    int has_bmi1    = 0;
+    int has_bmi2    = 0;
+
+    if (max_leaf >= 1 && __get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
+        has_sse42   = (ecx & (1u << 20)) != 0;
+        has_popcnt  = (ecx & (1u << 23)) != 0;
+        has_osxsave = (ecx & (1u << 27)) != 0;
+        has_avx     = (ecx & (1u << 28)) != 0;
+    }
+
+    int ymm_os_ok = 0;
+    if (has_osxsave && has_avx) {
+        uint64_t xcr0 = asm_xgetbv_eax0();
+        ymm_os_ok = ((xcr0 & 0x6ULL) == 0x6ULL);
+    }
+
+    if (max_leaf >= 7 && __get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx)) {
+        has_bmi1 = (ebx & (1u << 3)) != 0;
+        has_avx2 = (ebx & (1u << 5)) != 0;
+        has_bmi2 = (ebx & (1u << 8)) != 0;
+    }
+
+    if (ymm_os_ok && has_avx2 && has_bmi1 && has_bmi2 && has_sse42 && has_popcnt) {
+        g_detected_tier = STL_ISA_AVX2_BMI;
+    } else if (has_sse42 && has_popcnt) {
+        g_detected_tier = STL_ISA_SSE42_POPCNT;
+    } else {
+        g_detected_tier = STL_ISA_SSE2;
+    }
+
+    /* Read CPU brand string (leaves 0x80000002..0x80000004) */
+    unsigned int max_ext = __get_cpuid_max(0x80000000u, NULL);
+    if (max_ext >= 0x80000004u) {
+        uint32_t brand_words[12];
+        __get_cpuid(0x80000002u, &brand_words[0], &brand_words[1], &brand_words[2], &brand_words[3]);
+        __get_cpuid(0x80000003u, &brand_words[4], &brand_words[5], &brand_words[6], &brand_words[7]);
+        __get_cpuid(0x80000004u, &brand_words[8], &brand_words[9], &brand_words[10], &brand_words[11]);
+        memcpy(g_hw_caps.cpu_brand, brand_words, 48);
+        g_hw_caps.cpu_brand[48] = '\0';
+    } else {
+        snprintf(g_hw_caps.cpu_brand, sizeof(g_hw_caps.cpu_brand), "x86_64-generic");
+    }
+
+    g_hw_caps.isa_tier  = (uint32_t)g_detected_tier;
+    g_hw_caps.has_sse42 = (uint32_t)(has_sse42 && has_popcnt);
+    g_hw_caps.has_avx2  = (uint32_t)(ymm_os_ok && has_avx2);
+    g_hw_caps.has_bmi2  = (uint32_t)has_bmi2;
+    snprintf(g_hw_caps.tier_name, sizeof(g_hw_caps.tier_name), "%s", stl_isa_tier_name(g_detected_tier));
+}
+
+void c_init_once_hw_dispatch(void) {
+    pthread_once(&g_hw_once, detect_hw_once);
+}
+
+int stl_cpu_tier_detect(void) {
+    pthread_once(&g_hw_once, detect_hw_once);
+    return g_detected_tier;
+}
+
+int stl_active_isa_tier(void) {
+    pthread_once(&g_hw_once, detect_hw_once);
+    int forced = __atomic_load_n(&g_forced_tier, __ATOMIC_RELAXED);
+    if (forced >= STL_ISA_SSE2 && forced <= STL_ISA_AVX2_BMI) {
+        if (forced <= g_detected_tier) return forced;
+    }
+    return g_detected_tier;
+}
+
+void stl_force_isa_tier(int tier) {
+    pthread_once(&g_hw_once, detect_hw_once);
+    __atomic_store_n(&g_forced_tier, tier, __ATOMIC_RELAXED);
+}
+
+const char *stl_isa_tier_name(int tier) {
+    switch (tier) {
+        case STL_ISA_AVX2_BMI:     return "AVX2+BMI1/2";
+        case STL_ISA_SSE42_POPCNT: return "SSE4.2+POPCNT";
+        default:                   return "SSE2-baseline";
+    }
+}
+
+void c_get_hw_caps(StlHwCapsCompat *out_caps) {
+    pthread_once(&g_hw_once, detect_hw_once);
+    if (!out_caps) return;
+    *out_caps = g_hw_caps;
+    int active = stl_active_isa_tier();
+    out_caps->isa_tier = (uint32_t)active;
+    snprintf(out_caps->tier_name, sizeof(out_caps->tier_name), "%s", stl_isa_tier_name(active));
+}
+
+size_t stl_base64_encode(const uint8_t *src, size_t len, uint8_t *dst) {
+    if (!src || !dst || len == 0) return 0;
+    int tier = stl_active_isa_tier();
+    if (tier >= STL_ISA_AVX2_BMI) {
+        return asm_base64_encode_avx2(src, len, dst);
+    }
+    return asm_base64_encode_sse2(src, len, dst);
+}
+
+void stl_clean_stream_init(StlCleanStreamState *state) {
+    if (!state) return;
+    memset(state, 0, sizeof(*state));
+}
+
+void stl_clean_stream_clear_halfline(StlCleanStreamState *state) {
+    if (!state) return;
+    state->half_len    = 0;
+    state->tag_mask    = 0;
+    state->first_nonws = 0;
+    state->cur_col     = 0;
+    state->prev_was_cr = 0;
+    state->esc_state   = 0;
+}
+
+void stl_clean_split_classify(
+    StlCleanStreamState *state,
+    const uint8_t       *src,
+    size_t               src_len,
+    StlCleanOutput      *out) {
+    if (!state || !out) return;
+    if (!src || src_len == 0) {
+        out->src_consumed = 0;
+        return;
+    }
+    int tier = stl_active_isa_tier();
+    if (tier >= STL_ISA_AVX2_BMI) {
+        asm_clean_split_classify_avx2(state, src, src_len, out);
+    } else if (tier >= STL_ISA_SSE42_POPCNT) {
+        asm_clean_split_classify_sse42(state, src, src_len, out);
+    } else {
+        asm_clean_split_classify_sse2(state, src, src_len, out);
+    }
+}
+
+/* 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)
+ * ========================================================================= */
+static size_t round_up_pow2_min2m(size_t v) {
+    size_t cap = 2u * 1024u * 1024u; /* 2 MiB hugepage granularity */
+    while (cap < v && cap < (1ULL << 30)) {
+        cap <<= 1;
+    }
+    return cap;
+}
+
+int stl_ring_init(StlRingBuf *rb, size_t requested_cap) {
+    if (!rb) return -1;
+    memset(rb, 0, sizeof(*rb));
+
+    size_t cap = round_up_pow2_min2m(requested_cap == 0 ? (8u * 1024u * 1024u) : requested_cap);
+    size_t page_sz = 4096u;
+    /* [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 guard_bytes = page_sz;
+    size_t total       = cap + pad_bytes + guard_bytes;
+
+    void *mem = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+    if (mem == MAP_FAILED) {
+        return -1;
+    }
+
+#ifdef MADV_HUGEPAGE
+    (void)madvise(mem, cap, MADV_HUGEPAGE);
+#endif
+
+    /* Arm hardware guard page immediately after the 4KB tail-padding page */
+    uint8_t *base = (uint8_t *)mem;
+    memset(base + cap, 0, pad_bytes);
+    if (mprotect(base + cap + pad_bytes, guard_bytes, PROT_NONE) != 0) {
+        munmap(mem, total);
+        return -1;
+    }
+
+    rb->buf          = base;
+    rb->cap          = cap;
+    rb->mask         = cap - 1;
+    rb->mmap_total   = total;
+    rb->base_offset  = 0;
+    rb->write_offset = 0;
+    return 0;
+}
+
+void stl_ring_destroy(StlRingBuf *rb) {
+    if (!rb) return;
+    if (rb->buf && rb->mmap_total > 0) {
+        munmap(rb->buf, rb->mmap_total);
+    }
+    memset(rb, 0, sizeof(*rb));
+}
+
+uint64_t stl_ring_append(StlRingBuf *rb, const uint8_t *data, size_t len) {
+    if (!rb || !rb->buf) return 0;
+    if (!data || len == 0) return rb->write_offset;
+
+    if (len >= rb->cap) {
+        /* Input chunk exceeds entire ring capacity: retain trailing cap bytes */
+        const uint8_t *tail = data + (len - rb->cap);
+        uint64_t new_wo = rb->write_offset + (uint64_t)len;
+        uint64_t new_bo = new_wo - (uint64_t)rb->cap;
+        size_t pos = (size_t)(new_bo & rb->mask);
+        size_t first = rb->cap - pos;
+        memcpy(rb->buf + pos, tail, first);
+        if (first < rb->cap) {
+            memcpy(rb->buf, tail + first, rb->cap - first);
+        }
+        memset(rb->buf + rb->cap, 0, 64);
+        rb->write_offset = new_wo;
+        rb->base_offset  = new_bo;
+        return rb->write_offset;
+    }
+
+    size_t pos   = (size_t)(rb->write_offset & rb->mask);
+    size_t first = rb->cap - pos;
+    if (first >= len) {
+        memcpy(rb->buf + pos, data, len);
+    } else {
+        memcpy(rb->buf + pos, data, first);
+        memcpy(rb->buf, data + first, len - first);
+    }
+    /* Ensure 64-byte SIMD tail padding stays zeroed */
+    memset(rb->buf + rb->cap, 0, 64);
+
+    rb->write_offset += (uint64_t)len;
+    if (rb->write_offset - rb->base_offset > (uint64_t)rb->cap) {
+        /* Slide oldest bound forward; write_offset NEVER regresses */
+        rb->base_offset = rb->write_offset - (uint64_t)rb->cap;
+    }
+    return rb->write_offset;
+}
+
+size_t stl_ring_read(
+    const StlRingBuf *rb,
+    uint64_t          req_offset,
+    uint8_t          *dst,
+    size_t            max_len,
+    uint64_t         *out_actual_start,
+    uint64_t         *out_next_offset) {
+    if (!rb || !rb->buf) {
+        if (out_actual_start) *out_actual_start = 0;
+        if (out_next_offset)  *out_next_offset  = 0;
+        return 0;
+    }
+
+    uint64_t start = req_offset;
+    if (start < rb->base_offset) {
+        /* Reader fell behind trimmed window: advance monotonically to base_offset */
+        start = rb->base_offset;
+    }
+    if (start >= rb->write_offset || !dst || max_len == 0) {
+        uint64_t cur = rb->write_offset;
+        if (out_actual_start) *out_actual_start = cur;
+        if (out_next_offset)  *out_next_offset  = cur;
+        return 0;
+    }
+
+    uint64_t avail = rb->write_offset - start;
+    size_t   n     = (avail < (uint64_t)max_len) ? (size_t)avail : max_len;
+    size_t   pos   = (size_t)(start & rb->mask);
+    size_t   first = rb->cap - pos;
+    if (first >= n) {
+        memcpy(dst, rb->buf + pos, n);
+    } else {
+        memcpy(dst, rb->buf + pos, first);
+        memcpy(dst + first, rb->buf, n - first);
+    }
+
+    if (out_actual_start) *out_actual_start = start;
+    if (out_next_offset)  *out_next_offset  = start + (uint64_t)n;
+    return n;
+}
+
+void stl_ring_clear_monotonic(StlRingBuf *rb) {
+    if (!rb) return;
+    /* Advance base_offset to write_offset so old data is logically trimmed WITHOUT resetting offset! */
+    rb->base_offset = rb->write_offset;
+}
+
+/* =========================================================================
+ * 3. epoll / timerfd / eventfd / TCP_NODELAY + writev / Core Affinity
+ * ========================================================================= */
+int stl_epoll_create(void) {
+    return epoll_create1(EPOLL_CLOEXEC);
+}
+
+int stl_epoll_ctl_fd(int epfd, int op, int fd, uint32_t events, uint64_t token) {
+    struct epoll_event ev;
+    memset(&ev, 0, sizeof(ev));
+    ev.events   = events;
+    ev.data.u64 = token;
+    return epoll_ctl(epfd, op, fd, &ev);
+}
+
+int stl_epoll_wait_tokens(
+    int       epfd,
+    uint64_t *out_tokens,
+    uint32_t *out_events,
+    int       max_ev,
+    int       timeout_ms) {
+    if (epfd < 0 || max_ev <= 0) return 0;
+    if (max_ev > 128) max_ev = 128;
+    struct epoll_event evs[128];
+    int n = epoll_wait(epfd, evs, max_ev, timeout_ms);
+    if (n <= 0) return 0;
+    for (int i = 0; i < n; i++) {
+        if (out_tokens) out_tokens[i] = evs[i].data.u64;
+        if (out_events) out_events[i] = evs[i].events;
+    }
+    return n;
+}
+
+int stl_timerfd_create_ms(uint64_t initial_ms, uint64_t interval_ms) {
+    int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
+    if (tfd < 0) return -1;
+    if (stl_timerfd_arm_ms(tfd, initial_ms, interval_ms) != 0) {
+        close(tfd);
+        return -1;
+    }
+    return tfd;
+}
+
+int stl_timerfd_arm_ms(int tfd, uint64_t initial_ms, uint64_t interval_ms) {
+    if (tfd < 0) return -1;
+    struct itimerspec its;
+    memset(&its, 0, sizeof(its));
+    its.it_value.tv_sec     = (time_t)(initial_ms / 1000ULL);
+    its.it_value.tv_nsec    = (long)((initial_ms % 1000ULL) * 1000000ULL);
+    its.it_interval.tv_sec  = (time_t)(interval_ms / 1000ULL);
+    its.it_interval.tv_nsec = (long)((interval_ms % 1000ULL) * 1000000ULL);
+    return timerfd_settime(tfd, 0, &its, NULL);
+}
+
+void stl_timerfd_drain(int tfd) {
+    if (tfd < 0) return;
+    uint64_t exp = 0;
+    while (read(tfd, &exp, sizeof(exp)) > 0) {}
+}
+
+int stl_eventfd_create(void) {
+    return eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
+}
+
+void stl_eventfd_notify(int efd) {
+    if (efd < 0) return;
+    uint64_t v = 1;
+    ssize_t _r = write(efd, &v, sizeof(v));
+    (void)_r;
+}
+
+void stl_eventfd_drain(int efd) {
+    if (efd < 0) return;
+    uint64_t v = 0;
+    while (read(efd, &v, sizeof(v)) > 0) {}
+}
+
+int stl_set_nonblocking_nodelay(int fd, int is_tcp) {
+    if (fd < 0) return -1;
+    int flags = fcntl(fd, F_GETFL, 0);
+    if (flags >= 0) {
+        (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
+    }
+    if (is_tcp) {
+        int one = 1;
+        (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
+        (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
+    }
+    return 0;
+}
+
+/* Merged WebSocket header + payload writev (eliminates 44ms delayed-ACK stall) */
+int64_t stl_ws_writev2(
+    int            fd,
+    const uint8_t *hdr,
+    size_t         hdr_len,
+    const uint8_t *body,
+    size_t         body_len) {
+    if (fd < 0) return -1;
+    size_t off0 = 0;
+    size_t off1 = 0;
+    size_t total = hdr_len + body_len;
+    size_t sent  = 0;
+
+    while (sent < total) {
+        struct iovec iov[2];
+        int iovcnt = 0;
+        if (off0 < hdr_len) {
+            iov[iovcnt].iov_base = (void *)(hdr + off0);
+            iov[iovcnt].iov_len  = hdr_len - off0;
+            iovcnt++;
+        }
+        if (off1 < body_len) {
+            iov[iovcnt].iov_base = (void *)(body + off1);
+            iov[iovcnt].iov_len  = body_len - off1;
+            iovcnt++;
+        }
+        ssize_t n = writev(fd, iov, iovcnt);
+        if (n > 0) {
+            size_t adv = (size_t)n;
+            sent += adv;
+            if (off0 < hdr_len) {
+                size_t rem0 = hdr_len - off0;
+                if (adv <= rem0) {
+                    off0 += adv;
+                    adv = 0;
+                } else {
+                    off0 = hdr_len;
+                    adv -= rem0;
+                }
+            }
+            off1 += adv;
+            continue;
+        }
+        if (n < 0 && errno == EINTR) continue;
+        if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
+            struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0 };
+            int pr = poll(&pfd, 1, 2000);
+            if (pr > 0) continue;
+            return -1;
+        }
+        return -1;
+    }
+    return (int64_t)sent;
+}
+
+void stl_pin_thread_to_core(int core_index) {
+    if (core_index < 0) return;
+    long ncores = sysconf(_SC_NPROCESSORS_ONLN);
+    if (ncores <= 0) return;
+    int target = core_index % (int)ncores;
+    cpu_set_t set;
+    CPU_ZERO(&set);
+    CPU_SET(target, &set);
+    (void)pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
+}
+
+/* =========================================================================
+ * 4. Serial / TCP-RS232 / SSH Console (ignore known_hosts!) / IPMI SOL PTYs
+ * ========================================================================= */
+int stl_open_tty_115200_raw(const char *path) {
+    if (!path || path[0] == '\0') return -1;
+    /* Safety guard: NEVER touch /dev/ttyUSB1 (reserved for unrelated board) */
+    if (strstr(path, "ttyUSB1") != NULL) {
+        return -1;
+    }
+    int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK | O_CLOEXEC);
+    if (fd < 0) return -1;
+
+    struct termios tio;
+    if (tcgetattr(fd, &tio) != 0) {
+        close(fd);
+        return -1;
+    }
+    cfmakeraw(&tio);
+    cfsetispeed(&tio, B115200);
+    cfsetospeed(&tio, B115200);
+    tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
+    tio.c_cflag |= (CS8 | CLOCAL | CREAD);
+    tio.c_iflag &= ~(IXON | IXOFF | IXANY);
+    tio.c_cc[VMIN]  = 0;
+    tio.c_cc[VTIME] = 0;
+    if (tcsetattr(fd, TCSANOW, &tio) != 0) {
+        close(fd);
+        return -1;
+    }
+    return fd;
+}
+
+int c_pty_open_serial_115200(const char *path) {
+    return stl_open_tty_115200_raw(path);
+}
+
+/* Open serial with configurable baud rate (115200 / 230400 / 460800 / 921600) for thermal hood */
+int c_open_tty_baud_raw(const char *path, int baud) {
+    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);
+    if (fd < 0) return -1;
+
+    struct termios tio;
+    if (tcgetattr(fd, &tio) != 0) {
+        close(fd);
+        return -1;
+    }
+    cfmakeraw(&tio);
+    speed_t sp = B115200;
+    if (baud == 921600) sp = B921600;
+    else if (baud == 460800) sp = B460800;
+    else if (baud == 230400) sp = B230400;
+    cfsetispeed(&tio, sp);
+    cfsetospeed(&tio, sp);
+    tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
+    tio.c_cflag |= (CS8 | CLOCAL | CREAD);
+    tio.c_iflag &= ~(IXON | IXOFF | IXANY);
+    tio.c_cc[VMIN]  = 0;
+    tio.c_cc[VTIME] = 0;
+    if (tcsetattr(fd, TCSANOW, &tio) != 0) {
+        close(fd);
+        return -1;
+    }
+    return fd;
+}
+
+int c_pty_open_tcp_serial(const char *host, int port, int timeout_ms) {
+    if (!host || host[0] == '\0' || port <= 0) return -1;
+    struct addrinfo hints, *res = NULL;
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_family   = AF_INET;
+    hints.ai_socktype = SOCK_STREAM;
+    char port_s[16];
+    snprintf(port_s, sizeof(port_s), "%d", port);
+    if (getaddrinfo(host, port_s, &hints, &res) != 0 || !res) return -1;
+
+    int sfd = socket(res->ai_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+    if (sfd < 0) {
+        freeaddrinfo(res);
+        return -1;
+    }
+    int one = 1;
+    (void)setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
+    (void)setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof(one));
+
+    int rc = connect(sfd, res->ai_addr, res->ai_addrlen);
+    freeaddrinfo(res);
+    if (rc != 0) {
+        if (errno != EINPROGRESS) {
+            close(sfd);
+            return -1;
+        }
+        struct pollfd pfd = { .fd = sfd, .events = POLLOUT, .revents = 0 };
+        int wait_ms = (timeout_ms > 0) ? timeout_ms : 1500;
+        if (poll(&pfd, 1, wait_ms) <= 0) {
+            close(sfd);
+            return -1;
+        }
+        int so_err = 0;
+        socklen_t slen = sizeof(so_err);
+        if (getsockopt(sfd, SOL_SOCKET, SO_ERROR, &so_err, &slen) != 0 || so_err != 0) {
+            close(sfd);
+            return -1;
+        }
+    }
+    return sfd;
+}
+
+/*
+ * Spawn SSH console (port 2200) inside non-blocking PTY.
+ * Explicitly ignores known_hosts host-key changes so swapping server motherboards
+ * never blocks or fails with REMOTE HOST IDENTIFICATION HAS CHANGED.
+ */
+int c_pty_spawn_ssh_console(
+    const char *host,
+    int         port,
+    const char *user,
+    const char *password,
+    const char *known_hosts_path,
+    int        *out_master_fd,
+    int        *out_child_pid) {
+    (void)known_hosts_path; /* Ignored intentionally per motherboard-swap requirement */
+    if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
+
+    int master_fd = -1;
+    pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);
+    if (pid < 0) return -1;
+
+    if (pid == 0) {
+        char port_str[16];
+        snprintf(port_str, sizeof(port_str), "%d", port > 0 ? port : 2200);
+        setenv("SSHPASS", password, 1);
+        setenv("TERM", "vt100", 1);
+        execlp(
+            "sshpass", "sshpass", "-e",
+            "ssh",
+            "-tt",
+            "-p", port_str,
+            "-o", "StrictHostKeyChecking=no",
+            "-o", "UserKnownHostsFile=/dev/null",
+            "-o", "GlobalKnownHostsFile=/dev/null",
+            "-o", "LogLevel=ERROR",
+            "-o", "ConnectTimeout=15",
+            "-o", "ServerAliveInterval=10",
+            "-o", "ServerAliveCountMax=3",
+            "-l", user,
+            host,
+            (char *)NULL);
+        _exit(127);
+    }
+
+    int flags = fcntl(master_fd, F_GETFL, 0);
+    if (flags >= 0) (void)fcntl(master_fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
+    *out_master_fd = master_fd;
+    *out_child_pid = (int)pid;
+    return 0;
+}
+
+int c_pty_spawn_ipmi_sol(
+    const char *host,
+    const char *user,
+    const char *password,
+    int        *out_master_fd,
+    int        *out_child_pid) {
+    if (!host || !user || !password || !out_master_fd || !out_child_pid) return -1;
+
+    int master_fd = -1;
+    pid_t pid = forkpty(&master_fd, NULL, NULL, NULL);
+    if (pid < 0) return -1;
+
+    if (pid == 0) {
+        setenv("IPMI_PASSWORD", password, 1);
+        setenv("TERM", "vt100", 1);
+        execlp(
+            "ipmitool", "ipmitool",
+            "-I", "lanplus",
+            "-C", "17",
+            "-H", host,
+            "-U", user,
+            "-E",
+            "sol", "activate",
+            (char *)NULL);
+        _exit(127);
+    }
+
+    int flags = fcntl(master_fd, F_GETFL, 0);
+    if (flags >= 0) (void)fcntl(master_fd, F_SETFL, flags | O_NONBLOCK | O_CLOEXEC);
+    *out_master_fd = master_fd;
+    *out_child_pid = (int)pid;
+    return 0;
+}
+
+/*
+ * Persistent non-blocking IPMI shell session per station:
+ * Keeps a single RMCP+ session open via `ipmitool -I lanplus -C <cipher> -H <host> -U <user> -E shell`
+ * connected to non-blocking stdin/stdout pipes so power & SDR queries execute with zero blocking!
+ */
+int c_spawn_persistent_ipmi_shell(
+    const char *host,
+    const char *user,
+    const char *password,
+    int         cipher_suite,
+    int        *out_stdin_fd,
+    int        *out_stdout_fd,
+    int        *out_child_pid) {
+    if (!host || !user || !password || !out_stdin_fd || !out_stdout_fd || !out_child_pid) return -1;
+    int in_pipe[2]  = {-1, -1};
+    int out_pipe[2] = {-1, -1};
+    if (pipe2(in_pipe, O_CLOEXEC) != 0) return -1;
+    if (pipe2(out_pipe, O_CLOEXEC) != 0) {
+        close(in_pipe[0]);
+        close(in_pipe[1]);
+        return -1;
+    }
+
+    pid_t pid = fork();
+    if (pid < 0) {
+        close(in_pipe[0]); close(in_pipe[1]);
+        close(out_pipe[0]); close(out_pipe[1]);
+        return -1;
+    }
+
+    if (pid == 0) {
+        dup2(in_pipe[0], STDIN_FILENO);
+        dup2(out_pipe[1], STDOUT_FILENO);
+        dup2(out_pipe[1], STDERR_FILENO);
+        close(in_pipe[0]); close(in_pipe[1]);
+        close(out_pipe[0]); close(out_pipe[1]);
+        setenv("IPMI_PASSWORD", password, 1);
+        char ciph[16];
+        snprintf(ciph, sizeof(ciph), "%d", cipher_suite > 0 ? cipher_suite : 17);
+        execlp(
+            "ipmitool", "ipmitool",
+            "-I", "lanplus",
+            "-C", ciph,
+            "-N", "2",
+            "-R", "1",
+            "-H", host,
+            "-U", user,
+            "-E",
+            "shell",
+            (char *)NULL);
+        _exit(127);
+    }
+
+    close(in_pipe[0]);
+    close(out_pipe[1]);
+    (void)stl_set_nonblocking_nodelay(in_pipe[1], 0);
+    (void)stl_set_nonblocking_nodelay(out_pipe[0], 0);
+    *out_stdin_fd  = in_pipe[1];
+    *out_stdout_fd = out_pipe[0];
+    *out_child_pid = (int)pid;
+    return 0;
+}
+
+ssize_t c_pty_read_nonblock(int master_fd, uint8_t *buf, size_t cap) {
+    if (master_fd < 0 || !buf || cap == 0) return -1;
+    ssize_t n = read(master_fd, buf, cap);
+    if (n > 0) return n;
+    if (n == 0) return -2; /* EOF */
+    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
+    return -2; /* EIO / closed */
+}
+
+ssize_t c_pty_write_bytes(int master_fd, const uint8_t *buf, size_t len) {
+    if (master_fd < 0 || !buf || len == 0) return 0;
+    ssize_t n = write(master_fd, buf, len);
+    if (n >= 0) return n;
+    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) return 0;
+    return -1;
+}
+
+int c_pty_is_alive(int child_pid) {
+    if (child_pid <= 0) return 0;
+    int status = 0;
+    pid_t r = waitpid((pid_t)child_pid, &status, WNOHANG);
+    if (r == 0) return 1;
+    return 0;
+}
+
+void c_pty_close(int master_fd, int child_pid) {
+    if (master_fd >= 0) close(master_fd);
+    if (child_pid > 0 && kill((pid_t)child_pid, 0) == 0) {
+        kill((pid_t)child_pid, SIGTERM);
+        int status = 0;
+        for (int i = 0; i < 10; i++) {
+            if (waitpid((pid_t)child_pid, &status, WNOHANG) != 0) return;
+            struct timespec ts = { .tv_sec = 0, .tv_nsec = 5000000L };
+            nanosleep(&ts, NULL);
+        }
+        kill((pid_t)child_pid, SIGKILL);
+        (void)waitpid((pid_t)child_pid, &status, 0);
+    }
+}

+ 464 - 0
native/stl_accel/opencl_batch.c

@@ -0,0 +1,464 @@
+/*
+ * opencl_batch.c — Intel Gen7.5..Gen9.5 OpenCL 1.2 Zero-Copy Shared Memory Batch Offload (v0.8.1.18)
+ *
+ * Strictly OFF the real-time short serial path!
+ * Dynamically loads libOpenCL.so.1 via dlopen; automatically falls back to pure
+ * x86-64 SSE2 CPU kernels on 2nd-Gen Sandy Bridge, missing ICDs, below break-even
+ * threshold S*, or when 15W U-series TDP headroom would throttle CPU clocks.
+ */
+
+#define _GNU_SOURCE
+#include "stl_accel.h"
+
+#include <dlfcn.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+/* Zig pure-SSE2 CPU fallbacks (zig_kernels.zig) */
+extern size_t zig_batch_rescan_logs_cpu(
+    const uint8_t *buf_ptr,
+    size_t         len,
+    uint32_t      *out_offsets,
+    uint8_t       *out_tags,
+    size_t         max_lines);
+
+extern void zig_rmt_eye_reduce_cpu(
+    const float *margins_in,
+    size_t       station_count,
+    float       *eye_grid_out,
+    float       *summary_out);
+
+/* Minimal Khronos OpenCL 1.2 C ABI definitions (no external headers required) */
+typedef int32_t   cl_int;
+typedef uint32_t  cl_uint;
+typedef uint64_t  cl_ulong;
+typedef uint64_t  cl_bitfield;
+typedef cl_uint   cl_bool;
+typedef void     *cl_platform_id;
+typedef void     *cl_device_id;
+typedef void     *cl_context;
+typedef void     *cl_command_queue;
+typedef void     *cl_mem;
+typedef void     *cl_program;
+typedef void     *cl_kernel;
+typedef void     *cl_event;
+
+#define CL_SUCCESS                      0
+#define CL_TRUE                         1u
+#define CL_DEVICE_TYPE_GPU              (1ULL << 2)
+#define CL_DEVICE_NAME                  0x102Bu
+#define CL_DEVICE_MAX_COMPUTE_UNITS     0x1002u
+#define CL_DEVICE_HOST_UNIFIED_MEMORY   0x1035u
+#define CL_MEM_READ_WRITE               (1ULL << 0)
+#define CL_MEM_WRITE_ONLY               (1ULL << 1)
+#define CL_MEM_READ_ONLY                (1ULL << 2)
+#define CL_MEM_USE_HOST_PTR             (1ULL << 3)
+#define CL_MAP_READ                     (1ULL << 0)
+
+typedef cl_int (*fn_clGetPlatformIDs)(cl_uint, cl_platform_id *, cl_uint *);
+typedef cl_int (*fn_clGetDeviceIDs)(cl_platform_id, cl_bitfield, cl_uint, cl_device_id *, cl_uint *);
+typedef cl_int (*fn_clGetDeviceInfo)(cl_device_id, cl_uint, size_t, void *, size_t *);
+typedef cl_context (*fn_clCreateContext)(const intptr_t *, cl_uint, const cl_device_id *, void *, void *, cl_int *);
+typedef cl_command_queue (*fn_clCreateCommandQueue)(cl_context, cl_device_id, cl_bitfield, cl_int *);
+typedef cl_program (*fn_clCreateProgramWithSource)(cl_context, cl_uint, const char **, const size_t *, cl_int *);
+typedef cl_int (*fn_clBuildProgram)(cl_program, cl_uint, const cl_device_id *, const char *, void *, void *);
+typedef cl_kernel (*fn_clCreateKernel)(cl_program, const char *, cl_int *);
+typedef cl_mem (*fn_clCreateBuffer)(cl_context, cl_bitfield, size_t, void *, cl_int *);
+typedef cl_int (*fn_clSetKernelArg)(cl_kernel, cl_uint, size_t, const void *);
+typedef cl_int (*fn_clEnqueueNDRangeKernel)(
+    cl_command_queue, cl_kernel, cl_uint, const size_t *, const size_t *, const size_t *, cl_uint, const cl_event *, cl_event *);
+typedef void *(*fn_clEnqueueMapBuffer)(
+    cl_command_queue, cl_mem, cl_bool, cl_bitfield, size_t, size_t, cl_uint, const cl_event *, cl_event *, cl_int *);
+typedef cl_int (*fn_clEnqueueUnmapMemObject)(
+    cl_command_queue, cl_mem, void *, cl_uint, const cl_event *, cl_event *);
+typedef cl_int (*fn_clFinish)(cl_command_queue);
+typedef cl_int (*fn_clReleaseMemObject)(cl_mem);
+
+static const char *k_opencl_src =
+    "__kernel void rmt_eye_surface(\n"
+    "    __global const float4 *margins,\n"
+    "    __global float *eye_out)\n"
+    "{\n"
+    "    int ch_idx = get_global_id(0);\n"
+    "    int pix    = get_global_id(1);\n"
+    "    int row    = pix >> 4;\n"
+    "    int col    = pix & 15;\n"
+    "    float4 m   = fabs(margins[ch_idx]);\n"
+    "    float ht   = fmax((m.x + m.y) * 0.5f, 0.001f);\n"
+    "    float hv   = fmax((m.z + m.w) * 0.5f, 0.001f);\n"
+    "    float nx   = fabs(((float)col - 7.5f) / 7.5f * 32.0f) / ht;\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"
+    "}\n"
+    "__kernel void batch_line_tags(\n"
+    "    __global const uchar *buf,\n"
+    "    uint len,\n"
+    "    __global uchar *block_flags)\n"
+    "{\n"
+    "    uint blk = get_global_id(0);\n"
+    "    uint base = blk << 8;\n"
+    "    uint lim = base + 256u;\n"
+    "    if (lim > len) lim = len;\n"
+    "    uchar flg = 0u;\n"
+    "    for (uint i = base; i < lim; i++) {\n"
+    "        uchar c = buf[i];\n"
+    "        if (c == 10u || c == 13u) flg |= 8u;\n"
+    "        else if (c == 91u) flg |= 1u;\n"
+    "        else if (c == 62u || c == 35u) flg |= 2u;\n"
+    "        else if (c == 69u || c == 70u || c == 87u || c == 85u) flg |= 4u;\n"
+    "    }\n"
+    "    block_flags[blk] = flg;\n"
+    "}\n";
+
+static pthread_once_t   g_cl_once  = PTHREAD_ONCE_INIT;
+static pthread_mutex_t  g_cl_mutex = PTHREAD_MUTEX_INITIALIZER;
+static StlOpenClInfo    g_cl_info;
+static void            *g_cl_lib   = NULL;
+static cl_context       g_cl_ctx   = 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 fn_clCreateBuffer          p_clCreateBuffer          = NULL;
+static fn_clSetKernelArg          p_clSetKernelArg          = NULL;
+static fn_clEnqueueNDRangeKernel  p_clEnqueueNDRangeKernel  = NULL;
+static fn_clEnqueueMapBuffer      p_clEnqueueMapBuffer      = NULL;
+static fn_clEnqueueUnmapMemObject p_clEnqueueUnmapMemObject = NULL;
+static fn_clFinish                p_clFinish                = NULL;
+static fn_clReleaseMemObject      p_clReleaseMemObject      = NULL;
+
+static void init_opencl_once(void) {
+    memset(&g_cl_info, 0, sizeof(g_cl_info));
+    g_cl_info.break_even_bytes = 262144ULL; /* S* = 256 KiB */
+    snprintf(g_cl_info.device_name, sizeof(g_cl_info.device_name), "cpu-simd-fallback");
+
+    g_cl_lib = dlopen("libOpenCL.so.1", RTLD_LAZY | RTLD_LOCAL);
+    if (!g_cl_lib) return;
+
+    fn_clGetPlatformIDs p_getPlats = (fn_clGetPlatformIDs)dlsym(g_cl_lib, "clGetPlatformIDs");
+    fn_clGetDeviceIDs   p_getDevs  = (fn_clGetDeviceIDs)dlsym(g_cl_lib, "clGetDeviceIDs");
+    fn_clGetDeviceInfo  p_getInfo  = (fn_clGetDeviceInfo)dlsym(g_cl_lib, "clGetDeviceInfo");
+    fn_clCreateContext  p_mkCtx    = (fn_clCreateContext)dlsym(g_cl_lib, "clCreateContext");
+    fn_clCreateCommandQueue p_mkQ  = (fn_clCreateCommandQueue)dlsym(g_cl_lib, "clCreateCommandQueue");
+    fn_clCreateProgramWithSource p_mkProg =
+        (fn_clCreateProgramWithSource)dlsym(g_cl_lib, "clCreateProgramWithSource");
+    fn_clBuildProgram   p_bldProg  = (fn_clBuildProgram)dlsym(g_cl_lib, "clBuildProgram");
+    fn_clCreateKernel   p_mkKern   = (fn_clCreateKernel)dlsym(g_cl_lib, "clCreateKernel");
+    p_clCreateBuffer               = (fn_clCreateBuffer)dlsym(g_cl_lib, "clCreateBuffer");
+    p_clSetKernelArg               = (fn_clSetKernelArg)dlsym(g_cl_lib, "clSetKernelArg");
+    p_clEnqueueNDRangeKernel       = (fn_clEnqueueNDRangeKernel)dlsym(g_cl_lib, "clEnqueueNDRangeKernel");
+    p_clEnqueueMapBuffer           = (fn_clEnqueueMapBuffer)dlsym(g_cl_lib, "clEnqueueMapBuffer");
+    p_clEnqueueUnmapMemObject      = (fn_clEnqueueUnmapMemObject)dlsym(g_cl_lib, "clEnqueueUnmapMemObject");
+    p_clFinish                     = (fn_clFinish)dlsym(g_cl_lib, "clFinish");
+    p_clReleaseMemObject           = (fn_clReleaseMemObject)dlsym(g_cl_lib, "clReleaseMemObject");
+
+    if (!p_getPlats || !p_getDevs || !p_getInfo || !p_mkCtx || !p_mkQ || !p_mkProg ||
+        !p_bldProg || !p_mkKern || !p_clCreateBuffer || !p_clSetKernelArg ||
+        !p_clEnqueueNDRangeKernel || !p_clEnqueueMapBuffer || !p_clEnqueueUnmapMemObject ||
+        !p_clFinish || !p_clReleaseMemObject) {
+        return;
+    }
+
+    cl_platform_id plats[8];
+    cl_uint nplats = 0;
+    if (p_getPlats(8, plats, &nplats) != CL_SUCCESS || nplats == 0) return;
+
+    cl_device_id chosen_dev = NULL;
+    for (cl_uint p = 0; p < nplats && !chosen_dev; p++) {
+        cl_device_id devs[4];
+        cl_uint ndevs = 0;
+        if (p_getDevs(plats[p], CL_DEVICE_TYPE_GPU, 4, devs, &ndevs) == CL_SUCCESS && ndevs > 0) {
+            chosen_dev = devs[0];
+        }
+    }
+    if (!chosen_dev) return;
+
+    char name_buf[96];
+    memset(name_buf, 0, sizeof(name_buf));
+    (void)p_getInfo(chosen_dev, CL_DEVICE_NAME, sizeof(name_buf) - 1, name_buf, NULL);
+    cl_uint cus = 0;
+    (void)p_getInfo(chosen_dev, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cus), &cus, NULL);
+    cl_bool unified = 0;
+    (void)p_getInfo(chosen_dev, CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(unified), &unified, NULL);
+
+    cl_int err = 0;
+    cl_context ctx = p_mkCtx(NULL, 1, &chosen_dev, NULL, NULL, &err);
+    if (!ctx || err != CL_SUCCESS) return;
+    cl_command_queue q = p_mkQ(ctx, chosen_dev, 0, &err);
+    if (!q || err != CL_SUCCESS) return;
+
+    size_t src_len = strlen(k_opencl_src);
+    cl_program prog = p_mkProg(ctx, 1, &k_opencl_src, &src_len, &err);
+    if (!prog || err != CL_SUCCESS) return;
+    if (p_bldProg(prog, 1, &chosen_dev, "-cl-fast-relaxed-math", NULL, NULL) != CL_SUCCESS) return;
+    cl_kernel kern = p_mkKern(prog, "rmt_eye_surface", &err);
+    if (!kern || err != CL_SUCCESS) return;
+    cl_kernel log_kern = p_mkKern(prog, "batch_line_tags", &err);
+
+    g_cl_ctx   = ctx;
+    g_cl_queue = q;
+    g_cl_eye_k = kern;
+    g_cl_log_k = (err == CL_SUCCESS) ? log_kern : NULL;
+    g_cl_info.available     = 1;
+    g_cl_info.zero_copy_llc = (unified == CL_TRUE) ? 1 : 0;
+    g_cl_info.compute_units = cus;
+    snprintf(g_cl_info.device_name, sizeof(g_cl_info.device_name), "%s", name_buf);
+}
+
+static int read_sysfs_u64(const char *path, uint64_t *out) {
+    FILE *f = fopen(path, "r");
+    if (!f) return 0;
+    unsigned long long v = 0;
+    int ok = (fscanf(f, "%llu", &v) == 1);
+    fclose(f);
+    if (ok) *out = (uint64_t)v;
+    return ok;
+}
+
+/*
+ * Guard against 15W U-series package power throttling:
+ * If RAPL PL1 <= 16W and CPU load or frequency droop indicates package TDP pressure,
+ * keep iGPU idle so CPU cores retain full Turbo clock for serial/protocol actors.
+ */
+int stl_opencl_has_tdp_headroom(void) {
+    uint64_t pl1_uw = 0;
+    if (read_sysfs_u64("/sys/class/powercap/intel-rapl:0/constraint_0_power_limit_uw", &pl1_uw)) {
+        if (pl1_uw > 0 && pl1_uw <= 16000000ULL) {
+            /* 15W U-series SKU: check CPU loadavg and current scaling frequency */
+            double load1 = 0.0;
+            if (getloadavg(&load1, 1) == 1) {
+                long ncores = sysconf(_SC_NPROCESSORS_ONLN);
+                if (ncores > 0 && load1 > (double)ncores * 0.55) {
+                    return 0;
+                }
+            }
+        }
+    }
+    uint64_t cur_khz = 0, max_khz = 0;
+    if (read_sysfs_u64("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq", &cur_khz) &&
+        read_sysfs_u64("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq", &max_khz)) {
+        if (max_khz > 0 && cur_khz * 100ULL < max_khz * 50ULL) {
+            /* Only if heavily throttled under active load */
+            double load1 = 0.0;
+            if (getloadavg(&load1, 1) == 1 && load1 > 1.5) return 0;
+        }
+    }
+    return 1;
+}
+
+void stl_opencl_query_info(StlOpenClInfo *out_info) {
+    pthread_once(&g_cl_once, init_opencl_once);
+    if (!out_info) return;
+    *out_info = g_cl_info;
+}
+
+size_t stl_batch_rescan_logs(
+    const uint8_t *buf_4k_aligned,
+    size_t         len,
+    uint32_t      *out_line_offsets,
+    uint8_t       *out_line_tags,
+    size_t         max_lines,
+    int           *used_gpu) {
+    pthread_once(&g_cl_once, init_opencl_once);
+    if (used_gpu) *used_gpu = 0;
+    if (!buf_4k_aligned || len == 0 || !out_line_offsets || !out_line_tags || max_lines == 0) {
+        return 0;
+    }
+    /* Break-even & 15W TDP headroom gate: short logs or missing iGPU stay on pure SSE2 CPU */
+    if (!g_cl_info.available || !g_cl_log_k || len < (size_t)g_cl_info.break_even_bytes ||
+        ((uintptr_t)buf_4k_aligned & 4095u) != 0 || !stl_opencl_has_tdp_headroom()) {
+        return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
+    }
+
+    size_t n_blocks = (len + 255u) >> 8;
+    size_t in_bytes = (len + 4095u) & ~4095u;
+    size_t flg_bytes = (n_blocks + 4095u) & ~4095u;
+    void *flg_4k = NULL;
+    if (posix_memalign(&flg_4k, 4096, flg_bytes) != 0) {
+        return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
+    }
+
+    int gpu_ok = 0;
+    pthread_mutex_lock(&g_cl_mutex);
+    cl_int e1 = 0, e2 = 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_flg = p_clCreateBuffer(
+        g_cl_ctx, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, flg_bytes, flg_4k, &e2);
+    cl_uint u_len = (cl_uint)(len > 0xFFFFFFFFu ? 0xFFFFFFFFu : len);
+    if (m_in && m_flg && e1 == CL_SUCCESS && e2 == 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_flg) == CL_SUCCESS) {
+            size_t gws[1] = { n_blocks };
+            if (p_clEnqueueNDRangeKernel(g_cl_queue, g_cl_log_k, 1, NULL, gws, NULL, 0, NULL, NULL) == CL_SUCCESS) {
+                cl_int map_err = 0;
+                uint8_t *mapped = (uint8_t *)p_clEnqueueMapBuffer(
+                    g_cl_queue, m_flg, CL_TRUE, CL_MAP_READ, 0, n_blocks, 0, NULL, NULL, &map_err);
+                if (mapped && map_err == CL_SUCCESS) {
+                    gpu_ok = 1;
+                    (void)p_clEnqueueUnmapMemObject(g_cl_queue, m_flg, mapped, 0, NULL, NULL);
+                    (void)p_clFinish(g_cl_queue);
+                }
+            }
+        }
+    }
+    if (m_in)  (void)p_clReleaseMemObject(m_in);
+    if (m_flg) (void)p_clReleaseMemObject(m_flg);
+    pthread_mutex_unlock(&g_cl_mutex);
+
+    if (!gpu_ok) {
+        free(flg_4k);
+        return zig_batch_rescan_logs_cpu(buf_4k_aligned, len, out_line_offsets, out_line_tags, max_lines);
+    }
+
+    /* Prefix-compact 256B block flags from zero-copy iGPU pass into exact line offsets & tags */
+    const uint8_t *bflags = (const uint8_t *)flg_4k;
+    size_t line_count = 0, line_start = 0;
+    uint8_t cur_tag = 0;
+    int prev_cr = 0;
+    for (size_t blk = 0; blk < n_blocks && line_count < max_lines; blk++) {
+        uint8_t bf = bflags[blk];
+        size_t base = blk << 8;
+        size_t lim = base + 256u;
+        if (lim > len) lim = len;
+        if ((bf & 8u) == 0 && !prev_cr) {
+            cur_tag |= (bf & 7u);
+            continue;
+        }
+        for (size_t i = base; i < lim && line_count < max_lines; i++) {
+            uint8_t c = buf_4k_aligned[i];
+            if (c == '\n') {
+                if (prev_cr) { prev_cr = 0; line_start = i + 1; continue; }
+                if (i > line_start) {
+                    out_line_offsets[line_count] = (uint32_t)line_start;
+                    out_line_tags[line_count] = cur_tag;
+                    line_count++;
+                }
+                cur_tag = 0;
+                line_start = i + 1;
+            } else if (c == '\r') {
+                if (i > line_start) {
+                    out_line_offsets[line_count] = (uint32_t)line_start;
+                    out_line_tags[line_count] = cur_tag;
+                    line_count++;
+                }
+                cur_tag = 0;
+                prev_cr = 1;
+                line_start = i + 1;
+            } else {
+                prev_cr = 0;
+                if (c == '[') cur_tag |= 1u;
+                else if (c == '>' || c == '#') cur_tag |= 2u;
+                else if (c == 'E' || c == 'F' || c == 'W' || c == 'U') cur_tag |= 4u;
+            }
+        }
+    }
+    if (line_start < len && line_count < max_lines) {
+        out_line_offsets[line_count] = (uint32_t)line_start;
+        out_line_tags[line_count] = cur_tag;
+        line_count++;
+    }
+    free(flg_4k);
+    if (used_gpu) *used_gpu = 1;
+    return line_count;
+}
+
+int stl_batch_rmt_eye_reduce(
+    const float *margins_in,
+    size_t       station_count,
+    float       *eye_grid_out,
+    float       *summary_out,
+    int         *used_gpu) {
+    pthread_once(&g_cl_once, init_opencl_once);
+    if (used_gpu) *used_gpu = 0;
+    if (!margins_in || station_count == 0 || !eye_grid_out || !summary_out) return -1;
+
+    /* Break-even gate: require >= 4 stations AND available zero-copy iGPU AND 15W TDP headroom */
+    if (!g_cl_info.available || station_count < 4 || !stl_opencl_has_tdp_headroom()) {
+        zig_rmt_eye_reduce_cpu(margins_in, station_count, eye_grid_out, summary_out);
+        return 0;
+    }
+
+    size_t total_ch = station_count * 24;
+    size_t in_bytes  = ((total_ch * 4 * sizeof(float)) + 4095u) & ~4095u;
+    size_t out_bytes = ((total_ch * 256 * sizeof(float)) + 4095u) & ~4095u;
+
+    void *in_4k  = NULL;
+    void *out_4k = NULL;
+    if (posix_memalign(&in_4k, 4096, in_bytes) != 0 ||
+        posix_memalign(&out_4k, 4096, out_bytes) != 0) {
+        free(in_4k);
+        free(out_4k);
+        zig_rmt_eye_reduce_cpu(margins_in, station_count, eye_grid_out, summary_out);
+        return 0;
+    }
+    memcpy(in_4k, margins_in, total_ch * 4 * sizeof(float));
+
+    int gpu_ok = 0;
+    pthread_mutex_lock(&g_cl_mutex);
+    cl_int e1 = 0, e2 = 0;
+    cl_mem m_in  = p_clCreateBuffer(g_cl_ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, in_bytes, in_4k, &e1);
+    cl_mem m_out = p_clCreateBuffer(g_cl_ctx, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, out_bytes, out_4k, &e2);
+    if (m_in && m_out && e1 == CL_SUCCESS && e2 == CL_SUCCESS) {
+        if (p_clSetKernelArg(g_cl_eye_k, 0, sizeof(cl_mem), &m_in) == CL_SUCCESS &&
+            p_clSetKernelArg(g_cl_eye_k, 1, sizeof(cl_mem), &m_out) == CL_SUCCESS) {
+            size_t gws[2] = { total_ch, 256 };
+            if (p_clEnqueueNDRangeKernel(g_cl_queue, g_cl_eye_k, 2, NULL, gws, NULL, 0, NULL, NULL) == CL_SUCCESS) {
+                cl_int map_err = 0;
+                void *mapped = p_clEnqueueMapBuffer(
+                    g_cl_queue, m_out, CL_TRUE, CL_MAP_READ, 0, total_ch * 256 * sizeof(float),
+                    0, NULL, NULL, &map_err);
+                if (mapped && map_err == CL_SUCCESS) {
+                    memcpy(eye_grid_out, mapped, total_ch * 256 * sizeof(float));
+                    (void)p_clEnqueueUnmapMemObject(g_cl_queue, m_out, mapped, 0, NULL, NULL);
+                    (void)p_clFinish(g_cl_queue);
+                    gpu_ok = 1;
+                }
+            }
+        }
+    }
+    if (m_in)  (void)p_clReleaseMemObject(m_in);
+    if (m_out) (void)p_clReleaseMemObject(m_out);
+    pthread_mutex_unlock(&g_cl_mutex);
+
+    free(in_4k);
+    free(out_4k);
+
+    if (!gpu_ok) {
+        zig_rmt_eye_reduce_cpu(margins_in, station_count, eye_grid_out, summary_out);
+        return 0;
+    }
+
+    /* Compute compact per-station scalar min/mean summary on CPU (96 floats) */
+    for (size_t st = 0; st < station_count; st++) {
+        float min_t = 999.0f, min_v = 999.0f, sum_t = 0.0f, sum_v = 0.0f, cnt = 0.0f;
+        for (size_t ch = 0; ch < 24; ch++) {
+            const float *m = &margins_in[(st * 24 + ch) * 4];
+            float rx_lo = m[0] < 0 ? -m[0] : m[0];
+            float rx_hi = m[1] < 0 ? -m[1] : m[1];
+            float tx_lo = m[2] < 0 ? -m[2] : m[2];
+            float tx_hi = m[3] < 0 ? -m[3] : m[3];
+            float ts = rx_lo + rx_hi;
+            float vs = tx_lo + tx_hi;
+            if (ts > 0.0f || vs > 0.0f) {
+                if (ts < min_t) min_t = ts;
+                if (vs < min_v) min_v = vs;
+                sum_t += ts;
+                sum_v += vs;
+                cnt += 1.0f;
+            }
+        }
+        summary_out[st * 4 + 0] = cnt > 0.0f ? min_t : 0.0f;
+        summary_out[st * 4 + 1] = cnt > 0.0f ? min_v : 0.0f;
+        summary_out[st * 4 + 2] = cnt > 0.0f ? (sum_t / cnt) : 0.0f;
+        summary_out[st * 4 + 3] = cnt > 0.0f ? (sum_v / cnt) : 0.0f;
+    }
+    if (used_gpu) *used_gpu = 1;
+    return 0;
+}
+

+ 929 - 0
native/stl_accel/parser_re2c.re

@@ -0,0 +1,929 @@
+/*
+ * XJKJ-STL Deterministic re2c Line Lexer & Coordinate Extractor (v0.8.1.18)
+ *
+ * Compiled via: re2c -W --no-generation-date -o parser_re2c.c parser_re2c.re
+ * Pure C11 / x86-64 SSE2 baseline; zero heap allocations; replaces per-line
+ * repeated .contains() scans with a deterministic finite automaton (DFA).
+ *
+ * Verified 1:1 against both real server firmwares:
+ *   - .166: 107_VD012 / [Hovsee] / [HS_*] / [0][AMT #] GNR-4.3.3 (24 algos)
+ *   - .165: [CxmtDdrTest] / [HD_*] / [0][AMEMDIAG #] GNR-4.3.0 (19 algos)
+ *   - 118.efi / PassMark MemTest86 Site / UEFI Shell / PXE
+ */
+
+#include "stl_accel.h"
+#include <string.h>
+
+static inline uint8_t ascii_lower(uint8_t c) {
+    return (c >= 'A' && c <= 'Z') ? (uint8_t)(c + 32) : c;
+}
+
+static int parse_i32_at(const uint8_t *p, const uint8_t *end, int32_t *out, const uint8_t **after) {
+    while (p < end && (*p == ' ' || *p == '\t' || *p == ':' || *p == '=' || *p == '#')) {
+        p++;
+    }
+    if (p >= end) return 0;
+    int neg = 0;
+    if (*p == '-') { neg = 1; p++; }
+    else if (*p == '+') { p++; }
+    if (p >= end || *p < '0' || *p > '9') return 0;
+    int64_t v = 0;
+    while (p < end && *p >= '0' && *p <= '9') {
+        v = v * 10 + (*p - '0');
+        if (v > 0x7fffffffLL) v = 0x7fffffffLL;
+        p++;
+    }
+    *out = neg ? (int32_t)(-v) : (int32_t)v;
+    if (after) *after = p;
+    return 1;
+}
+
+static int parse_hex64_at(const uint8_t *p, const uint8_t *end, uint64_t *out) {
+    while (p < end && (*p == ' ' || *p == '\t' || *p == ':' || *p == '=')) p++;
+    if (p + 2 <= end && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) p += 2;
+    if (p >= end) return 0;
+    uint64_t v = 0;
+    int digits = 0;
+    while (p < end) {
+        uint8_t c = *p;
+        uint8_t d;
+        if (c >= '0' && c <= '9') d = (uint8_t)(c - '0');
+        else if (c >= 'a' && c <= 'f') d = (uint8_t)(c - 'a' + 10);
+        else if (c >= 'A' && c <= 'F') d = (uint8_t)(c - 'A' + 10);
+        else break;
+        v = (v << 4) | d;
+        digits++;
+        p++;
+    }
+    if (digits == 0) return 0;
+    *out = v;
+    return 1;
+}
+
+/* Extract leading [<cpu>] prefix common on Hovsee/CxmtDdrTest/AMT lines */
+static void extract_leading_bracket_cpu(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
+    const uint8_t *p = s;
+    while (p < end && (*p == '.' || *p == ' ' || *p == '\t')) p++;
+    if (p + 3 <= end && p[0] == '[' && (p[1] == '0' || p[1] == '1') && p[2] == ']') {
+        ev->cpu = (int8_t)(p[1] - '0');
+    }
+}
+
+/* Extract N<cpu>.C<ch>[.D<dimm>][.SC<sub>][.R<rank>] topology token & RMT margins */
+static int extract_ncd_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
+    for (const uint8_t *p = s; p + 5 <= end; p++) {
+        if ((p[0] == 'N' || p[0] == 'n') &&
+            (p[1] >= '0' && p[1] <= '3') && p[2] == '.' &&
+            (p[3] == 'C' || p[3] == 'c') && (p[4] >= '0' && p[4] <= '9')) {
+            int cpu = p[1] - '0';
+            const uint8_t *q = p + 4;
+            int ch = 0;
+            while (q < end && *q >= '0' && *q <= '9') {
+                ch = ch * 10 + (*q - '0');
+                q++;
+            }
+            if (cpu >= 0 && cpu <= 1 && ch >= 0 && ch <= 11) {
+                ev->cpu = (int8_t)cpu;
+                ev->channel = (int8_t)ch;
+                while (q + 2 <= end && *q == '.') {
+                    if (q + 3 <= end && (q[1] == 'D' || q[1] == 'd') && q[2] >= '0' && q[2] <= '1') {
+                        ev->dimm = (int8_t)(q[2] - '0');
+                        q += 3;
+                    } else if (q + 4 <= end && (q[1] == 'S' || q[1] == 's') &&
+                               (q[2] == 'C' || q[2] == 'c') && q[3] >= '0' && q[3] <= '1') {
+                        q += 4;
+                    } else if (q + 3 <= end && (q[1] == 'R' || q[1] == 'r') && q[2] >= '0' && q[2] <= '9') {
+                        ev->rank = (int8_t)((q[2] - '0') & 3);
+                        q += 3;
+                        while (q < end && *q >= '0' && *q <= '9') q++;
+                    } else if (q + 3 <= end && (q[1] == 'L' || q[1] == 'l') && q[2] >= '0' && q[2] <= '9') {
+                        q += 3;
+                        while (q < end && *q >= '0' && *q <= '9') q++;
+                    } else {
+                        break;
+                    }
+                }
+                if (q < end && *q == ':') {
+                    q++;
+                    int32_t vals[4] = {0, 0, 0, 0};
+                    int got = 0;
+                    const uint8_t *nx = q;
+                    while (nx < end && got < 4) {
+                        while (nx < end && (*nx == ' ' || *nx == '\t')) nx++;
+                        if (nx < end && *nx == '*') {
+                            vals[got++] = 0;
+                            nx++;
+                        } else {
+                            int32_t mv = 0;
+                            if (parse_i32_at(nx, end, &mv, &nx)) {
+                                vals[got++] = mv;
+                            } else {
+                                break;
+                            }
+                        }
+                    }
+                    if (got >= 4) {
+                        ev->val0 = vals[0];
+                        ev->val1 = vals[1];
+                        ev->val2 = vals[2];
+                        ev->val3 = vals[3];
+                    }
+                }
+                return 1;
+            }
+        }
+    }
+    return 0;
+}
+
+static int match_ci_kw(const uint8_t *p, const uint8_t *end, const char *kw, const uint8_t **after) {
+    size_t klen = strlen(kw);
+    if ((size_t)(end - p) < klen) return 0;
+    for (size_t i = 0; i < klen; i++) {
+        if (ascii_lower(p[i]) != (uint8_t)kw[i]) return 0;
+    }
+    const uint8_t *q = p + klen;
+    if (q < end && ((*q >= 'a' && *q <= 'z') || (*q >= 'A' && *q <= 'Z') || *q == '_')) return 0;
+    *after = q;
+    return 1;
+}
+
+/*
+ * Extract physical topology coordinates from BIOS/Training/AMT/MemTest86 lines.
+ * Strictly enforces 0 <= bank < 32 (never trusts broken historical >= 32 bank analyses).
+ */
+static void extract_coords_and_addr(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
+    extract_leading_bracket_cpu(s, end, ev);
+    extract_ncd_token(s, end, ev);
+
+    /* Check MemTest86 "(P0,C3,S0,R0)" or "Channel/Slot: N0-3-0" or "(Chan,Slot,Rank,Bank,Row,Col): (3,0,0,12,...)" */
+    for (const uint8_t *p = s; p + 6 <= end; p++) {
+        if ((p[0] == 'N' || p[0] == 'n') && (p[1] == '0' || p[1] == '1') &&
+            p[2] == '-' && p[3] >= '0' && p[3] <= '9') {
+            int32_t ch = -1, sl = -1;
+            const uint8_t *nx = p + 3;
+            if (parse_i32_at(nx, end, &ch, &nx) && ch >= 0 && ch <= 11) {
+                ev->cpu = (int8_t)(p[1] - '0');
+                ev->channel = (int8_t)ch;
+                if (nx < end && *nx == '-') {
+                    if (parse_i32_at(nx + 1, end, &sl, &nx) && sl >= 0 && sl <= 1) {
+                        ev->dimm = (int8_t)sl;
+                    }
+                }
+            }
+        }
+        if (p + 8 > end) continue;
+        if (p[0] == '(' && (p[1] == 'P' || p[1] == 'p') && (p[2] == '0' || p[2] == '1') &&
+            p[3] == ',' && (p[4] == 'C' || p[4] == 'c')) {
+            int32_t ch = -1, sl = -1;
+            const uint8_t *nx = p + 5;
+            if (parse_i32_at(nx, end, &ch, &nx) && ch >= 0 && ch <= 11) {
+                ev->cpu = (int8_t)(p[2] - '0');
+                ev->channel = (int8_t)ch;
+                if (nx + 2 < end && nx[0] == ',' && (nx[1] == 'S' || nx[1] == 's')) {
+                    if (parse_i32_at(nx + 2, end, &sl, &nx) && sl >= 0 && sl <= 1) {
+                        ev->dimm = (int8_t)sl;
+                    }
+                }
+            }
+        }
+        if (p + 25 <= end && memcmp(p, "(Chan,Slot,Rank,Bank,Row,", 25) == 0) {
+            const uint8_t *lp = memchr(p + 25, '(', (size_t)(end - (p + 25)));
+            if (lp) {
+                int32_t c_ch = -1, c_sl = -1, c_rk = -1, c_bk = -1;
+                const uint8_t *nx = lp + 1;
+                if (parse_i32_at(nx, end, &c_ch, &nx) && nx < end && *nx == ',' &&
+                    parse_i32_at(nx + 1, end, &c_sl, &nx) && nx < end && *nx == ',' &&
+                    parse_i32_at(nx + 1, end, &c_rk, &nx) && nx < end && *nx == ',' &&
+                    parse_i32_at(nx + 1, end, &c_bk, &nx)) {
+                    if (c_ch >= 0 && c_ch <= 11) ev->channel = (int8_t)c_ch;
+                    if (c_sl >= 0 && c_sl <= 1) ev->dimm = (int8_t)c_sl;
+                    if (c_rk >= 0 && c_rk <= 3) ev->rank = (int8_t)c_rk;
+                    if (c_bk >= 0 && c_bk < 32) ev->bank = (int8_t)c_bk;
+                    ev->subkind = 5; /* 2nd-line MT ECC coordinate continuation */
+                }
+            }
+        }
+    }
+
+    int bg = -1;
+    int ba = -1;
+    int direct_bank = -1;
+
+    for (const uint8_t *p = s; p < end; p++) {
+        if (p > s) {
+            uint8_t prev = p[-1];
+            if ((prev >= 'a' && prev <= 'z') || (prev >= 'A' && prev <= 'Z') ||
+                (prev >= '0' && prev <= '9') || prev == '_') {
+                continue;
+            }
+        }
+        const uint8_t *after = NULL;
+        int32_t v = 0;
+        if (match_ci_kw(p, end, "socket", &after) || match_ci_kw(p, end, "scktid", &after) ||
+            match_ci_kw(p, end, "node", &after) || match_ci_kw(p, end, "cpu", &after)) {
+            if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 1 && ev->cpu < 0) {
+                ev->cpu = (int8_t)v;
+            }
+        } else if (match_ci_kw(p, end, "channel", &after) || match_ci_kw(p, end, "ch", &after) ||
+                   match_ci_kw(p, end, "chan", &after)) {
+            if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 23) {
+                if (v >= 12 && ev->cpu < 0) {
+                    ev->cpu = 1;
+                    ev->channel = (int8_t)(v - 12);
+                } else if (v <= 11) {
+                    ev->channel = (int8_t)v;
+                }
+            }
+        } else if (match_ci_kw(p, end, "dimm", &after) || match_ci_kw(p, end, "slot", &after)) {
+            if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 23) {
+                if (v <= 1) {
+                    ev->dimm = (int8_t)v;
+                } else if (ev->channel < 0) {
+                    ev->cpu = (int8_t)(v / 12);
+                    ev->channel = (int8_t)(v % 12);
+                    ev->dimm = 0;
+                }
+            }
+        } else if (match_ci_kw(p, end, "rank", &after)) {
+            if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 3) {
+                ev->rank = (int8_t)v;
+            }
+        } else if (match_ci_kw(p, end, "bankgroup", &after) || match_ci_kw(p, end, "bg", &after)) {
+            if (parse_i32_at(after, end, &v, NULL) && v >= 0 && v <= 7) {
+                bg = (int)v;
+            }
+        } else if (match_ci_kw(p, end, "bank", &after) || match_ci_kw(p, end, "ba", &after)) {
+            if (parse_i32_at(after, end, &v, NULL)) {
+                if (ascii_lower(p[1]) == 'a' && v >= 0 && v <= 3) {
+                    ba = (int)v;
+                } else if (v >= 0 && v < 32) {
+                    direct_bank = (int)v;
+                }
+            }
+        } else if (match_ci_kw(p, end, "addr", &after) || match_ci_kw(p, end, "address", &after) ||
+                   match_ci_kw(p, end, "checkpoint", &after)) {
+            uint64_t a = 0;
+            if (parse_hex64_at(after, end, &a)) {
+                ev->addr = a;
+            }
+        }
+    }
+
+    if (bg >= 0 && ba >= 0) {
+        int combined = bg * 4 + ba;
+        if (combined >= 0 && combined < 32) ev->bank = (int8_t)combined;
+    } else if (direct_bank >= 0 && direct_bank < 32 && ev->bank < 0) {
+        ev->bank = (int8_t)direct_bank;
+    }
+}
+
+static void trim_ws(const uint8_t **ps, const uint8_t **pe) {
+    const uint8_t *s = *ps;
+    const uint8_t *e = *pe;
+    while (s < e && (*s == ' ' || *s == '\t')) s++;
+    while (e > s && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r' || e[-1] == '\n')) e--;
+    *ps = s;
+    *pe = e;
+}
+
+/*!re2c
+    re2c:define:YYCTYPE  = uint8_t;
+    re2c:yyfill:enable   = 0;
+    re2c:flags:tags      = 0;
+    re2c:flags:case-insensitive = 0;
+
+    WS   = [ \t]*;
+    ANY  = [\x00-\xff];
+    DIG  = [0-9]+;
+*/
+
+static uint32_t re2c_scan_token(const uint8_t *s, const uint8_t *end, StlRe2cEvent *ev) {
+    uint8_t buf[520];
+    size_t n = (size_t)(end - s);
+    if (n > 512) n = 512;
+    memcpy(buf, s, n);
+    buf[n] = 0;
+
+    extract_leading_bracket_cpu(buf, buf + n, ev);
+
+    const uint8_t *YYCURSOR = buf;
+    const uint8_t *YYMARKER = buf;
+    const uint8_t *lim = buf + n;
+
+    /* Step 1: Anchored prompt & full-line patterns */
+    /*!re2c
+        WS "UIP>" WS "\x00" {
+            return STL_LK_ICT_PROMPT;
+        }
+        WS "[" [01] "][" ("Hovsee" | "CxmtDdrTest") "]Please input your command" ":"? WS "\x00" {
+            ev->cpu = (int8_t)(buf[1] == '1' ? 1 : 0);
+            for (size_t i = 0; i + 6 <= n; i++) {
+                if (memcmp(buf + i, "Hovsee", 6) == 0) { ev->fw_family = 1; break; }
+                if (i + 11 <= n && memcmp(buf + i, "CxmtDdrTest", 11) == 0) { ev->fw_family = 2; break; }
+            }
+            return STL_LK_ICT_PROMPT;
+        }
+        WS (("[" [01] "]" WS) | ("CPU" [01] WS ":"? WS))? "[" ("CPU" [01] WS)? ("AMT" | "AMEMDIAG") WS "#" WS "]" WS "\x00" {
+            for (size_t i = 0; i + 3 <= n; i++) {
+                if (buf[i] == '[' && (buf[i+1] == '0' || buf[i+1] == '1') && buf[i+2] == ']') {
+                    ev->cpu = (int8_t)(buf[i+1] - '0');
+                }
+                if (i + 4 <= n && buf[i] == 'C' && buf[i+1] == 'P' && buf[i+2] == 'U' && (buf[i+3] == '0' || buf[i+3] == '1')) {
+                    ev->cpu = (int8_t)(buf[i+3] - '0');
+                }
+                if (i + 8 <= n && memcmp(buf + i, "AMEMDIAG", 8) == 0) ev->fw_family = 2;
+                else if (memcmp(buf + i, "AMT", 3) == 0 && ev->fw_family == 0) ev->fw_family = 1;
+            }
+            return STL_LK_AMT_PROMPT;
+        }
+        WS "FS" [0-9] ":\\" ("EFI" | "efi") ("\\" [^\x00\r\n<>]*)? ">" WS "\x00" |
+        WS "FS" [0-9] ":\\" ("EFI" | "efi") ">" WS "\x00" {
+            for (size_t i = 0; i + 2 < n; i++) {
+                if (buf[i] == 'F' && buf[i+1] == 'S' && buf[i+2] >= '0' && buf[i+2] <= '9') {
+                    ev->fs_index = (uint8_t)(buf[i+2] - '0');
+                    break;
+                }
+            }
+            return STL_LK_UEFI_PROMPT_EFI;
+        }
+        WS "FS" [0-9] ":" "\\"? ">" WS "\x00" {
+            for (size_t i = 0; i + 2 < n; i++) {
+                if (buf[i] == 'F' && buf[i+1] == 'S' && buf[i+2] >= '0' && buf[i+2] <= '9') {
+                    ev->fs_index = (uint8_t)(buf[i+2] - '0');
+                    break;
+                }
+            }
+            return STL_LK_UEFI_PROMPT_ROOT;
+        }
+        WS "Shell>" WS "\x00" {
+            ev->fs_index = 255;
+            return STL_LK_UEFI_PROMPT_ROOT;
+        }
+        * { goto scan_anywhere; }
+    */
+
+scan_anywhere:
+    YYCURSOR = buf;
+    while (YYCURSOR < lim) {
+        const uint8_t *tok = YYCURSOR;
+        /*!re2c
+            "[SYS_BIOS]Version:" {
+                return STL_LK_BIOS_BOOT;
+            }
+            "Welcome to Hovsee" | "Hovsee inc. IMC Config Tool" {
+                ev->fw_family = 1;
+                return STL_LK_ICT_BANNER_HOVSEE;
+            }
+            "Welcome to CxmtDdrTest" | "CxmtDdrTest IMC Config Tool" {
+                ev->fw_family = 2;
+                return STL_LK_ICT_BANNER_CXMT;
+            }
+            "[" ("Hovsee" | "CxmtDdrTest") "]Current stage is" WS "1" {
+                ev->fw_family = (tok[1] == 'H') ? 1 : 2;
+                return STL_LK_ICT_START_STAGE1;
+            }
+            "[" ("Hovsee" | "CxmtDdrTest") "]Current stage is" WS "2" {
+                ev->fw_family = (tok[1] == 'H') ? 1 : 2;
+                return STL_LK_ICT_START_STAGE2;
+            }
+            "[Hovsee]Stage2 UIP" {
+                ev->fw_family = 1;
+                return STL_LK_ICT_START_STAGE2;
+            }
+            "[CxmtDdrTest]Stage2 UIP" {
+                ev->fw_family = 2;
+                return STL_LK_ICT_START_STAGE2;
+            }
+            "[Hovsee]Start UIP" {
+                ev->fw_family = 1;
+                return STL_LK_ICT_START_STAGE1;
+            }
+            "[CxmtDdrTest]Start UIP" {
+                ev->fw_family = 2;
+                return STL_LK_ICT_START_STAGE1;
+            }
+            "Please press ENTER to start UIP" {
+                return STL_LK_ICT_ENTER_HINT;
+            }
+            "[" ("Hovsee" | "CxmtDdrTest") "]Please input your command" {
+                ev->fw_family = (tok[1] == 'H') ? 1 : 2;
+                /* Only prompt if no trailing user command echo on same line */
+                const uint8_t *colon = memchr(YYCURSOR, ':', (size_t)(lim - YYCURSOR));
+                if (!colon || colon + 1 >= lim) return STL_LK_ICT_PROMPT;
+                continue;
+            }
+            "[Hovsee]Exit UIP" | "[CxmtDdrTest]Exit UIP" |
+            "[Hovsee]Exit Hovsee UIP" | "[CxmtDdrTest]Exit CxmtDdrTest UIP" |
+            "[Hovsee]Exit ICT ddr test" | "[CxmtDdrTest]Exit ICT ddr test" |
+            "No command input or timeout, so go on training" |
+            "User input command is exit" {
+                if (tok[0] == '[' && tok[1] == 'H') ev->fw_family = 1;
+                if (tok[0] == '[' && tok[1] == 'C') ev->fw_family = 2;
+                return STL_LK_ICT_EXIT;
+            }
+            "is not recognized as an internal or external command" {
+                ev->subkind = 3; /* UEFI shell missing binary error */
+                return STL_LK_MT_FAIL_COMPLETE;
+            }
+            "AdvancedMemTestWorker" | "GNR AP Gpio" | "SetVMGpioMemTest" | "DdrMemTest()" {
+                for (const uint8_t *p = buf; p + 6 <= lim; p++) {
+                    if (memcmp(p, "Hovsee", 6) == 0) { ev->fw_family = 1; break; }
+                    if (p + 11 <= lim && memcmp(p, "CxmtDdrTest", 11) == 0) { ev->fw_family = 2; break; }
+                }
+                return STL_LK_NONE;
+            }
+            "[HS_MRC]" | "[HD_MRC]" |
+            "[HS_StartMemTrain]" | "[HD_StartMemTrain]" |
+            "[Hovsee]Socket " [01] " RcdQcaTraining" {
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'S') ev->fw_family = 1;
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') ev->fw_family = 2;
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'o') ev->fw_family = 1;
+                return STL_LK_MRC_START;
+            }
+            "STOP_MRC_RUN" | "MRC Done" | "Memory Training Complete" |
+            "[HS_EndMemTrain]" | "[HD_EndMemTrain]" {
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'S') ev->fw_family = 1;
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') ev->fw_family = 2;
+                return STL_LK_MRC_DONE;
+            }
+            "0x4F : DXE IPL Start" | "0x60 : DXE Core Started" |
+            "0x90 : BDS Started" | "0x91 : Connecting Drivers" {
+                ev->subkind = 4; /* POST / DXE milestone */
+                return STL_LK_MRC_DONE;
+            }
+            ("AMT" | "AMEMDIAG") WS "Test Start" {
+                ev->fw_family = (tok[0] == 'A' && tok[1] == 'M' && tok[2] == 'E') ? 2 : 1;
+                ev->subkind = 3; /* AMT start */
+                return STL_LK_AMT_PROGRESS;
+            }
+            "[BIOS][Training][ScktId:" WS [01] "]" {
+                extract_coords_and_addr(s, end, ev);
+                /* Check if Rank Margin Tool or MemTest or FAILED */
+                for (const uint8_t *p = YYCURSOR; p + 6 <= lim; p++) {
+                    if (p + 16 <= lim && memcmp(p, "Rank Margin Tool", 16) == 0) {
+                        return STL_LK_RMT_STOP;
+                    }
+                    if (memcmp(p, "FAILED", 6) == 0) {
+                        ev->subkind = 2;
+                        return STL_LK_TRAINING_ERROR;
+                    }
+                }
+                return STL_LK_MRC_START;
+            }
+            "START_RMT_N" [01] {
+                ev->cpu = (int8_t)(tok[11] - '0');
+                return STL_LK_RMT_START;
+            }
+            "START_RMT" | "Starting RMT test v" | "Rank Margin Tool -- Started" |
+            "[HS_StartRmt]" | "[HD_StartRmt]" {
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'S') ev->fw_family = 1;
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') ev->fw_family = 2;
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_RMT_START;
+            }
+            "STOP_RMT_N" [01] {
+                ev->cpu = (int8_t)(tok[10] - '0');
+                return STL_LK_RMT_STOP;
+            }
+            "STOP_RMT" | "[HS_StopRmt]" | "[HD_StopRmt]" | "RMT test v" {
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'S') {
+                    ev->fw_family = 1;
+                    return STL_LK_RMT_STOP;
+                }
+                if (tok[0] == '[' && tok[1] == 'H' && tok[2] == 'D') {
+                    ev->fw_family = 2;
+                    return STL_LK_RMT_STOP;
+                }
+                for (const uint8_t *p = tok; p + 8 <= lim; p++) {
+                    if (memcmp(p, "complete", 8) == 0) {
+                        return STL_LK_RMT_STOP;
+                    }
+                }
+                if (tok[0] == 'S') return STL_LK_RMT_STOP;
+                continue;
+            }
+            "[" ("HS" | "HD") "_" ("RMTSensor" | "Sensor") "]" {
+                ev->fw_family = (tok[2] == 'S') ? 1 : 2;
+                extract_ncd_token(s, end, ev);
+                const uint8_t *cl = memchr(YYCURSOR, ':', (size_t)(lim - YYCURSOR));
+                if (cl) {
+                    int32_t deg = 0;
+                    const uint8_t *nx = NULL;
+                    if (parse_i32_at(cl + 1, lim, &deg, &nx)) {
+                        int32_t tenths = 0;
+                        if (nx && nx + 1 < lim && *nx == '.' && nx[1] >= '0' && nx[1] <= '9') {
+                            tenths = nx[1] - '0';
+                        }
+                        ev->val3 = deg * 10 + (deg >= 0 ? tenths : -tenths);
+                    }
+                }
+                return STL_LK_INLINE_TEMP;
+            }
+            "[" ("HS" | "HD") "_DRAM]" {
+                ev->fw_family = (tok[2] == 'S') ? 1 : 2;
+                extract_coords_and_addr(s, end, ev);
+                /* Check Size:0 -> absent, else present */
+                ev->subkind = 4;
+                for (const uint8_t *p = YYCURSOR; p + 5 <= lim; p++) {
+                    if (memcmp(p, "Size:", 5) == 0) {
+                        int32_t sz = 0;
+                        if (parse_i32_at(p + 5, lim, &sz, NULL)) {
+                            ev->subkind = (sz > 0) ? 4 : 0;
+                            ev->val0 = sz;
+                        }
+                        break;
+                    }
+                }
+                return STL_LK_DIMM_INVENTORY;
+            }
+            "[" ("HS" | "HD") "_DisableDimm]" | "DisableDIMM()" | "MapOutDimm()" | "Mapping out DDR" {
+                extract_coords_and_addr(s, end, ev);
+                ev->subkind = 3; /* disabled */
+                return STL_LK_DIMM_INVENTORY;
+            }
+            "AMT Version " | "Welcome to Advanced Memory Test" | "GNR-4.3.3" {
+                ev->fw_family = 1;
+                return STL_LK_AMT_BANNER;
+            }
+            "AMEMDIAG Version " | "Welcome to Advanced Memory Diagnostic" | "GNR-4.3.0" {
+                ev->fw_family = 2;
+                return STL_LK_AMT_BANNER;
+            }
+            ("AMT" | "AMEMDIAG") WS "Test Algo Count:" {
+                int32_t cnt = 0;
+                if (parse_i32_at(YYCURSOR, lim, &cnt, NULL)) {
+                    ev->val1 = cnt; /* algorithm count */
+                }
+                ev->subkind = 0;
+                return STL_LK_AMT_SUMMARY;
+            }
+            ("AMT" | "AMEMDIAG") WS "Test Result Summary:" |
+            ("AMT" | "AMEMDIAG") WS "Test Result:" |
+            "AMT Test PASS" | "AMEMDIAG Test PASS" | "All Test PASS" |
+            "AMT Test FAIL" | "AMEMDIAG Test FAIL" | "All Test FAIL" {
+                extract_coords_and_addr(s, end, ev);
+                /* Determine scope: summary vs per-socket */
+                for (const uint8_t *p = tok; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "summary", &af)) {
+                        ev->val2 = 1; /* scope = summary */
+                    }
+                    if (match_ci_kw(p, lim, "fail", &af) || match_ci_kw(p, lim, "block", &af)) {
+                        ev->subkind = 2;
+                    } else if (match_ci_kw(p, lim, "pass", &af) && ev->subkind != 2) {
+                        ev->subkind = 1;
+                    }
+                }
+                return STL_LK_AMT_SUMMARY;
+            }
+            "Total Error Count" {
+                int32_t cnt = 0;
+                if (parse_i32_at(YYCURSOR, lim, &cnt, NULL)) {
+                    ev->val0 = cnt;
+                    ev->subkind = (cnt > 0) ? 2 : 1;
+                }
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_AMT_SUMMARY;
+            }
+            "[" ("AMT" | "AMEMDIAG") WS DIG "/" DIG WS DIG "/" DIG WS DIG "/" DIG "]" {
+                /* e.g. [0][AMT 1/1 1/1 3/24] Algo ... */
+                ev->fw_family = (tok[1] == 'A' && tok[2] == 'M' && tok[3] == 'E') ? 2 : 1;
+                const uint8_t *p = tok + 4;
+                while (p < YYCURSOR && (*p < '0' || *p > '9')) p++;
+                int32_t r1=0, r2=0, p1=0, p2=0, a1=0, a2=0;
+                if (parse_i32_at(p, YYCURSOR, &r1, &p) && p < YYCURSOR && *p == '/' &&
+                    parse_i32_at(p+1, YYCURSOR, &r2, &p) &&
+                    parse_i32_at(p, YYCURSOR, &p1, &p) && p < YYCURSOR && *p == '/' &&
+                    parse_i32_at(p+1, YYCURSOR, &p2, &p) &&
+                    parse_i32_at(p, YYCURSOR, &a1, &p) && p < YYCURSOR && *p == '/' &&
+                    parse_i32_at(p+1, YYCURSOR, &a2, &p)) {
+                    ev->val0 = a1; /* algorithm_index */
+                    ev->val1 = a2; /* algorithm_count */
+                    if (a2 > 0) ev->val2 = (a1 * 100) / a2;
+                }
+                return STL_LK_AMT_PROGRESS;
+            }
+            "Failure detected - Advanced Memtest" | "Error Address" | "Fail Address" |
+            "Data Compare Error" | "[AMT_ERR]" | "[AMEMDIAG_ERR]" |
+            "[" ("HS" | "HD") "_MemoryError]" {
+                ev->subkind = 2;
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_AMT_ERROR;
+            }
+            "Logical Rank" WS "=" | "Error on rising strobe:" | "Error on falling strobe:" {
+                ev->subkind = 5; /* 3-line AMT diagnostic continuation */
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_AMT_ERROR;
+            }
+            "Failing DIMM" | "[BIOS][FailMode]" |
+            "Training Fail" | "BIST Error" | "BIST FAIL" | "Uncorrectable" |
+            "Correctable error threshold exceeded" {
+                ev->subkind = 2;
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_TRAINING_ERROR;
+            }
+            "UEFI Interactive Shell" {
+                return STL_LK_UEFI_BANNER;
+            }
+            "Start PXE over IPv4" | "Downloading NBP file" | "NBP filename is" {
+                return STL_LK_PXE_BOOT;
+            }
+            "PassMark MemTest86" | "MemTest86 V" | "MemTest86 v" |
+            "Found configuration file:" | "*** TEST SESSION -" | "Launching 118.efi" |
+            "STL_SIM TEST_START MT" {
+                return STL_LK_MT_BANNER;
+            }
+            "STL_SIM TEST_RESULT " ("PASS" | "FAIL") {
+                for (const uint8_t *p = tok; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "fail", &af)) {
+                        ev->subkind = 2;
+                        return STL_LK_MT_FAIL_COMPLETE;
+                    }
+                }
+                ev->subkind = 1;
+                return STL_LK_MT_PASS_COMPLETE;
+            }
+            "[MEM ERROR" | "[ECC Errors]" | "[Data Error]" | "ECC Error:" {
+                ev->subkind = 2;
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_MT_ERROR;
+            }
+            "Channel/Slot:" | "(Chan,Slot,Rank,Bank,Row," {
+                ev->subkind = 5; /* 2nd-line MT ECC/Data Error coordinate continuation */
+                extract_coords_and_addr(s, end, ev);
+                return STL_LK_MT_ERROR;
+            }
+            "Finished pass #" DIG WS "(of" WS DIG ")" {
+                int32_t pno = 0, ptot = 0;
+                const uint8_t *nx = NULL;
+                if (parse_i32_at(tok + 15, lim, &pno, &nx)) {
+                    const uint8_t *ofp = memchr(tok + 15, 'f', (size_t)(lim - (tok + 15)));
+                    if (ofp) parse_i32_at(ofp + 1, lim, &ptot, NULL);
+                }
+                int32_t errs = 0;
+                for (const uint8_t *p = YYCURSOR; p + 6 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "count", &af) || match_ci_kw(p, lim, "errors", &af)) {
+                        int32_t v = 0;
+                        if (parse_i32_at(af, lim, &v, NULL)) errs += v;
+                    }
+                }
+                ev->val0 = errs;
+                if (ptot > 0 && pno >= ptot) {
+                    ev->subkind = (errs > 0) ? 2 : 1;
+                    return (errs > 0) ? STL_LK_MT_FAIL_COMPLETE : STL_LK_MT_PASS_COMPLETE;
+                }
+                ev->val2 = (ptot > 0) ? ((pno * 100) / ptot) : 50;
+                return STL_LK_MT_PROGRESS;
+            }
+            ("Test Result" | "Result") WS ":" WS ("PASS" | "FAIL" | "FAILED") {
+                for (const uint8_t *p = tok; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "fail", &af) || match_ci_kw(p, lim, "failed", &af)) {
+                        ev->subkind = 2;
+                        return STL_LK_MT_FAIL_COMPLETE;
+                    }
+                    if (match_ci_kw(p, lim, "pass", &af)) {
+                        ev->subkind = 1;
+                        return STL_LK_MT_PASS_COMPLETE;
+                    }
+                }
+                continue;
+            }
+            "Pass complete, no errors" {
+                ev->subkind = 1;
+                ev->val0 = 0;
+                return STL_LK_MT_PASS_COMPLETE;
+            }
+            "Test Complete" {
+                extract_coords_and_addr(s, end, ev);
+                if (ev->val0 > 0) {
+                    ev->subkind = 2;
+                    return STL_LK_MT_FAIL_COMPLETE;
+                }
+                for (const uint8_t *p = YYCURSOR; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "fail", &af)) {
+                        ev->subkind = 2;
+                        return STL_LK_MT_FAIL_COMPLETE;
+                    }
+                }
+                ev->subkind = 1;
+                return STL_LK_MT_PASS_COMPLETE;
+            }
+            "Running test #" DIG {
+                int32_t tid = 0;
+                if (parse_i32_at(tok + 14, lim, &tid, NULL)) {
+                    ev->val0 = tid;
+                    ev->val1 = 13;
+                    ev->val2 = (tid >= 0 && tid <= 13) ? ((tid * 100) / 14) : 50;
+                }
+                return STL_LK_MT_PROGRESS;
+            }
+            "N" [01] ".C" DIG (".D" [01])? (".SC" [01])? ".R" DIG (".L" DIG)? WS ":" {
+                extract_ncd_token(s, end, ev);
+                for (const uint8_t *q = YYCURSOR; q + 4 <= lim; q++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(q, lim, "advanced memtest", &af) ||
+                        match_ci_kw(q, lim, "failure detected", &af)) {
+                        ev->subkind = 2;
+                        extract_coords_and_addr(s, end, ev);
+                        return STL_LK_AMT_ERROR;
+                    }
+                    if (match_ci_kw(q, lim, "error", &af) || match_ci_kw(q, lim, "failed", &af)) {
+                        ev->subkind = 2;
+                        extract_coords_and_addr(s, end, ev);
+                        return STL_LK_TRAINING_ERROR;
+                    }
+                }
+                return STL_LK_RMT_ROW;
+            }
+            "N" [01] ".C" DIG ".D" [01] {
+                extract_ncd_token(s, end, ev);
+                for (const uint8_t *q = tok; q + 11 <= lim; q++) {
+                    const uint8_t *af_por = NULL;
+                    if (match_ci_kw(q, lim, "minimum por", &af_por)) {
+                        ev->subkind = 4;
+                        return STL_LK_DIMM_INVENTORY;
+                    }
+                }
+                for (const uint8_t *p = tok; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "disabled", &af)) {
+                        ev->subkind = 3;
+                        return STL_LK_DIMM_INVENTORY;
+                    }
+                    if (match_ci_kw(p, lim, "not", &af) || match_ci_kw(p, lim, "empty", &af) ||
+                        match_ci_kw(p, lim, "absent", &af)) {
+                        ev->subkind = 0;
+                        return STL_LK_DIMM_INVENTORY;
+                    }
+                    if (match_ci_kw(p, lim, "present", &af) || match_ci_kw(p, lim, "ddr5", &af) ||
+                        match_ci_kw(p, lim, "enabled", &af) || match_ci_kw(p, lim, "test", &af)) {
+                        ev->subkind = 4;
+                        return STL_LK_DIMM_INVENTORY;
+                    }
+                    if (match_ci_kw(p, lim, "fail", &af) || match_ci_kw(p, lim, "error", &af)) {
+                        ev->subkind = 2;
+                        extract_coords_and_addr(s, end, ev);
+                        return STL_LK_TRAINING_ERROR;
+                    }
+                }
+                continue;
+            }
+            "Test:" WS DIG {
+                for (const uint8_t *p = YYCURSOR; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "expected", &af) || match_ci_kw(p, lim, "actual", &af)) {
+                        ev->subkind = 2;
+                        extract_coords_and_addr(s, end, ev);
+                        return STL_LK_MT_ERROR;
+                    }
+                }
+                int32_t tnum = 0;
+                const uint8_t *nx = NULL;
+                if (parse_i32_at(tok + 5, lim, &tnum, &nx)) {
+                    ev->val0 = tnum;
+                    if (nx && nx < lim && *nx == '/') {
+                        int32_t ttot = 0;
+                        if (parse_i32_at(nx + 1, lim, &ttot, &nx)) ev->val1 = ttot;
+                    }
+                }
+                for (const uint8_t *p = YYCURSOR; p < lim; p++) {
+                    if (*p == '%' && p > buf && p[-1] >= '0' && p[-1] <= '9') {
+                        const uint8_t *dg = p - 1;
+                        while (dg > buf && dg[-1] >= '0' && dg[-1] <= '9') dg--;
+                        int32_t pct = 0;
+                        if (parse_i32_at(dg, p, &pct, NULL)) ev->val2 = pct;
+                        break;
+                    }
+                }
+                return STL_LK_MT_PROGRESS;
+            }
+            ("Test Pattern" | "Algo" WS "#" | "AlgoId") {
+                extract_coords_and_addr(s, end, ev);
+                int32_t aid = -1;
+                if (parse_i32_at(YYCURSOR, lim, &aid, NULL) && aid >= 0) ev->val0 = aid;
+                for (const uint8_t *p = buf; p + 4 <= lim; p++) {
+                    const uint8_t *af = NULL;
+                    if (match_ci_kw(p, lim, "fail", &af)) { ev->subkind = 2; break; }
+                    if (match_ci_kw(p, lim, "pass", &af)) { ev->subkind = 1; }
+                }
+                return STL_LK_AMT_PROGRESS;
+            }
+            ("BankGroup" | "SubRank") {
+                ev->subkind = 5;
+                extract_coords_and_addr(s, end, ev);
+                if (ev->cpu >= 0 || ev->channel >= 0 || ev->bank >= 0) {
+                    return STL_LK_AMT_ERROR;
+                }
+                continue;
+            }
+            "\x00" { break; }
+            ANY { continue; }
+        */
+    }
+
+    return STL_LK_NONE;
+}
+
+void stl_re2c_parse_line(const uint8_t *line, size_t len, uint32_t tag_mask, StlRe2cEvent *ev) {
+    memset(ev, 0, sizeof(*ev));
+    ev->cpu     = -1;
+    ev->channel = -1;
+    ev->dimm    = -1;
+    ev->rank    = -1;
+    ev->bank    = -1;
+    if (!line || len == 0) return;
+
+    const uint8_t *s = line;
+    const uint8_t *e = line + len;
+    trim_ws(&s, &e);
+    if (s >= e) return;
+
+    if (tag_mask == 0 && s[0] == '.') {
+        return;
+    }
+
+    ev->kind = re2c_scan_token(s, e, ev);
+}
+
+int stl_re2c_detect_halfline_prompt(const uint8_t *buf, size_t len, StlRe2cEvent *ev) {
+    memset(ev, 0, sizeof(*ev));
+    ev->cpu     = -1;
+    ev->channel = -1;
+    ev->dimm    = -1;
+    ev->rank    = -1;
+    ev->bank    = -1;
+    if (!buf || len == 0) return 0;
+
+    const uint8_t *s = buf;
+    const uint8_t *e = buf + len;
+    trim_ws(&s, &e);
+    if (s >= e) return 0;
+
+    uint32_t k = re2c_scan_token(s, e, ev);
+    if (k == STL_LK_ICT_PROMPT || k == STL_LK_ICT_ENTER_HINT ||
+        k == STL_LK_AMT_PROMPT || k == STL_LK_UEFI_PROMPT_EFI ||
+        k == STL_LK_UEFI_PROMPT_ROOT) {
+        ev->kind = k;
+        return 1;
+    }
+
+    size_t tlen = (size_t)(e - s);
+    if (tlen >= 4 && memcmp(e - 4, "UIP>", 4) == 0) {
+        ev->kind = STL_LK_ICT_PROMPT;
+        return 1;
+    }
+    if (tlen >= 26 && memcmp(e - 26, "Please input your command:", 26) == 0) {
+        ev->kind = STL_LK_ICT_PROMPT;
+        extract_leading_bracket_cpu(s, e, ev);
+        return 1;
+    }
+    if (tlen >= 25 && memcmp(e - 25, "Please input your command", 25) == 0) {
+        ev->kind = STL_LK_ICT_PROMPT;
+        extract_leading_bracket_cpu(s, e, ev);
+        return 1;
+    }
+    if (tlen >= 7 && memcmp(e - 7, "[AMT #]", 7) == 0) {
+        ev->kind = STL_LK_AMT_PROMPT;
+        ev->fw_family = 1;
+        if (tlen >= 10 && e[-10] == '[' && (e[-9] == '0' || e[-9] == '1') && e[-8] == ']') {
+            ev->cpu = (int8_t)(e[-9] - '0');
+        }
+        return 1;
+    }
+    if (tlen >= 12 && memcmp(e - 12, "[AMEMDIAG #]", 12) == 0) {
+        ev->kind = STL_LK_AMT_PROMPT;
+        ev->fw_family = 2;
+        if (tlen >= 15 && e[-15] == '[' && (e[-14] == '0' || e[-14] == '1') && e[-13] == ']') {
+            ev->cpu = (int8_t)(e[-14] - '0');
+        }
+        return 1;
+    }
+    if (tlen >= 6 && memcmp(e - 6, "Shell>", 6) == 0) {
+        ev->kind = STL_LK_UEFI_PROMPT_ROOT;
+        ev->fs_index = 255;
+        return 1;
+    }
+    /* Check trailing FSx:\EFI\> or FSx:\> */
+    if (tlen >= 6 && e[-1] == '>') {
+        for (size_t i = (tlen > 24 ? tlen - 24 : 0); i + 4 < tlen; i++) {
+            if (s[i] == 'F' && s[i+1] == 'S' && s[i+2] >= '0' && s[i+2] <= '9' && s[i+3] == ':') {
+                ev->fs_index = (uint8_t)(s[i+2] - '0');
+                for (size_t j = i + 4; j + 3 <= tlen; j++) {
+                    if ((s[j] == 'E' || s[j] == 'e') && (s[j+1] == 'F' || s[j+1] == 'f') &&
+                        (s[j+2] == 'I' || s[j+2] == 'i')) {
+                        ev->kind = STL_LK_UEFI_PROMPT_EFI;
+                        return 1;
+                    }
+                }
+                ev->kind = STL_LK_UEFI_PROMPT_ROOT;
+                return 1;
+            }
+        }
+    }
+    return 0;
+}

Разница между файлами не показана из-за своего большого размера
+ 1204 - 0
native/stl_accel/scan_asm.S


Разница между файлами не показана из-за своего большого размера
+ 1774 - 0
native/stl_accel/src/actors.rs


Разница между файлами не показана из-за своего большого размера
+ 1664 - 0
native/stl_accel/src/api.rs


Разница между файлами не показана из-за своего большого размера
+ 1310 - 0
native/stl_accel/src/commands.rs


+ 93 - 0
native/stl_accel/src/config.rs

@@ -0,0 +1,93 @@
+// config.rs — Server CLI arguments, version/commit metadata, and station config loader (v0.8.1.18)
+
+use crate::json::{parse_json, JsonVal};
+use std::env;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+pub static COMPILED_VERSION: &str = include_str!("../../../VERSION");
+
+#[derive(Clone, Debug)]
+pub struct ServerArgs {
+    pub config_path: PathBuf,
+    pub data_dir: PathBuf,
+    pub web_listen: String,
+    pub grpc_listen: String,
+    pub web_dir: PathBuf,
+    pub contracts_path: PathBuf,
+    pub version: String,
+    pub commit: String,
+}
+
+impl ServerArgs {
+    pub fn parse() -> Result<Self, String> {
+        let args: Vec<String> = env::args().collect();
+        let mut config_path = PathBuf::from("config/station0-live.json");
+        let mut data_dir = PathBuf::from("data");
+        let mut web_listen = "0.0.0.0:8080".to_string();
+        let mut grpc_listen = "0.0.0.0:50051".to_string();
+        let mut web_dir = PathBuf::from("web");
+        let mut contracts_path = PathBuf::from("contracts/firmware-vd012.json");
+
+        let mut i = 1;
+        while i < args.len() {
+            match args[i].as_str() {
+                "--config" if i + 1 < args.len() => {
+                    config_path = PathBuf::from(&args[i + 1]);
+                    i += 2;
+                }
+                "--data-dir" if i + 1 < args.len() => {
+                    data_dir = PathBuf::from(&args[i + 1]);
+                    i += 2;
+                }
+                "--web-listen" if i + 1 < args.len() => {
+                    web_listen = args[i + 1].clone();
+                    i += 2;
+                }
+                "--listen" | "--grpc-listen" if i + 1 < args.len() => {
+                    grpc_listen = args[i + 1].clone();
+                    i += 2;
+                }
+                "--web-dir" if i + 1 < args.len() => {
+                    web_dir = PathBuf::from(&args[i + 1]);
+                    i += 2;
+                }
+                "--contracts" if i + 1 < args.len() => {
+                    contracts_path = PathBuf::from(&args[i + 1]);
+                    i += 2;
+                }
+                other => {
+                    return Err(format!(
+                        "未知命令行参数 '{}'。支持参数: --config <path> --data-dir <dir> --web-listen <addr> --listen <grpc_addr> --web-dir <dir> --contracts <path>",
+                        other
+                    ));
+                }
+            }
+        }
+
+        let version = env::var("STL_VERSION")
+            .ok()
+            .filter(|s| !s.trim().is_empty())
+            .unwrap_or_else(|| COMPILED_VERSION.trim().to_string());
+        let commit = env::var("STL_BUILD_COMMIT")
+            .ok()
+            .filter(|s| !s.trim().is_empty() && s != "unknown")
+            .unwrap_or_else(|| "dev".to_string());
+
+        Ok(Self {
+            config_path,
+            data_dir,
+            web_listen,
+            grpc_listen,
+            web_dir,
+            contracts_path,
+            version,
+            commit,
+        })
+    }
+}
+
+pub fn load_config_json(path: &Path) -> Option<JsonVal> {
+    let txt = fs::read_to_string(path).ok()?;
+    parse_json(&txt).ok()
+}

+ 615 - 0
native/stl_accel/src/devices.rs

@@ -0,0 +1,615 @@
+// devices.rs — Non-blocking POSIX PTY / Serial (/dev/ttyUSB0, TCP, SSH, SOL),
+//              8B/20ms TX pacer, persistent IPMI shell worker, 24-ch BMC SDR parser,
+//              and local thermal chamber serial telemetry.
+
+use crate::lib;
+use crate::results::{now_ms, StationState};
+use std::collections::BTreeMap;
+use std::net::{SocketAddr, TcpStream};
+use std::path::Path;
+use std::process::Command;
+use std::sync::{Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+static STATION_CLAIMED_HOSTS: OnceLock<Mutex<BTreeMap<String, String>>> = OnceLock::new();
+
+fn claimed_hosts_map() -> &'static Mutex<BTreeMap<String, String>> {
+    STATION_CLAIMED_HOSTS.get_or_init(|| Mutex::new(BTreeMap::new()))
+}
+
+pub fn register_station_host_claim(station_id: &str, host: &str) {
+    if station_id.is_empty() {
+        return;
+    }
+    if let Ok(mut map) = claimed_hosts_map().lock() {
+        let h = host.trim();
+        if h.is_empty() || h.starts_with("/dev/") {
+            map.remove(station_id);
+        } else {
+            map.insert(station_id.to_string(), h.to_string());
+        }
+    }
+}
+
+fn is_host_claimed_by_other(preferred: &str, candidate: &str) -> bool {
+    let Ok(map) = claimed_hosts_map().lock() else {
+        return false;
+    };
+    let pref_owners: Vec<&String> = map
+        .iter()
+        .filter_map(|(sid, h)| if h == preferred { Some(sid) } else { None })
+        .collect();
+    for (sid, h) in map.iter() {
+        if h == candidate && !pref_owners.contains(&sid) {
+            return true;
+        }
+    }
+    false
+}
+
+pub fn probe_tcp_port(host: &str, port: u16, timeout_ms: u64) -> bool {
+    let Ok(addr) = format!("{}:{}", host, port).parse::<SocketAddr>() else {
+        return false;
+    };
+    TcpStream::connect_timeout(&addr, Duration::from_millis(timeout_ms)).is_ok()
+}
+
+/// Auto-probe failover between 192.168.2.166 and 192.168.2.165 when preferred BMC is unreachable,
+/// while strictly preventing an offline station from hijacking a sibling host already claimed by another station.
+pub fn resolve_reachable_bmc_host(preferred: &str, port: u16) -> String {
+    let trimmed = preferred.trim();
+    if trimmed.is_empty() || trimmed.starts_with("/dev/") {
+        return trimmed.to_string();
+    }
+    let check_port = if port > 0 { port } else { 22 };
+    if probe_tcp_port(trimmed, check_port, 80) {
+        return trimmed.to_string();
+    }
+    let sibling = match trimmed {
+        "192.168.2.165" => Some("192.168.2.166"),
+        "192.168.2.166" => Some("192.168.2.165"),
+        _ => None,
+    };
+    if let Some(alt) = sibling {
+        if !is_host_claimed_by_other(trimmed, alt) && probe_tcp_port(alt, check_port, 80) {
+            return alt.to_string();
+        }
+    }
+    trimmed.to_string()
+}
+
+pub fn open_station_pty(st: &mut StationState, data_dir: &Path) -> Result<(), String> {
+    close_station_pty(st);
+    if !st.console_enabled {
+        return Err("控制台未启用".to_string());
+    }
+    let tr = st.console_transport.as_str();
+    let is_local_tty = tr == "serial"
+        || tr == "tty"
+        || tr == "tty_serial"
+        || tr == "usb_serial"
+        || tr == "local_serial"
+        || st.console_host.starts_with("/dev/");
+    if !is_local_tty && st.console_host.is_empty() {
+        return Err("控制台未配置目标主机 IP 或串口设备".to_string());
+    }
+
+    let mut mfd: i32 = -1;
+    let mut cpid: i32 = -1;
+
+    if is_local_tty {
+        let dev_path = if st.console_host.starts_with("/dev/") {
+            st.console_host.as_str()
+        } else {
+            "/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);
+        mfd = unsafe { lib::c_pty_open_serial_115200(dev_c.as_ptr()) };
+        cpid = 0;
+    } else if tr == "tcp_serial" || tr == "rs232_tcp" {
+        let port = if st.console_port > 0 { st.console_port } else { 4001 };
+        let host_c = format!("{}\0", st.console_host);
+        mfd = unsafe { lib::c_pty_open_tcp_serial(host_c.as_ptr(), port, 250) };
+        cpid = 0;
+    } else {
+        let port_u16 = if st.console_port > 0 {
+            st.console_port as u16
+        } else {
+            2200
+        };
+        let resolved = resolve_reachable_bmc_host(&st.console_host, port_u16);
+        if !resolved.is_empty() && resolved != st.console_host {
+            if st.bmc_host == st.console_host {
+                st.bmc_host = resolved.clone();
+            }
+            st.console_host = resolved;
+            if st.console_host == "192.168.2.165" && st.hot.fw_family == 0 {
+                st.hot.fw_family = 2;
+            }
+        }
+        // Quick reachability guard so sshpass doesn't linger when host is powered off / unplugged
+        if tr != "ipmi_sol" && !probe_tcp_port(&st.console_host, port_u16, 80) {
+            st.diag_state = "error".to_string();
+            st.console_online = false;
+            st.hot.console_online = false;
+            st.diag_last_error = format!("目标串口 {}:{} 当前不可达", st.console_host, port_u16);
+            return Err(st.diag_last_error.clone());
+        }
+        let effective_pass = if st.bmc_password.is_empty() || st.bmc_password == "ADMIN" {
+            "Admin123@pl"
+        } else {
+            st.bmc_password.as_str()
+        };
+        let host_c = format!("{}\0", st.console_host);
+        let user_c = format!("{}\0", st.bmc_user);
+        let pass_c = format!("{}\0", effective_pass);
+        let kh_c = format!("{}\0", data_dir.join("ssh_known_hosts").display());
+        let rc = unsafe {
+            if tr == "ipmi_sol" {
+                lib::c_pty_spawn_ipmi_sol(
+                    host_c.as_ptr(),
+                    user_c.as_ptr(),
+                    pass_c.as_ptr(),
+                    &mut mfd,
+                    &mut cpid,
+                )
+            } else {
+                lib::c_pty_spawn_ssh_console(
+                    host_c.as_ptr(),
+                    port_u16 as i32,
+                    user_c.as_ptr(),
+                    pass_c.as_ptr(),
+                    kh_c.as_ptr(),
+                    &mut mfd,
+                    &mut cpid,
+                )
+            }
+        };
+        if rc != 0 {
+            mfd = -1;
+        }
+    }
+
+    if mfd < 0 {
+        st.diag_state = "error".to_string();
+        st.console_online = false;
+        st.hot.console_online = false;
+        st.diag_last_error = "无法建立串口会话".to_string();
+        return Err(st.diag_last_error.clone());
+    }
+    let now = now_ms();
+    st.pty_master_fd = mfd;
+    st.pty_child_pid = cpid;
+    st.diag_state = "online".to_string();
+    st.console_online = true;
+    st.hot.console_online = true;
+    if st.diag_session_id.is_empty() {
+        st.diag_session_id = format!("D-{}-{}", st.station_id, now);
+    }
+    st.diag_last_error.clear();
+    st.tx_pacer.clear();
+    Ok(())
+}
+
+pub fn close_station_pty(st: &mut StationState) {
+    if st.pty_master_fd >= 0 {
+        unsafe { lib::c_pty_close(st.pty_master_fd, st.pty_child_pid) };
+        st.pty_master_fd = -1;
+        st.pty_child_pid = -1;
+    }
+    st.diag_state = "closed".to_string();
+    st.console_online = false;
+    st.hot.console_online = false;
+    st.prompt_ready = false;
+    st.hot.prompt_ready = false;
+    st.tx_pacer.clear();
+}
+
+/// Non-blocking drain of station serial fd; returns number of bytes read or -1 if disconnected.
+pub fn poll_station_pty(st: &mut StationState) -> isize {
+    if st.pty_master_fd < 0 {
+        st.console_online = false;
+        st.hot.console_online = false;
+        return 0;
+    }
+    let mut total: isize = 0;
+    let mut buf = [0u8; 16384];
+    loop {
+        let n = unsafe { lib::c_pty_read_nonblock(st.pty_master_fd, buf.as_mut_ptr(), buf.len()) };
+        if n > 0 {
+            total += n;
+            st.console_online = true;
+            st.hot.console_online = true;
+            st.observe_serial_chunk(&buf[..n as usize]);
+        } else if n < 0 || (st.pty_child_pid > 0 && unsafe { lib::c_pty_is_alive(st.pty_child_pid) } == 0) {
+            close_station_pty(st);
+            return -1;
+        } else {
+            let alive = st.diag_state == "online";
+            st.console_online = alive;
+            st.hot.console_online = alive;
+            break;
+        }
+    }
+    total
+}
+
+/// Enqueue serial TX bytes into the station's non-blocking 8B / 20ms pacer and flush any ready chunk immediately.
+/// Never sleeps inside any lock or actor turn!
+pub fn write_station_paced(st: &mut StationState, data: &[u8]) -> Result<(), String> {
+    if st.pty_master_fd < 0 || st.diag_state != "online" {
+        return Err("BIOS 串口尚未连接,请先点击「连接串口」".to_string());
+    }
+    if data.is_empty() {
+        return Ok(());
+    }
+    st.clear_halfline_on_tx();
+    st.tx_pacer.enqueue(data);
+    flush_tx_pacer(st, now_ms())
+}
+
+/// Called by the Station Actor's `timerfd` tick to emit 8B chunks spaced by `write_gap_ms` (default 20ms).
+pub fn flush_tx_pacer(st: &mut StationState, now: i64) -> Result<(), String> {
+    if st.tx_pacer.is_empty() {
+        return Ok(());
+    }
+    if st.pty_master_fd < 0 || st.diag_state != "online" {
+        st.tx_pacer.clear();
+        return Err("串口连接已断开".to_string());
+    }
+    let chunk_sz = if st.write_chunk_bytes > 0 {
+        st.write_chunk_bytes
+    } else {
+        8
+    };
+    let gap_ms = (st.write_gap_ms.round() as i64).max(0);
+    while !st.tx_pacer.is_empty() {
+        if st.tx_pacer.next_send_ms > now {
+            break;
+        }
+        let n_take = st.tx_pacer.queue.len().min(chunk_sz);
+        let mut chunk = [0u8; 64];
+        let take_capped = n_take.min(chunk.len());
+        for slot in chunk.iter_mut().take(take_capped) {
+            if let Some(b) = st.tx_pacer.queue.pop_front() {
+                *slot = b;
+            }
+        }
+        let rc = unsafe { lib::c_pty_write_bytes(st.pty_master_fd, chunk.as_ptr(), take_capped) };
+        if rc < 0 {
+            close_station_pty(st);
+            return Err("串口写入失败,连接已断开".to_string());
+        }
+        if gap_ms > 0 {
+            st.tx_pacer.next_send_ms = now + gap_ms;
+            break;
+        }
+    }
+    Ok(())
+}
+
+/// Persistent non-blocking `ipmitool shell` session managed by the dedicated per-station IPMI worker.
+pub struct PersistentIpmiSession {
+    pub host: String,
+    pub user: String,
+    pub pass: String,
+    pub stdin_fd: i32,
+    pub stdout_fd: i32,
+    pub child_pid: i32,
+}
+
+impl Default for PersistentIpmiSession {
+    fn default() -> Self {
+        Self {
+            host: String::new(),
+            user: String::new(),
+            pass: String::new(),
+            stdin_fd: -1,
+            stdout_fd: -1,
+            child_pid: -1,
+        }
+    }
+}
+
+impl PersistentIpmiSession {
+    pub fn close(&mut self) {
+        if self.stdin_fd >= 0 {
+            lib::close_fd(self.stdin_fd);
+        }
+        if self.stdout_fd >= 0 || self.child_pid > 0 {
+            unsafe {
+                lib::c_pty_close(self.stdout_fd, self.child_pid);
+            }
+        }
+        self.stdin_fd = -1;
+        self.stdout_fd = -1;
+        self.child_pid = -1;
+    }
+
+    pub fn ensure_connected(&mut self, host: &str, user: &str, pass: &str) -> bool {
+        if self.stdin_fd >= 0
+            && self.stdout_fd >= 0
+            && self.child_pid > 0
+            && self.host == host
+            && self.user == user
+            && self.pass == pass
+            && unsafe { lib::c_pty_is_alive(self.child_pid) } != 0
+        {
+            return true;
+        }
+        self.close();
+        let host_c = format!("{}\0", host);
+        let user_c = format!("{}\0", user);
+        let pass_c = format!("{}\0", pass);
+        let mut in_fd = -1;
+        let mut out_fd = -1;
+        let mut pid = -1;
+        let rc = unsafe {
+            lib::c_spawn_persistent_ipmi_shell(
+                host_c.as_ptr(),
+                user_c.as_ptr(),
+                pass_c.as_ptr(),
+                17,
+                &mut in_fd,
+                &mut out_fd,
+                &mut pid,
+            )
+        };
+        if rc == 0 && in_fd >= 0 && out_fd >= 0 {
+            self.host = host.to_string();
+            self.user = user.to_string();
+            self.pass = pass.to_string();
+            self.stdin_fd = in_fd;
+            self.stdout_fd = out_fd;
+            self.child_pid = pid;
+            let mut drain = [0u8; 1024];
+            let _ = unsafe { lib::c_pty_read_nonblock(self.stdout_fd, drain.as_mut_ptr(), drain.len()) };
+            true
+        } else {
+            false
+        }
+    }
+
+    /// Execute an interactive subcommand (e.g. `chassis power status`, `sdr list`) on the persistent `ipmitool shell`
+    /// using an epoll timeout on `stdout_fd` (no process fork per poll!).
+    pub fn exec_shell_cmd(&mut self, cmd_line: &str, timeout_ms: u64) -> Option<String> {
+        if self.stdin_fd < 0 || self.stdout_fd < 0 {
+            return None;
+        }
+        let mut tmp = [0u8; 4096];
+        while unsafe { lib::c_pty_read_nonblock(self.stdout_fd, tmp.as_mut_ptr(), tmp.len()) } > 0 {}
+
+        let payload = format!("{}\n", cmd_line.trim());
+        if unsafe { lib::c_pty_write_bytes(self.stdin_fd, payload.as_ptr(), payload.len()) } < 0 {
+            self.close();
+            return None;
+        }
+        let epfd = unsafe { lib::stl_epoll_create() };
+        if epfd >= 0 {
+            unsafe {
+                lib::stl_epoll_ctl_fd(epfd, lib::EPOLL_CTL_ADD, self.stdout_fd, lib::EPOLLIN, 1);
+            }
+        }
+        let deadline = Instant::now() + Duration::from_millis(timeout_ms);
+        let mut acc = Vec::with_capacity(4096);
+        let mut toks = [0u64; 4];
+        let mut evs = [0u32; 4];
+        while Instant::now() < deadline {
+            if epfd >= 0 {
+                let rem = deadline.saturating_duration_since(Instant::now()).as_millis() as i32;
+                let wait_ms = rem.clamp(1, 80);
+                unsafe {
+                    lib::stl_epoll_wait_tokens(epfd, toks.as_mut_ptr(), evs.as_mut_ptr(), 4, wait_ms);
+                }
+            }
+            let n = unsafe { lib::c_pty_read_nonblock(self.stdout_fd, tmp.as_mut_ptr(), tmp.len()) };
+            if n > 0 {
+                acc.extend_from_slice(&tmp[..n as usize]);
+                if let Ok(s) = std::str::from_utf8(&acc) {
+                    if s.contains("ipmitool>") {
+                        lib::close_fd(epfd);
+                        let cleaned = s.replace("ipmitool>", "").trim().to_string();
+                        if !cleaned.is_empty() && !cleaned.contains("Error:") && !cleaned.contains("Unable to establish") {
+                            return Some(cleaned);
+                        }
+                        return None;
+                    }
+                }
+            } else if n < 0 {
+                self.close();
+                break;
+            }
+        }
+        lib::close_fd(epfd);
+        None
+    }
+}
+
+impl Drop for PersistentIpmiSession {
+    fn drop(&mut self) {
+        self.close();
+    }
+}
+
+/// Execute BMC IPMI command via persistent shell first, falling back to dual-password (`Admin123@pl` / `ADMIN`) CLI.
+/// Always runs on the dedicated per-station IPMI worker thread, NEVER blocking any Station Actor!
+pub fn run_ipmi_with_session(
+    sess: Option<&mut PersistentIpmiSession>,
+    host: &str,
+    user: &str,
+    pass: &str,
+    args: &[&str],
+) -> Result<(String, String), String> {
+    if host.is_empty() {
+        return Err("BMC IP 未配置".to_string());
+    }
+    let resolved_host = resolve_reachable_bmc_host(host, 22);
+    let primary_pass = if pass.is_empty() || pass == "ADMIN" {
+        "Admin123@pl"
+    } else {
+        pass
+    };
+    let joined = args.join(" ");
+    // Try persistent ipmitool shell for standard commands (no raw hex quotes issues)
+    if let Some(s) = sess {
+        if !args.iter().any(|a| a.contains(' ')) && s.ensure_connected(&resolved_host, user, primary_pass) {
+            if let Some(out) = s.exec_shell_cmd(&joined, 1800) {
+                return Ok((resolved_host, out));
+            }
+        }
+    }
+    let out = Command::new("ipmitool")
+        .env("IPMI_PASSWORD", primary_pass)
+        .args([
+            "-I",
+            "lanplus",
+            "-N",
+            "1",
+            "-R",
+            "1",
+            "-H",
+            &resolved_host,
+            "-U",
+            user,
+            "-E",
+            "-C",
+            "17",
+        ])
+        .args(args)
+        .output()
+        .map_err(|e| format!("无法执行 ipmitool: {}", e))?;
+    if out.status.success() {
+        return Ok((resolved_host, String::from_utf8_lossy(&out.stdout).to_string()));
+    }
+    let alt_pass = if primary_pass == "Admin123@pl" {
+        "ADMIN"
+    } else {
+        "Admin123@pl"
+    };
+    let out2 = Command::new("ipmitool")
+        .env("IPMI_PASSWORD", alt_pass)
+        .args([
+            "-I",
+            "lanplus",
+            "-N",
+            "1",
+            "-R",
+            "1",
+            "-H",
+            &resolved_host,
+            "-U",
+            user,
+            "-E",
+            "-C",
+            "17",
+        ])
+        .args(args)
+        .output()
+        .map_err(|e| format!("无法执行 ipmitool: {}", e))?;
+    if out2.status.success() {
+        return Ok((resolved_host, String::from_utf8_lossy(&out2.stdout).to_string()));
+    }
+    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
+    Err(format!("BMC ({}) 命令返回非零: {}", resolved_host, stderr.trim()))
+}
+
+pub fn run_ipmi_cmd(host: &str, user: &str, pass: &str, args: &[&str]) -> Result<String, String> {
+    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`).
+/// Never writes to `st.chamber_current_c`!
+pub fn update_dimms_from_bmc_sdr(st: &mut StationState, sdr_output: &str) {
+    let now = now_ms();
+    for line in sdr_output.lines() {
+        let parts: Vec<&str> = line.split('|').map(|s| s.trim()).collect();
+        if parts.len() < 2 {
+            continue;
+        }
+        let sensor_name = parts[0].to_ascii_uppercase();
+        let Some(slot_idx) = map_sdr_sensor_to_slot(&sensor_name) else {
+            continue;
+        };
+        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;
+                    }
+                }
+            }
+        }
+        if let Some(temp_c) = parsed_temp {
+            if let Some(slot) = st.dimms.get_mut(slot_idx) {
+                slot.value_c = Some(temp_c);
+                slot.quality = "reported".to_string();
+                slot.source = "bmc_sdr".to_string();
+                slot.received_ms = now;
+                slot.presence = "present".to_string();
+                if slot.enabled == "unknown" {
+                    slot.enabled = "enabled".to_string();
+                }
+            }
+            st.sync_dimm_to_soa(slot_idx);
+        }
+    }
+}
+
+pub fn map_sdr_sensor_to_slot(sensor: &str) -> Option<usize> {
+    if !sensor.contains("DIMM") {
+        return None;
+    }
+    // Check explicit M..X single-letter naming for CPU1 slots 12..23 (e.g., DIMMM_TEMP, DIMM_M_TEMP)
+    if !sensor.contains("CPU0") && !sensor.contains("P0_") {
+        for (idx, ch) in ('M'..='X').enumerate() {
+            let pat1 = format!("DIMM_{}", ch);
+            let pat2 = format!("DIMM{}", ch);
+            let pat3 = format!("_{}_TEMP", ch);
+            if sensor.contains(&pat1) || sensor.contains(&pat2) || sensor.contains(&pat3) {
+                return Some(12 + idx);
+            }
+        }
+    }
+    let cpu = if sensor.contains("CPU1") || sensor.contains("P1_") || sensor.contains("SOCKET1") {
+        1usize
+    } else if sensor.contains("CPU0") || sensor.contains("P0_") || sensor.contains("SOCKET0") || sensor.starts_with("DIMM") {
+        0usize
+    } else {
+        return None;
+    };
+    for (idx, ch) in ('A'..='L').enumerate() {
+        let pat1 = format!("DIMM_{}", ch);
+        let pat2 = format!("DIMM{}", ch);
+        let pat3 = format!("_{}0", ch);
+        let pat4 = format!("_{}_TEMP", ch);
+        let pat5 = format!("CPU0_{}", ch);
+        let pat6 = format!("CPU1_{}", ch);
+        let pat7 = format!("P0_{}", ch);
+        let pat8 = format!("P1_{}", ch);
+        if sensor.contains(&pat1)
+            || sensor.contains(&pat2)
+            || sensor.ends_with(&pat3)
+            || sensor.contains(&pat4)
+            || sensor.contains(&pat5)
+            || sensor.contains(&pat6)
+            || sensor.contains(&pat7)
+            || sensor.contains(&pat8)
+        {
+            return Some(cpu * 12 + idx);
+        }
+    }
+    None
+}

+ 800 - 0
native/stl_accel/src/firmware.rs

@@ -0,0 +1,800 @@
+// firmware.rs — Authoritative 107_VD012 & CxmtDdrTest Dual-Firmware Contract,
+//               224-Item ICT (IMC Config Tool) + 30-Item AMT Builders & Safe Timing Presets (v0.8.1.18)
+
+use crate::json::{parse_json, JsonVal};
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::Path;
+
+static DEFAULT_CONTRACT_JSON: &str = include_str!("../../../contracts/firmware-vd012.json");
+
+pub struct FirmwareContract {
+    pub raw_catalog: JsonVal,
+    pub uip_commands: BTreeMap<String, String>,
+    pub uip_input_kinds: BTreeMap<String, String>,
+    pub uip_strict_choices: BTreeMap<String, BTreeSet<String>>,
+    pub amt_allowed: BTreeSet<String>,
+}
+
+impl FirmwareContract {
+    pub fn load(path: &Path) -> Self {
+        let txt = fs::read_to_string(path).unwrap_or_else(|_| DEFAULT_CONTRACT_JSON.to_string());
+        let mut raw_catalog = parse_json(&txt)
+            .or_else(|_| parse_json(DEFAULT_CONTRACT_JSON))
+            .unwrap_or_else(|_| JsonVal::obj());
+
+        // Add user-facing ICT (IMC Config Tool) display metadata while keeping wire field names 100% compatible
+        raw_catalog.set("display_stage_name", JsonVal::Str("ICT (IMC Config Tool)".to_string()));
+        raw_catalog.set("display_stage1_name", JsonVal::Str("ICT Stage 1".to_string()));
+        raw_catalog.set("display_stage2_name", JsonVal::Str("ICT Stage 2".to_string()));
+        raw_catalog.set("safe_error_presets", Self::safe_error_injection_presets_json());
+
+        let mut uip_commands = BTreeMap::new();
+        let mut uip_input_kinds = BTreeMap::new();
+        let mut uip_strict_choices = BTreeMap::new();
+
+        if let Some(items) = raw_catalog.get_arr("items") {
+            for item in items {
+                let id = item.get_str_or("id", "");
+                if id.is_empty() {
+                    continue;
+                }
+                let cmd = item.get_str_or("command", &id);
+                let ikind = item.get_str_or("input_kind", "raw");
+                uip_commands.insert(id.clone(), cmd);
+                uip_input_kinds.insert(id.clone(), ikind.clone());
+                if ikind == "choice" {
+                    if let Some(ch_arr) = item.get_arr("choices") {
+                        let mut set = BTreeSet::new();
+                        for c in ch_arr {
+                            if let Some(s) = c.as_str() {
+                                set.insert(s.to_ascii_lowercase());
+                            } else if let Some(v) = c.get_str("value") {
+                                set.insert(v.to_ascii_lowercase());
+                            }
+                        }
+                        if !set.is_empty() {
+                            uip_strict_choices.insert(id, set);
+                        }
+                    }
+                }
+            }
+        }
+
+        let mut amt_allowed = BTreeSet::new();
+        if let Some(amt_obj) = raw_catalog.get("amt") {
+            if let Some(amt_items) = amt_obj.get_arr("items") {
+                for item in amt_items {
+                    let id = item.get_str_or("id", "");
+                    if !id.is_empty() && item.get_bool("configuration_allowed").unwrap_or(true) {
+                        amt_allowed.insert(id);
+                    }
+                }
+            }
+        }
+
+        Self {
+            raw_catalog,
+            uip_commands,
+            uip_input_kinds,
+            uip_strict_choices,
+            amt_allowed,
+        }
+    }
+
+    /// Safe DRAM error-injection presets: pure timing/refresh margin pulls (zero overvoltage,
+    /// zero thermal runaway, non-destructive to DDR5 oxide & cell lifetime).
+    pub fn safe_error_injection_presets_json() -> JsonVal {
+        let mut arr = Vec::new();
+
+        let mut p1 = JsonVal::obj();
+        p1.set("preset_id", JsonVal::Str("safe_trcd_trp_pull".to_string()));
+        p1.set(
+            "label",
+            JsonVal::Str("安全时序拉偏 (tRCD=22 / tRP=22, 零加压不伤颗粒)".to_string()),
+        );
+        p1.set("voltage_safe", JsonVal::Bool(true));
+        let mut ov1 = Vec::new();
+        for (id, val) in [("errhandle", "disable"), ("actm.trcd", "22"), ("actm.trp", "22")] {
+            let mut o = JsonVal::obj();
+            o.set("id", JsonVal::Str(id.to_string()));
+            o.set("mode", JsonVal::Str("override".to_string()));
+            o.set("value", JsonVal::Str(val.to_string()));
+            ov1.push(o);
+        }
+        p1.set("uip_overrides", JsonVal::Arr(ov1));
+        arr.push(p1);
+
+        let mut p2 = JsonVal::obj();
+        p2.set("preset_id", JsonVal::Str("safe_trfc_pull".to_string()));
+        p2.set(
+            "label",
+            JsonVal::Str("安全刷新窗口压缩 (tRFC=180 / tRFCsb=110, 零加压触发软位翻转)".to_string()),
+        );
+        p2.set("voltage_safe", JsonVal::Bool(true));
+        let mut ov2 = Vec::new();
+        for (id, val) in [("errhandle", "disable"), ("actm.trfc", "180"), ("actm.trfcsb", "110")] {
+            let mut o = JsonVal::obj();
+            o.set("id", JsonVal::Str(id.to_string()));
+            o.set("mode", JsonVal::Str("override".to_string()));
+            o.set("value", JsonVal::Str(val.to_string()));
+            ov2.push(o);
+        }
+        p2.set("uip_overrides", JsonVal::Arr(ov2));
+        arr.push(p2);
+
+        JsonVal::Arr(arr)
+    }
+
+    pub fn safe_timing_pull_presets(fw_family_name: &str) -> JsonVal {
+        let mut root = JsonVal::obj();
+        root.set("firmware_family", JsonVal::Str(fw_family_name.to_string()));
+        root.set("voltage_safe", JsonVal::Bool(true));
+        let mut presets = match Self::safe_error_injection_presets_json() {
+            JsonVal::Arr(a) => a,
+            _ => Vec::new(),
+        };
+        if fw_family_name == "cxmt" {
+            for p in &mut presets {
+                if let Some(ovs) = p.get_arr("uip_overrides").cloned() {
+                    let filtered: Vec<JsonVal> = ovs
+                        .into_iter()
+                        .filter(|o| o.get_str_or("id", "") != "actm.trfcsb")
+                        .collect();
+                    p.set("uip_overrides", JsonVal::Arr(filtered));
+                }
+            }
+        }
+        root.set("presets", JsonVal::Arr(presets));
+        root
+    }
+
+    pub fn memory_params_to_uip_overrides_for_family(
+        mem_params: &JsonVal,
+        run_rmt: Option<bool>,
+        rmt_cfg: Option<&JsonVal>,
+        fw_family_name: &str,
+    ) -> (Vec<JsonVal>, Vec<String>) {
+        let (ovs, raws) = Self::memory_params_to_uip_overrides(mem_params, run_rmt, rmt_cfg);
+        if fw_family_name == "cxmt" {
+            let has_trfc = ovs.iter().any(|o| o.get_str_or("id", "") == "actm.trfc");
+            let mut mapped = Vec::with_capacity(ovs.len());
+            for mut o in ovs {
+                if o.get_str_or("id", "") == "actm.trfcsb" {
+                    if has_trfc {
+                        continue;
+                    }
+                    o.set("id", JsonVal::Str("actm.trfc".to_string()));
+                }
+                mapped.push(o);
+            }
+            return (mapped, raws);
+        }
+        (ovs, raws)
+    }
+
+    pub fn memory_params_to_uip_overrides(
+        mem_params: &JsonVal,
+        run_rmt: Option<bool>,
+        rmt_cfg: Option<&JsonVal>,
+    ) -> (Vec<JsonVal>, Vec<String>) {
+        let mut ovs = Vec::new();
+        let mut raws = Vec::new();
+        let mut rmt_enabled = run_rmt;
+        let mut has_explicit_rmt = false;
+
+        if let Some(r_obj) = rmt_cfg {
+            if rmt_enabled.is_none() {
+                rmt_enabled = r_obj.get_bool("enabled");
+            }
+            if let Some(sel) = r_obj.get_arr("selected") {
+                for item in sel {
+                    let Some(s) = item.as_str() else { continue };
+                    let cmd_part = s.split('(').next().unwrap_or(s).trim().to_ascii_lowercase();
+                    if cmd_part == "rmt enable" || cmd_part == "rmt" || s.contains("Rank Margin Tool") {
+                        has_explicit_rmt = true;
+                        let mut o = JsonVal::obj();
+                        o.set("id", JsonVal::Str("rmt".to_string()));
+                        o.set("mode", JsonVal::Str("override".to_string()));
+                        o.set("value", JsonVal::Str("enable".to_string()));
+                        ovs.push(o);
+                    } else if cmd_part == "rmt backside" {
+                        has_explicit_rmt = true;
+                        let mut o = JsonVal::obj();
+                        o.set("id", JsonVal::Str("rmt".to_string()));
+                        o.set("mode", JsonVal::Str("override".to_string()));
+                        o.set("value", JsonVal::Str("backside".to_string()));
+                        ovs.push(o);
+                    } else if cmd_part == "rmt userdef 1" {
+                        let mut o = JsonVal::obj();
+                        o.set("id", JsonVal::Str("rmt.userdef".to_string()));
+                        o.set("mode", JsonVal::Str("override".to_string()));
+                        o.set("value", JsonVal::Str("1".to_string()));
+                        ovs.push(o);
+                    } else if cmd_part == "rmt userdef 2" {
+                        let mut o = JsonVal::obj();
+                        o.set("id", JsonVal::Str("rmt.userdef".to_string()));
+                        o.set("mode", JsonVal::Str("override".to_string()));
+                        o.set("value", JsonVal::Str("2".to_string()));
+                        ovs.push(o);
+                    } else if !cmd_part.is_empty() {
+                        raws.push(cmd_part);
+                    }
+                }
+            }
+        }
+
+        for (k, id) in [
+            ("mem vdd", "vol.mem.vdd"),
+            ("mem_vdd", "vol.mem.vdd"),
+            ("mem vddq", "vol.mem.vddq"),
+            ("mem_vddq", "vol.mem.vddq"),
+            ("tCL", "actm.tcl"),
+            ("tcl", "actm.tcl"),
+            ("tRCD", "actm.trcd"),
+            ("trcd", "actm.trcd"),
+            ("tRP", "actm.trp"),
+            ("trp", "actm.trp"),
+            ("tRAS", "actm.tras"),
+            ("tras", "actm.tras"),
+            ("tRFC", "actm.trfc"),
+            ("trfc", "actm.trfc"),
+            ("tRTP", "actm.trtp"),
+            ("trtp", "actm.trtp"),
+            ("trrd_l", "actm.trrd_l"),
+            ("tRRD_L", "actm.trrd_l"),
+            ("tWTR_S", "actm.twtr_s"),
+            ("twtr_s", "actm.twtr_s"),
+            ("tWTR_L", "actm.twtr_l"),
+            ("twtr_l", "actm.twtr_l"),
+            ("tWR", "actm.twr"),
+            ("twr", "actm.twr"),
+            ("tCCD_L", "actm.tccd_l"),
+            ("tccd_l", "actm.tccd_l"),
+            ("trefi", "actm.trefi"),
+            ("tREFI", "actm.trefi"),
+            ("tRFCsb", "actm.trfcsb"),
+            ("trfcsb", "actm.trfcsb"),
+            ("tRFCfgrcsb", "actm.trfcfgrcsb"),
+            ("trfcfgrcsb", "actm.trfcfgrcsb"),
+            ("trrd", "actm.trrd"),
+            ("trrd_s", "actm.trrd_s"),
+            ("tcssr", "actm.tcssr"),
+            ("tcshsrexit", "actm.tcshsrexit"),
+            ("tcwl", "actm.tcwl"),
+            ("trefsb", "actm.trefsb"),
+        ] {
+            if let Some(v) = mem_params.get_i64(k) {
+                if v > 0 && !ovs.iter().any(|x| x.get_str_or("id", "") == id) {
+                    let mut o = JsonVal::obj();
+                    o.set("id", JsonVal::Str(id.to_string()));
+                    o.set("mode", JsonVal::Str("override".to_string()));
+                    o.set("value", JsonVal::Str(v.to_string()));
+                    ovs.push(o);
+                }
+            }
+        }
+        for (k, id) in [("ap", "ap"), ("ecc", "ecc")] {
+            if !ovs.iter().any(|x| x.get_str_or("id", "") == id) {
+                if let Some(b) = mem_params.get_bool(k) {
+                    let mut o = JsonVal::obj();
+                    o.set("id", JsonVal::Str(id.to_string()));
+                    o.set("mode", JsonVal::Str("override".to_string()));
+                    o.set("value", JsonVal::Str(if b { "enable" } else { "disable" }.to_string()));
+                    ovs.push(o);
+                } else if let Some(s) = mem_params.get_str(k) {
+                    let st = s.trim().to_ascii_lowercase();
+                    if st == "enable" || st == "disable" {
+                        let mut o = JsonVal::obj();
+                        o.set("id", JsonVal::Str(id.to_string()));
+                        o.set("mode", JsonVal::Str("override".to_string()));
+                        o.set("value", JsonVal::Str(st));
+                        ovs.push(o);
+                    }
+                }
+            }
+        }
+        if !ovs.iter().any(|x| x.get_str_or("id", "") == "errhandle") {
+            if let Some(b) = mem_params.get_bool("errhandle") {
+                if b {
+                    let mut o = JsonVal::obj();
+                    o.set("id", JsonVal::Str("errhandle".to_string()));
+                    o.set("mode", JsonVal::Str("override".to_string()));
+                    o.set("value", JsonVal::Str("disable".to_string()));
+                    ovs.push(o);
+                }
+            } else if let Some(s) = mem_params.get_str("errhandle") {
+                let st = s.trim().to_ascii_lowercase();
+                if st == "disable" || st == "enable" {
+                    let mut o = JsonVal::obj();
+                    o.set("id", JsonVal::Str("errhandle".to_string()));
+                    o.set("mode", JsonVal::Str("override".to_string()));
+                    o.set("value", JsonVal::Str("disable".to_string()));
+                    ovs.push(o);
+                }
+            }
+        }
+        if !ovs.iter().any(|x| x.get_str_or("id", "") == "debuglog") {
+            let mapped_dbg = if let Some(b) = mem_params.get_bool("debuglog") {
+                // Note: `debuglog off` mutes Hovsee BIOS SerialDebugMsgLevel=0 completely (even prompts!).
+                // Unchecked `debuglog: false` keeps BIOS normal console output; `debuglog: true` sends `debuglog on`.
+                if b { Some("on".to_string()) } else { None }
+            } else if let Some(s) = mem_params.get_str("debuglog") {
+                match s.trim().to_ascii_lowercase().as_str() {
+                    "true" | "1" | "enable" | "on" => Some("on".to_string()),
+                    "false" | "0" | "disable" | "" => None,
+                    "off" => Some("off".to_string()),
+                    "cpgc" => Some("cpgc".to_string()),
+                    "dfe" => Some("dfe".to_string()),
+                    _ => None,
+                }
+            } else {
+                None
+            };
+            if let Some(val) = mapped_dbg {
+                let mut o = JsonVal::obj();
+                o.set("id", JsonVal::Str("debuglog".to_string()));
+                o.set("mode", JsonVal::Str("override".to_string()));
+                o.set("value", JsonVal::Str(val));
+                ovs.push(o);
+            }
+        }
+        if !has_explicit_rmt {
+            if let Some(en) = rmt_enabled {
+                let mut o = JsonVal::obj();
+                o.set("id", JsonVal::Str("rmt".to_string()));
+                o.set("mode", JsonVal::Str("override".to_string()));
+                o.set("value", JsonVal::Str(if en { "enable" } else { "disable" }.to_string()));
+                ovs.push(o);
+            }
+        }
+        (ovs, raws)
+    }
+
+    pub fn multi_step_limit(item_id: &str) -> Option<u32> {
+        match item_id {
+            "maskmain" | "pausemain" => Some(101),
+            "masktrain" | "pausetrain" => Some(84),
+            _ => None,
+        }
+    }
+
+    pub fn parse_multi_steps(item_id: &str, raw_val: &str, max_idx: u32) -> Result<Vec<u32>, String> {
+        let mut steps = Vec::new();
+        let mut seen = BTreeSet::new();
+        for tok in raw_val
+            .split(|c: char| c == ',' || c.is_whitespace())
+            .filter(|s| !s.is_empty())
+        {
+            let idx: u32 = tok
+                .parse()
+                .map_err(|_| format!("{} 步骤索引必须是 0..{} 的十进制整数: {}", item_id, max_idx, tok))?;
+            if idx > max_idx {
+                return Err(format!("{} 步骤索引 {} 超出有效范围 0..{}", item_id, idx, max_idx));
+            }
+            if seen.insert(idx) {
+                steps.push(idx);
+            }
+        }
+        if steps.is_empty() {
+            return Err(format!("请为 {} 填写至少一个步骤索引 (0..{})", item_id, max_idx));
+        }
+        Ok(steps)
+    }
+
+    pub fn command_stage_scope(cmd_line: &str) -> &'static str {
+        let head = cmd_line
+            .split_whitespace()
+            .next()
+            .unwrap_or("")
+            .to_ascii_lowercase();
+        match head.as_str() {
+            "vol2" | "mem" | "mcreg" | "reg2" => "stage2",
+            "spd" | "mr2" | "disabledimm" | "dimminfo" | "rcdreg" | "hppr" | "sppr" => "both",
+            _ => "stage1",
+        }
+    }
+
+    pub fn build_uip_commands(
+        &self,
+        overrides: &[JsonVal],
+        raw_commands: &[String],
+        target_stage: Option<u8>,
+    ) -> Result<Vec<String>, String> {
+        self.build_uip_commands_for_fw(overrides, raw_commands, target_stage, 0)
+    }
+
+    pub fn build_uip_commands_for_family(
+        &self,
+        overrides: &[JsonVal],
+        raw_commands: &[String],
+        target_stage: Option<u8>,
+        fw_family_name: &str,
+    ) -> Result<Vec<String>, String> {
+        let fw_id = if fw_family_name == "cxmt" { 2u8 } else { 1u8 };
+        self.build_uip_commands_for_fw(overrides, raw_commands, target_stage, fw_id)
+    }
+
+    /// Dual-firmware ICT command builder:
+    /// `fw_family == 1` -> Hovsee 107_VD012 (.166, supports extended actm trfcsb/trfcfgrcsb/tcwl/trefsb)
+    /// `fw_family == 2` -> CxmtDdrTest (.165, skips Hovsee-only extended actm subcommands or maps trfcsb->trfc)
+    pub fn build_uip_commands_for_fw(
+        &self,
+        overrides: &[JsonVal],
+        raw_commands: &[String],
+        target_stage: Option<u8>,
+        fw_family: u8,
+    ) -> Result<Vec<String>, String> {
+        let mut seen_ids = BTreeSet::new();
+        let mut active_ids = BTreeSet::new();
+        let mut expanded_lines = Vec::new();
+
+        for ov in overrides {
+            let item_id = ov.get_str_or("id", "");
+            if item_id.is_empty() {
+                return Err("ICT 覆盖项缺少 id".to_string());
+            }
+            if !self.uip_commands.contains_key(&item_id) {
+                return Err(format!("未知 ICT 参数: {}", item_id));
+            }
+            if !seen_ids.insert(item_id.clone()) {
+                return Err(format!("重复的 ICT 参数: {}", item_id));
+            }
+            let mode = ov.get_str_or("mode", "override");
+            if mode == "default" {
+                continue;
+            }
+            if mode != "override" {
+                return Err(format!("无效的 ICT mode: {}", mode));
+            }
+            let val = ov.get_str_or("value", "").trim().to_string();
+            if val.contains('\r') || val.contains('\n') || val.contains('\0') {
+                return Err(format!("ICT 参数值必须为单行文本: {}", item_id));
+            }
+            let ikind = self
+                .uip_input_kinds
+                .get(&item_id)
+                .map(|s| s.as_str())
+                .unwrap_or("raw");
+            if (ikind == "choice" || ikind == "value") && item_id != "errhandle" && val.is_empty() {
+                return Err(format!("请为 {} 填写有效参数值,或取消勾选保持默认", item_id));
+            }
+            if let Some(allowed) = self.uip_strict_choices.get(&item_id) {
+                if !val.is_empty() && !allowed.contains(&val.to_ascii_lowercase()) {
+                    return Err(format!(
+                        "ICT 参数 {} 的取值 '{}' 不在固件支持范围内",
+                        item_id, val
+                    ));
+                }
+            }
+
+            // Dual-firmware adaptation for CxmtDdrTest (.165, fw_family == 2)
+            if fw_family == 2 {
+                if matches!(
+                    item_id.as_str(),
+                    "actm.trfcfgrcsb" | "actm.tcssr" | "actm.tcshsrexit" | "actm.tcwl" | "actm.trefsb"
+                ) {
+                    continue;
+                }
+                if item_id == "actm.trfcsb" && !seen_ids.contains("actm.trfc") {
+                    expanded_lines.push(format!("actm trfc {}", val));
+                    active_ids.insert(item_id);
+                    continue;
+                }
+            }
+
+            let base_cmd = self.uip_commands.get(&item_id).unwrap();
+            if let Some(max_idx) = Self::multi_step_limit(&item_id) {
+                for idx in Self::parse_multi_steps(&item_id, &val, max_idx)? {
+                    let line = format!("{} {}", base_cmd, idx);
+                    if line.len() >= 127 {
+                        return Err(format!("ICT 命令超过 126 字节固件上限: {}", line));
+                    }
+                    expanded_lines.push(line);
+                }
+            } else {
+                let line = format!("{} {}", base_cmd, val).trim().to_string();
+                if line.len() >= 127 {
+                    return Err(format!("ICT 命令超过 126 字节固件上限: {}", line));
+                }
+                expanded_lines.push(line);
+            }
+            active_ids.insert(item_id);
+        }
+
+        for id in &active_ids {
+            if let Some((parent, _)) = id.split_once('.') {
+                if active_ids.contains(parent) && !matches!(parent, "rmt" | "patch" | "txdfe") {
+                    return Err(format!("父项 {} 与子项 {} 不能同时覆盖", parent, id));
+                }
+            }
+        }
+
+        for raw in raw_commands {
+            let trimmed = raw.trim();
+            if trimmed.is_empty() {
+                continue;
+            }
+            if trimmed.contains('\r') || trimmed.contains('\n') || trimmed.contains('\0') {
+                return Err("补充 ICT 命令不能包含换行符".to_string());
+            }
+            if trimmed.len() >= 127 {
+                return Err(format!("补充 ICT 命令超过 126 字节固件上限: {}", trimmed));
+            }
+            expanded_lines.push(trimmed.to_string());
+        }
+
+        if let Some(stg) = target_stage {
+            if stg == 2 {
+                // Stage 2 strictly executes ONLY Stage-2-specific commands (never re-runs Stage-1 rmt/admt/errhandle)
+                expanded_lines.retain(|ln| Self::command_stage_scope(ln) == "stage2");
+            } else {
+                expanded_lines.retain(|ln| {
+                    let scope = Self::command_stage_scope(ln);
+                    scope == "stage1" || scope == "both"
+                });
+            }
+        }
+
+        Ok(expanded_lines)
+    }
+
+    pub fn build_amt_commands(&self, settings: &JsonVal) -> Result<Vec<String>, String> {
+        self.build_amt_commands_for_fw(settings, 0)
+    }
+
+    pub fn build_amt_commands_for_family(
+        &self,
+        settings: &JsonVal,
+        fw_family_name: &str,
+    ) -> Result<Vec<String>, String> {
+        let fw_id = if fw_family_name == "cxmt" { 2u8 } else { 1u8 };
+        self.build_amt_commands_for_fw(settings, fw_id)
+    }
+
+    /// Dual-firmware AMT `tp` plan builder:
+    /// - Converts `selected_algorithms`, `selected`, `only_tests`, `skip_tests`, and `tp_end_step`/`end_step`
+    ///   into compliant 6-field (`algoid,1,0,end_step,0,255`) or 10-field RowHammer (`15`/`20` -> `...,0,0,0x1d4c00,8`)
+    ///   `tp` commands (never relying on ignored `algomask`).
+    /// - Automatically adapts max algorithm count for `GNR-4.3.0` (`fw_family == 2`, 19 algos `0..18`)
+    ///   vs `GNR-4.3.3` (`fw_family == 1` or `0`, 24 algos `0..23`).
+    pub fn build_amt_commands_for_fw(&self, settings: &JsonVal, fw_family: u8) -> Result<Vec<String>, String> {
+        let max_algo_id: u32 = if fw_family == 2 { 18 } else { 23 };
+        let total_algos: u32 = max_algo_id + 1;
+
+        let mut cmds = Vec::new();
+        let mut seen = BTreeSet::new();
+
+        let has_explicit_tp_override = settings
+            .get_arr("overrides")
+            .map(|arr| {
+                arr.iter().any(|ov| {
+                    ov.get_str_or("name", &ov.get_str_or("id", "")).trim() == "tp"
+                        && !ov.get_str_or("value", "").trim().is_empty()
+                })
+            })
+            .unwrap_or(false);
+
+        let mut algo_indices: Option<Vec<u32>> = None;
+        if !has_explicit_tp_override {
+            if let Some(sel_arr) = settings.get_arr("selected_algorithms") {
+                let mut indices = Vec::with_capacity(sel_arr.len());
+                for item in sel_arr {
+                    let idx = item
+                        .get_i64("")
+                        .or_else(|| match item {
+                            JsonVal::Num(n) => Some(*n as i64),
+                            JsonVal::Str(s) => s.trim().split(':').next()?.parse::<i64>().ok(),
+                            _ => None,
+                        })
+                        .ok_or_else(|| "selected_algorithms 元素必须是整数".to_string())?;
+                    if !(0..=23).contains(&idx) {
+                        return Err(format!("AMT 算法索引超出 0..23 范围: {}", idx));
+                    }
+                    if (idx as u32) <= max_algo_id && !indices.contains(&(idx as u32)) {
+                        indices.push(idx as u32);
+                    }
+                }
+                if indices.is_empty() {
+                    return Err("selected_algorithms 不能为空;跳过 AMT 请使用 action=skip".to_string());
+                }
+                algo_indices = Some(indices);
+            } else if let Some(sel_strs) = settings.get_arr("selected") {
+                if !sel_strs.is_empty() {
+                    let mut indices = Vec::new();
+                    for item in sel_strs {
+                        let idx_opt = match item {
+                            JsonVal::Num(n) => Some(*n as i64),
+                            JsonVal::Str(s) => s
+                                .trim()
+                                .split(|c: char| !c.is_ascii_digit())
+                                .next()
+                                .and_then(|d| d.parse::<i64>().ok()),
+                            _ => None,
+                        };
+                        if let Some(idx) = idx_opt {
+                            if (0..=23).contains(&idx)
+                                && (idx as u32) <= max_algo_id
+                                && !indices.contains(&(idx as u32))
+                            {
+                                indices.push(idx as u32);
+                            }
+                        }
+                    }
+                    if !indices.is_empty()
+                        && (indices.len() < total_algos as usize
+                            || settings.get_i64("tp_end_step").is_some()
+                            || settings.get_i64("end_step").is_some()
+                            || settings.get_i64("max_step").is_some())
+                    {
+                        algo_indices = Some(indices);
+                    }
+                }
+            } else if let Some(only_arr) = settings.get_arr("only_tests") {
+                if !only_arr.is_empty() {
+                    let raw_nums: Vec<i64> = only_arr
+                        .iter()
+                        .filter_map(|x| match x {
+                            JsonVal::Num(n) => Some(*n as i64),
+                            JsonVal::Str(s) => s.trim().split(':').next()?.parse::<i64>().ok(),
+                            _ => None,
+                        })
+                        .collect();
+                    let one_based = raw_nums.iter().all(|&n| (1..=24).contains(&n)) && !raw_nums.contains(&0);
+                    let mut indices = Vec::new();
+                    for n in raw_nums {
+                        let z = if one_based { n - 1 } else { n };
+                        if (0..=23).contains(&z)
+                            && (z as u32) <= max_algo_id
+                            && !indices.contains(&(z as u32))
+                        {
+                            indices.push(z as u32);
+                        }
+                    }
+                    if !indices.is_empty() {
+                        algo_indices = Some(indices);
+                    }
+                }
+            } else if let Some(skip_arr) = settings.get_arr("skip_tests") {
+                if !skip_arr.is_empty() {
+                    let raw_nums: Vec<i64> = skip_arr
+                        .iter()
+                        .filter_map(|x| match x {
+                            JsonVal::Num(n) => Some(*n as i64),
+                            JsonVal::Str(s) => s.trim().split(':').next()?.parse::<i64>().ok(),
+                            _ => None,
+                        })
+                        .collect();
+                    let one_based = raw_nums.iter().all(|&n| (1..=24).contains(&n)) && !raw_nums.contains(&0);
+                    let skip_set: BTreeSet<u32> = raw_nums
+                        .into_iter()
+                        .filter_map(|n| {
+                            let z = if one_based { n - 1 } else { n };
+                            if (0..=23).contains(&z) { Some(z as u32) } else { None }
+                        })
+                        .collect();
+                    let indices: Vec<u32> = (0..total_algos).filter(|i| !skip_set.contains(i)).collect();
+                    if !indices.is_empty() {
+                        algo_indices = Some(indices);
+                    }
+                }
+            }
+
+            if algo_indices.is_none()
+                && (settings.get_i64("tp_end_step").is_some()
+                    || settings.get_i64("end_step").is_some()
+                    || settings.get_i64("max_step").is_some())
+            {
+                algo_indices = Some((0..total_algos).collect());
+            }
+        }
+
+        if let Some(indices) = algo_indices {
+            let max_step = settings
+                .get_i64("tp_end_step")
+                .or_else(|| settings.get_i64("end_step"))
+                .or_else(|| settings.get_i64("max_step"))
+                .unwrap_or(255)
+                .clamp(0, 255) as u32;
+            let tp_val = indices
+                .into_iter()
+                .map(|idx| format_vd012_tp_entry_with_step(idx, max_step))
+                .collect::<Vec<_>>()
+                .join(" ");
+            seen.insert("tp".to_string());
+            cmds.push(format!("tp {}", tp_val));
+        }
+
+        if let Some(ovs) = settings.get_arr("overrides") {
+            for ov in ovs {
+                let name = ov
+                    .get_str_or("name", &ov.get_str_or("id", ""))
+                    .trim()
+                    .to_string();
+                if name.is_empty() {
+                    continue;
+                }
+                if !self.amt_allowed.contains(&name) {
+                    return Err(format!("未知或不可作为覆盖项的 AMT 命令: {}", name));
+                }
+                if !seen.insert(name.clone()) {
+                    return Err(format!("重复的 AMT 参数: {}", name));
+                }
+                let val = ov.get_str_or("value", "").trim().to_string();
+                if val.contains('\r') || val.contains('\n') || val.contains('\0') {
+                    return Err(format!("AMT 参数值必须为单行文本: {}", name));
+                }
+                if val.is_empty() && !matches!(name.as_str(), "show" | "tp") {
+                    return Err(format!("AMT 参数 {} 需要显式填写参数值", name));
+                }
+                if name == "tp" && !val.is_empty() {
+                    let normalized = normalize_tp_plan_str(&val, max_algo_id)?;
+                    cmds.push(format!("tp {}", normalized));
+                } else {
+                    cmds.push(format!("{} {}", name, val).trim().to_string());
+                }
+            }
+        }
+        if let Some(raws) = settings.get_arr("raw_commands") {
+            for r in raws {
+                if let Some(s) = r.as_str() {
+                    let t = s.trim();
+                    if !t.is_empty() {
+                        if t.contains('\r') || t.contains('\n') || t.contains('\0') {
+                            return Err("补充 AMT 命令必须为单行文本".to_string());
+                        }
+                        cmds.push(t.to_string());
+                    }
+                }
+            }
+        }
+        Ok(cmds)
+    }
+}
+
+pub fn format_vd012_tp_entry_with_step(algo_idx_zero_based: u32, end_step: u32) -> String {
+    let step = end_step.min(255);
+    if algo_idx_zero_based == 15 || algo_idx_zero_based == 20 {
+        // RowHammer (15: B-Hammer, 20: B-HammerSec) requires 10-field tp tuple
+        format!("{},1,0,{},0,255,0,0,0x1d4c00,8", algo_idx_zero_based, step)
+    } else {
+        format!("{},1,0,{},0,255", algo_idx_zero_based, step)
+    }
+}
+
+/// Validates a user-provided `tp` plan string AND auto-completes RowHammer (15/20) to 10 fields if given 6 fields!
+fn normalize_tp_plan_str(val: &str, max_algo_id: u32) -> Result<String, String> {
+    let entries: Vec<&str> = val.split_whitespace().collect();
+    if entries.len() > 256 {
+        return Err("AMT tp 计划项不能超过 256 组".to_string());
+    }
+    let mut out = Vec::with_capacity(entries.len());
+    for entry in entries {
+        let fields: Vec<&str> = entry.split(',').collect();
+        if fields.len() != 6 && fields.len() != 10 {
+            return Err(format!(
+                "AMT tp 项 '{}' 需要 6 个或 10 个逗号分隔字段 (algoid,loop,start,end,pat_table,pat_type[,ext0,ext1,hammer_cnt,bg_inter])",
+                entry
+            ));
+        }
+        let algo_id: u32 = fields[0]
+            .parse()
+            .map_err(|_| format!("AMT tp 算法编号必须是 0..23 的十进制整数: {}", fields[0]))?;
+        if algo_id > 23 {
+            return Err(format!("AMT tp 算法编号 {} 超出 0..23 范围", algo_id));
+        }
+        if algo_id > max_algo_id {
+            // Skip algos unsupported on 19-algo GNR-4.3.0 firmware if other entries remain
+            continue;
+        }
+        if (algo_id == 15 || algo_id == 20) && fields.len() == 6 {
+            out.push(format!("{},0,0,0x1d4c00,8", entry));
+        } else {
+            out.push(entry.to_string());
+        }
+    }
+    if out.is_empty() {
+        out.push("0,1,0,255,0,255".to_string());
+    }
+    Ok(out.join(" "))
+}

Разница между файлами не показана из-за своего большого размера
+ 1682 - 0
native/stl_accel/src/grpc.rs


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

@@ -0,0 +1,334 @@
+// json.rs — Zero-dependency JSON parser and serializer for stl_native_server
+
+use std::collections::BTreeMap;
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum JsonVal {
+    Null,
+    Bool(bool),
+    Num(f64),
+    Str(String),
+    Arr(Vec<JsonVal>),
+    Obj(BTreeMap<String, JsonVal>),
+}
+
+impl Default for JsonVal {
+    fn default() -> Self {
+        JsonVal::Null
+    }
+}
+
+impl JsonVal {
+    pub fn obj() -> Self {
+        JsonVal::Obj(BTreeMap::new())
+    }
+
+    pub fn set(&mut self, k: &str, v: JsonVal) {
+        if let JsonVal::Obj(ref mut m) = self {
+            m.insert(k.to_string(), v);
+        }
+    }
+
+    pub fn get(&self, k: &str) -> Option<&JsonVal> {
+        if let JsonVal::Obj(ref m) = self {
+            m.get(k)
+        } else {
+            None
+        }
+    }
+
+    pub fn get_str(&self, k: &str) -> Option<&str> {
+        match self.get(k) {
+            Some(JsonVal::Str(s)) => Some(s.as_str()),
+            _ => None,
+        }
+    }
+
+    pub fn get_str_or(&self, k: &str, default: &str) -> String {
+        self.get_str(k).unwrap_or(default).to_string()
+    }
+
+    pub fn get_bool(&self, k: &str) -> Option<bool> {
+        match self.get(k) {
+            Some(JsonVal::Bool(b)) => Some(*b),
+            _ => None,
+        }
+    }
+
+    pub fn get_f64(&self, k: &str) -> Option<f64> {
+        match self.get(k) {
+            Some(JsonVal::Num(n)) => Some(*n),
+            Some(JsonVal::Str(s)) => s.parse::<f64>().ok(),
+            _ => None,
+        }
+    }
+
+    pub fn get_i64(&self, k: &str) -> Option<i64> {
+        self.get_f64(k).map(|v| v as i64)
+    }
+
+    pub fn get_arr(&self, k: &str) -> Option<&Vec<JsonVal>> {
+        match self.get(k) {
+            Some(JsonVal::Arr(a)) => Some(a),
+            _ => None,
+        }
+    }
+
+    pub fn as_str(&self) -> Option<&str> {
+        if let JsonVal::Str(s) = self {
+            Some(s.as_str())
+        } else {
+            None
+        }
+    }
+
+    pub fn as_obj(&self) -> Option<&BTreeMap<String, JsonVal>> {
+        if let JsonVal::Obj(ref m) = self {
+            Some(m)
+        } else {
+            None
+        }
+    }
+
+    pub fn as_obj_mut(&mut self) -> Option<&mut BTreeMap<String, JsonVal>> {
+        if let JsonVal::Obj(ref mut m) = self {
+            Some(m)
+        } else {
+            None
+        }
+    }
+
+    pub fn parse(input: &str) -> Option<Self> {
+        parse_json(input).ok()
+    }
+
+    pub fn to_json(&self) -> String {
+        let mut out = String::with_capacity(256);
+        self.write_to(&mut out);
+        out
+    }
+
+    pub fn write_to(&self, out: &mut String) {
+        match self {
+            JsonVal::Null => out.push_str("null"),
+            JsonVal::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
+            JsonVal::Num(n) => {
+                if n.is_finite() {
+                    if n.fract() == 0.0 && n.abs() < 1e15 {
+                        out.push_str(&format!("{}", *n as i64));
+                    } else {
+                        out.push_str(&format!("{}", n));
+                    }
+                } else {
+                    out.push_str("0");
+                }
+            }
+            JsonVal::Str(s) => escape_json_into(s, out),
+            JsonVal::Arr(arr) => {
+                out.push('[');
+                for (i, item) in arr.iter().enumerate() {
+                    if i > 0 {
+                        out.push(',');
+                    }
+                    item.write_to(out);
+                }
+                out.push(']');
+            }
+            JsonVal::Obj(map) => {
+                out.push('{');
+                for (i, (k, v)) in map.iter().enumerate() {
+                    if i > 0 {
+                        out.push(',');
+                    }
+                    escape_json_into(k, out);
+                    out.push(':');
+                    v.write_to(out);
+                }
+                out.push('}');
+            }
+        }
+    }
+}
+
+pub fn escape_json_into(s: &str, out: &mut String) {
+    out.push('"');
+    for ch in s.chars() {
+        match ch {
+            '"' => out.push_str("\\\""),
+            '\\' => out.push_str("\\\\"),
+            '\n' => out.push_str("\\n"),
+            '\r' => out.push_str("\\r"),
+            '\t' => out.push_str("\\t"),
+            c if (c as u32) < 0x20 => {
+                out.push_str(&format!("\\u{:04x}", c as u32));
+            }
+            c => out.push(c),
+        }
+    }
+    out.push('"');
+}
+
+pub fn parse_json(input: &str) -> Result<JsonVal, String> {
+    let bytes = input.as_bytes();
+    let mut pos = 0;
+    let val = parse_value(bytes, &mut pos)?;
+    skip_ws(bytes, &mut pos);
+    Ok(val)
+}
+
+fn skip_ws(b: &[u8], pos: &mut usize) {
+    while *pos < b.len() && matches!(b[*pos], b' ' | b'\t' | b'\r' | b'\n') {
+        *pos += 1;
+    }
+}
+
+fn parse_value(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
+    skip_ws(b, pos);
+    if *pos >= b.len() {
+        return Err("Unexpected EOF".to_string());
+    }
+    match b[*pos] {
+        b'"' => parse_string(b, pos).map(JsonVal::Str),
+        b'{' => parse_object(b, pos),
+        b'[' => parse_array(b, pos),
+        b't' => {
+            if b.get(*pos..*pos + 4) == Some(b"true") {
+                *pos += 4;
+                Ok(JsonVal::Bool(true))
+            } else {
+                Err("Invalid token true".to_string())
+            }
+        }
+        b'f' => {
+            if b.get(*pos..*pos + 5) == Some(b"false") {
+                *pos += 5;
+                Ok(JsonVal::Bool(false))
+            } else {
+                Err("Invalid token false".to_string())
+            }
+        }
+        b'n' => {
+            if b.get(*pos..*pos + 4) == Some(b"null") {
+                *pos += 4;
+                Ok(JsonVal::Null)
+            } else {
+                Err("Invalid token null".to_string())
+            }
+        }
+        c if c == b'-' || c.is_ascii_digit() => parse_number(b, pos),
+        other => Err(format!("Unexpected byte '{}' at {}", other as char, *pos)),
+    }
+}
+
+fn parse_string(b: &[u8], pos: &mut usize) -> Result<String, String> {
+    if b.get(*pos) != Some(&b'"') {
+        return Err("Expected '\"'".to_string());
+    }
+    *pos += 1;
+    let mut out = String::new();
+    while *pos < b.len() {
+        let c = b[*pos];
+        if c == b'"' {
+            *pos += 1;
+            return Ok(out);
+        }
+        if c == b'\\' {
+            *pos += 1;
+            if *pos >= b.len() {
+                return Err("Unterminated escape".to_string());
+            }
+            match b[*pos] {
+                b'"' => { out.push('"'); *pos += 1; }
+                b'\\' => { out.push('\\'); *pos += 1; }
+                b'/' => { out.push('/'); *pos += 1; }
+                b'b' => { out.push('\u{0008}'); *pos += 1; }
+                b'f' => { out.push('\u{000c}'); *pos += 1; }
+                b'n' => { out.push('\n'); *pos += 1; }
+                b'r' => { out.push('\r'); *pos += 1; }
+                b't' => { out.push('\t'); *pos += 1; }
+                b'u' => {
+                    *pos += 1;
+                    if *pos + 4 > b.len() {
+                        return Err("Invalid \\u escape".to_string());
+                    }
+                    let hex_s = std::str::from_utf8(&b[*pos..*pos + 4]).map_err(|_| "Bad hex")?;
+                    let code = u32::from_str_radix(hex_s, 16).map_err(|_| "Bad hex")?;
+                    *pos += 4;
+                    if let Some(ch) = char::from_u32(code) {
+                        out.push(ch);
+                    }
+                }
+                other => {
+                    out.push(other as char);
+                    *pos += 1;
+                }
+            }
+        } else {
+            let s = std::str::from_utf8(&b[*pos..]).map_err(|_| "Invalid UTF-8")?;
+            let ch = s.chars().next().ok_or("EOF")?;
+            out.push(ch);
+            *pos += ch.len_utf8();
+        }
+    }
+    Err("Unterminated string".to_string())
+}
+
+fn parse_number(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
+    let start = *pos;
+    if b.get(*pos) == Some(&b'-') {
+        *pos += 1;
+    }
+    while *pos < b.len() && matches!(b[*pos], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
+        *pos += 1;
+    }
+    let s = std::str::from_utf8(&b[start..*pos]).map_err(|_| "Invalid number UTF-8")?;
+    let val = s.parse::<f64>().map_err(|_| format!("Invalid number: {}", s))?;
+    Ok(JsonVal::Num(val))
+}
+
+fn parse_array(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
+    *pos += 1; // skip '['
+    skip_ws(b, pos);
+    let mut arr = Vec::new();
+    if b.get(*pos) == Some(&b']') {
+        *pos += 1;
+        return Ok(JsonVal::Arr(arr));
+    }
+    loop {
+        let v = parse_value(b, pos)?;
+        arr.push(v);
+        skip_ws(b, pos);
+        match b.get(*pos) {
+            Some(b',') => { *pos += 1; }
+            Some(b']') => { *pos += 1; return Ok(JsonVal::Arr(arr)); }
+            _ => return Err("Expected ',' or ']' in array".to_string()),
+        }
+    }
+}
+
+fn parse_object(b: &[u8], pos: &mut usize) -> Result<JsonVal, String> {
+    *pos += 1; // skip '{'
+    skip_ws(b, pos);
+    let mut map = BTreeMap::new();
+    if b.get(*pos) == Some(&b'}') {
+        *pos += 1;
+        return Ok(JsonVal::Obj(map));
+    }
+    loop {
+        skip_ws(b, pos);
+        let key = parse_string(b, pos)?;
+        skip_ws(b, pos);
+        if b.get(*pos) != Some(&b':') {
+            return Err("Expected ':' in object".to_string());
+        }
+        *pos += 1;
+        let val = parse_value(b, pos)?;
+        map.insert(key, val);
+        skip_ws(b, pos);
+        match b.get(*pos) {
+            Some(b',') => { *pos += 1; }
+            Some(b'}') => { *pos += 1; return Ok(JsonVal::Obj(map)); }
+            _ => return Err("Expected ',' or '}' in object".to_string()),
+        }
+    }
+}

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

@@ -0,0 +1,677 @@
+// lib.rs — Native Hardware Dispatch, ASM Base64 & Single-Pass Clean/Split/Classify,
+//          Monotonic 64-Bit mmap Ring Buffer, re2c DFA, epoll/timerfd & OpenCL FFI (v0.8.1.18)
+
+use crate::json::JsonVal;
+
+pub const STL_TAG_BRACKET: u32 = 1 << 0;
+pub const STL_TAG_PROMPT: u32 = 1 << 1;
+pub const STL_TAG_ERR_HINT: u32 = 1 << 2;
+pub const STL_TAG_DIGIT: u32 = 1 << 3;
+pub const STL_TAG_COLON_EQ: u32 = 1 << 4;
+
+pub const STL_LK_NONE: u32 = 0;
+pub const STL_LK_ICT_BANNER_HOVSEE: u32 = 1;
+pub const STL_LK_ICT_BANNER_CXMT: u32 = 2;
+pub const STL_LK_ICT_START_STAGE1: u32 = 3;
+pub const STL_LK_ICT_START_STAGE2: u32 = 4;
+pub const STL_LK_ICT_ENTER_HINT: u32 = 5;
+pub const STL_LK_ICT_PROMPT: u32 = 6;
+pub const STL_LK_ICT_EXIT: u32 = 7;
+pub const STL_LK_MRC_START: u32 = 8;
+pub const STL_LK_MRC_DONE: u32 = 9;
+pub const STL_LK_DIMM_INVENTORY: u32 = 10;
+pub const STL_LK_RMT_START: u32 = 11;
+pub const STL_LK_RMT_ROW: u32 = 12;
+pub const STL_LK_RMT_STOP: u32 = 13;
+pub const STL_LK_TRAINING_ERROR: u32 = 14;
+pub const STL_LK_AMT_BANNER: u32 = 15;
+pub const STL_LK_AMT_PROMPT: u32 = 16;
+pub const STL_LK_AMT_PROGRESS: u32 = 17;
+pub const STL_LK_AMT_SUMMARY: u32 = 18;
+pub const STL_LK_AMT_ERROR: u32 = 19;
+pub const STL_LK_UEFI_BANNER: u32 = 20;
+pub const STL_LK_UEFI_PROMPT_ROOT: u32 = 21;
+pub const STL_LK_UEFI_PROMPT_EFI: u32 = 22;
+pub const STL_LK_PXE_BOOT: u32 = 23;
+pub const STL_LK_MT_BANNER: u32 = 24;
+pub const STL_LK_MT_PROGRESS: u32 = 25;
+pub const STL_LK_MT_ERROR: u32 = 26;
+pub const STL_LK_MT_PASS_COMPLETE: u32 = 27;
+pub const STL_LK_MT_FAIL_COMPLETE: u32 = 28;
+pub const STL_LK_INLINE_TEMP: u32 = 29;
+pub const STL_LK_BIOS_BOOT: u32 = 30;
+
+pub const EPOLL_CTL_ADD: i32 = 1;
+pub const EPOLL_CTL_DEL: i32 = 2;
+pub const EPOLL_CTL_MOD: i32 = 3;
+pub const EPOLLIN: u32 = 0x001;
+pub const EPOLLERR: u32 = 0x008;
+pub const EPOLLHUP: u32 = 0x010;
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct StlHwCaps {
+    pub isa_tier: u32,
+    pub has_sse42: u32,
+    pub has_avx2: u32,
+    pub has_bmi2: u32,
+    pub cpu_brand: [u8; 64],
+    pub tier_name: [u8; 32],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Default)]
+pub struct StlCleanLineSpan {
+    pub offset: u32,
+    pub len: u32,
+    pub tag_mask: u32,
+    pub first_nonws: u8,
+    pub term_kind: u8,
+    pub reserved: u16,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct StlCleanStreamState {
+    pub esc_state: u32,
+    pub csi_p1: u32,
+    pub csi_p2: u32,
+    pub csi_param_idx: u32,
+    pub cur_row: u32,
+    pub cur_col: u32,
+    pub prev_was_cr: u32,
+    pub half_len: u32,
+    pub tag_mask: u32,
+    pub first_nonws: u8,
+    pub csi_priv: u8,
+    pub pad0: u16,
+    pub half_buf: [u8; 1024],
+}
+
+impl Default for StlCleanStreamState {
+    fn default() -> Self {
+        Self {
+            esc_state: 0,
+            csi_p1: 0,
+            csi_p2: 0,
+            csi_param_idx: 0,
+            cur_row: 0,
+            cur_col: 0,
+            prev_was_cr: 0,
+            half_len: 0,
+            tag_mask: 0,
+            first_nonws: 0,
+            csi_priv: 0,
+            pad0: 0,
+            half_buf: [0u8; 1024],
+        }
+    }
+}
+
+#[repr(C)]
+pub struct StlCleanOutput {
+    pub clean_buf: *mut u8,
+    pub clean_cap: usize,
+    pub clean_written: usize,
+    pub spans: *mut StlCleanLineSpan,
+    pub spans_cap: usize,
+    pub spans_count: usize,
+    pub src_consumed: usize,
+}
+
+#[repr(C)]
+pub struct StlRingBufRaw {
+    pub buf: *mut u8,
+    pub cap: usize,
+    pub mask: usize,
+    pub mmap_total: usize,
+    pub base_offset: u64,
+    pub write_offset: u64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Default, Debug)]
+pub struct StlRe2cEvent {
+    pub kind: u32,
+    pub fw_family: u8,
+    pub cpu: i8,
+    pub channel: i8,
+    pub dimm: i8,
+    pub rank: i8,
+    pub bank: i8,
+    pub subkind: i8,
+    pub fs_index: u8,
+    pub val0: i32,
+    pub val1: i32,
+    pub val2: i32,
+    pub val3: i32,
+    pub addr: u64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct StlOpenClInfo {
+    pub available: i32,
+    pub zero_copy_llc: i32,
+    pub compute_units: u32,
+    pub break_even_bytes: u64,
+    pub device_name: [u8; 96],
+}
+
+extern "C" {
+    pub fn c_init_once_hw_dispatch();
+    pub fn c_get_hw_caps(out_caps: *mut StlHwCaps);
+    pub fn stl_force_isa_tier(tier: i32);
+    pub fn stl_base64_encode(src: *const u8, len: usize, dst: *mut u8) -> usize;
+
+    pub fn stl_clean_stream_init(state: *mut StlCleanStreamState);
+    pub fn stl_clean_stream_clear_halfline(state: *mut StlCleanStreamState);
+    pub fn stl_clean_split_classify(
+        state: *mut StlCleanStreamState,
+        src: *const u8,
+        src_len: usize,
+        out: *mut StlCleanOutput,
+    );
+
+    pub fn stl_ring_init(rb: *mut StlRingBufRaw, requested_cap: usize) -> i32;
+    pub fn stl_ring_destroy(rb: *mut StlRingBufRaw);
+    pub fn stl_ring_append(rb: *mut StlRingBufRaw, data: *const u8, len: usize) -> u64;
+    pub fn stl_ring_read(
+        rb: *const StlRingBufRaw,
+        req_offset: u64,
+        dst: *mut u8,
+        max_len: usize,
+        out_actual_start: *mut u64,
+        out_next_offset: *mut u64,
+    ) -> usize;
+    pub fn stl_ring_clear_monotonic(rb: *mut StlRingBufRaw);
+
+    pub fn stl_re2c_parse_line(
+        line: *const u8,
+        len: usize,
+        tag_mask: u32,
+        ev: *mut StlRe2cEvent,
+    );
+    pub fn stl_re2c_detect_halfline_prompt(
+        buf: *const u8,
+        len: usize,
+        ev: *mut StlRe2cEvent,
+    ) -> 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_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_crc16_ccitt_false(data_ptr: *const u8, len: usize) -> u16;
+
+    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_wait_tokens(
+        epfd: i32,
+        out_tokens: *mut u64,
+        out_events: *mut u32,
+        max_ev: i32,
+        timeout_ms: i32,
+    ) -> i32;
+    pub fn stl_timerfd_create_ms(initial_ms: u64, interval_ms: u64) -> i32;
+    pub fn stl_timerfd_arm_ms(tfd: i32, initial_ms: u64, interval_ms: u64) -> i32;
+    pub fn stl_timerfd_drain(tfd: i32);
+    pub fn stl_eventfd_create() -> i32;
+    pub fn stl_eventfd_notify(efd: i32);
+    pub fn stl_eventfd_drain(efd: i32);
+    pub fn stl_set_nonblocking_nodelay(fd: i32, is_tcp: i32) -> i32;
+    pub fn stl_ws_writev2(
+        fd: i32,
+        hdr: *const u8,
+        hdr_len: usize,
+        body: *const u8,
+        body_len: usize,
+    ) -> i64;
+    pub fn stl_pin_thread_to_core(core_index: i32);
+
+    pub fn c_pty_open_serial_115200(path: *const u8) -> i32;
+    pub fn c_open_tty_baud_raw(path: *const u8, baud: i32) -> i32;
+    pub fn c_pty_open_tcp_serial(host: *const u8, port: i32, timeout_ms: i32) -> i32;
+    pub fn c_pty_spawn_ssh_console(
+        host: *const u8,
+        port: i32,
+        user: *const u8,
+        password: *const u8,
+        known_hosts_path: *const u8,
+        out_master_fd: *mut i32,
+        out_child_pid: *mut i32,
+    ) -> i32;
+    pub fn c_pty_spawn_ipmi_sol(
+        host: *const u8,
+        user: *const u8,
+        password: *const u8,
+        out_master_fd: *mut i32,
+        out_child_pid: *mut i32,
+    ) -> i32;
+    pub fn c_spawn_persistent_ipmi_shell(
+        host: *const u8,
+        user: *const u8,
+        password: *const u8,
+        cipher_suite: i32,
+        out_stdin_fd: *mut i32,
+        out_stdout_fd: *mut i32,
+        out_child_pid: *mut i32,
+    ) -> i32;
+    pub fn c_pty_read_nonblock(master_fd: i32, buf: *mut u8, cap: usize) -> isize;
+    pub fn c_pty_write_bytes(master_fd: i32, buf: *const u8, len: usize) -> isize;
+    pub fn c_pty_is_alive(child_pid: i32) -> i32;
+    pub fn c_pty_close(master_fd: i32, child_pid: i32);
+
+    pub fn stl_opencl_query_info(out_info: *mut StlOpenClInfo);
+    pub fn stl_batch_rescan_logs(
+        buf_4k_aligned: *const u8,
+        len: usize,
+        out_line_offsets: *mut u32,
+        out_line_tags: *mut u8,
+        max_lines: usize,
+        used_gpu: *mut i32,
+    ) -> usize;
+    pub fn stl_batch_rmt_eye_reduce(
+        margins_in: *const f32,
+        station_count: usize,
+        eye_grid_out: *mut f32,
+        summary_out: *mut f32,
+        used_gpu: *mut i32,
+    ) -> i32;
+}
+
+/// Safe RAII wrapper around the monotonic 64-bit mmap ring buffer (Hugepage + 64B tail pad + PROT_NONE guard).
+pub struct MonotonicRingBuffer {
+    raw: StlRingBufRaw,
+}
+
+unsafe impl Send for MonotonicRingBuffer {}
+unsafe impl Sync for MonotonicRingBuffer {}
+
+impl MonotonicRingBuffer {
+    pub fn new(requested_cap: usize) -> Self {
+        let mut raw = StlRingBufRaw {
+            buf: std::ptr::null_mut(),
+            cap: 0,
+            mask: 0,
+            mmap_total: 0,
+            base_offset: 0,
+            write_offset: 0,
+        };
+        let rc = unsafe { stl_ring_init(&mut raw, requested_cap) };
+        assert_eq!(rc, 0, "stl_ring_init mmap failed");
+        Self { raw }
+    }
+
+    #[inline]
+    pub fn base_offset(&self) -> u64 {
+        self.raw.base_offset
+    }
+
+    #[inline]
+    pub fn write_offset(&self) -> u64 {
+        self.raw.write_offset
+    }
+
+    #[inline]
+    pub fn capacity(&self) -> usize {
+        self.raw.cap
+    }
+
+    #[inline]
+    pub fn append(&mut self, data: &[u8]) -> u64 {
+        if data.is_empty() {
+            return self.raw.write_offset;
+        }
+        unsafe { stl_ring_append(&mut self.raw, data.as_ptr(), data.len()) }
+    }
+
+    /// Reads `[actual_start .. next_offset)` into `dst`, returning `(bytes_copied, actual_start, next_offset)`.
+    /// Never regresses `next_offset` even if older data slid out of the window.
+    pub fn read_slice(&self, req_offset: u64, max_bytes: usize) -> (Vec<u8>, u64, u64) {
+        let cap = max_bytes.min(self.raw.cap).max(1);
+        let avail = if req_offset < self.raw.write_offset {
+            let eff_start = req_offset.max(self.raw.base_offset);
+            (self.raw.write_offset - eff_start) as usize
+        } else {
+            0
+        };
+        if avail == 0 || max_bytes == 0 {
+            let cur = self.raw.write_offset;
+            return (Vec::new(), cur, cur);
+        }
+        let alloc_len = avail.min(cap);
+        let mut dst = vec![0u8; alloc_len];
+        let mut actual_start = 0u64;
+        let mut next_offset = 0u64;
+        let n = unsafe {
+            stl_ring_read(
+                &self.raw,
+                req_offset,
+                dst.as_mut_ptr(),
+                alloc_len,
+                &mut actual_start,
+                &mut next_offset,
+            )
+        };
+        dst.truncate(n);
+        (dst, actual_start, next_offset)
+    }
+
+    #[inline]
+    pub fn read_from(&self, req_offset: u64, max_bytes: usize) -> (Vec<u8>, u64) {
+        let (v, _, next) = self.read_slice(req_offset, max_bytes);
+        (v, next)
+    }
+
+    pub fn clear_monotonic(&mut self) {
+        unsafe { stl_ring_clear_monotonic(&mut self.raw) };
+    }
+}
+
+impl Drop for MonotonicRingBuffer {
+    fn drop(&mut self) {
+        unsafe { stl_ring_destroy(&mut self.raw) };
+    }
+}
+
+/// Zero-allocation streaming cleaner + UEFI cursor folder + CR/LF/CRLF splitter + re2c feeder.
+pub struct NativeStreamCleaner {
+    pub state: StlCleanStreamState,
+    clean_scratch: Vec<u8>,
+    spans_scratch: Vec<StlCleanLineSpan>,
+}
+
+impl NativeStreamCleaner {
+    pub fn new() -> Self {
+        let mut state = StlCleanStreamState::default();
+        unsafe { stl_clean_stream_init(&mut state) };
+        Self {
+            state,
+            clean_scratch: vec![0u8; 131072],
+            spans_scratch: vec![StlCleanLineSpan::default(); 4096],
+        }
+    }
+
+    #[inline]
+    pub fn clear_halfline(&mut self) {
+        unsafe { stl_clean_stream_clear_halfline(&mut self.state) };
+    }
+
+    #[inline]
+    pub fn halfline_bytes(&self) -> &[u8] {
+        let n = (self.state.half_len as usize).min(1024);
+        &self.state.half_buf[..n]
+    }
+
+    /// Feeds raw serial bytes through the single-pass ASM kernel in slices until all `raw` bytes are consumed.
+    pub fn feed<F>(&mut self, raw: &[u8], mut on_batch: F)
+    where
+        F: FnMut(&[u8], &[StlCleanLineSpan]),
+    {
+        let mut pos = 0usize;
+        while pos < raw.len() {
+            let mut out = StlCleanOutput {
+                clean_buf: self.clean_scratch.as_mut_ptr(),
+                clean_cap: self.clean_scratch.len(),
+                clean_written: 0,
+                spans: self.spans_scratch.as_mut_ptr(),
+                spans_cap: self.spans_scratch.len(),
+                spans_count: 0,
+                src_consumed: 0,
+            };
+            let rem = &raw[pos..];
+            unsafe {
+                stl_clean_split_classify(&mut self.state, rem.as_ptr(), rem.len(), &mut out);
+            }
+            if out.clean_written > 0 || out.spans_count > 0 {
+                on_batch(
+                    &self.clean_scratch[..out.clean_written],
+                    &self.spans_scratch[..out.spans_count],
+                );
+            }
+            if out.src_consumed == 0 {
+                /* Safety progress guard if single span exceeded scratch */
+                pos += 1;
+            } else {
+                pos += out.src_consumed;
+            }
+        }
+    }
+
+    #[inline]
+    pub fn detect_live_prompt(&self) -> Option<StlRe2cEvent> {
+        let hl = self.halfline_bytes();
+        if hl.is_empty() {
+            return None;
+        }
+        let mut ev = StlRe2cEvent::default();
+        let ok = unsafe { stl_re2c_detect_halfline_prompt(hl.as_ptr(), hl.len(), &mut ev) };
+        if ok != 0 {
+            Some(ev)
+        } else {
+            None
+        }
+    }
+}
+
+#[inline]
+pub fn re2c_parse_line(line: &[u8], tag_mask: u32) -> StlRe2cEvent {
+    let mut ev = StlRe2cEvent::default();
+    unsafe {
+        stl_re2c_parse_line(line.as_ptr(), line.len(), tag_mask, &mut ev);
+    }
+    ev
+}
+
+pub fn init_hardware() {
+    unsafe {
+        c_init_once_hw_dispatch();
+    }
+}
+
+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 {
+    if raw.is_empty() {
+        return String::new();
+    }
+    let mut cleaner = NativeStreamCleaner::new();
+    let mut out_bytes = Vec::with_capacity(raw.len() + 16);
+    cleaner.feed(raw, |clean_chunk, _spans| {
+        out_bytes.extend_from_slice(clean_chunk);
+    });
+    let rem = cleaner.halfline_bytes();
+    if !rem.is_empty() {
+        out_bytes.extend_from_slice(rem);
+    }
+    String::from_utf8_lossy(&out_bytes).to_string()
+}
+
+/// Vectorized Base64 encoder using runtime-dispatched SSE2 / AVX2 hand-written assembly.
+pub fn b64_encode(data: &[u8]) -> String {
+    if data.is_empty() {
+        return String::new();
+    }
+    let cap = ((data.len() + 2) / 3) * 4 + 8;
+    let mut out = vec![0u8; cap];
+    let n = unsafe { stl_base64_encode(data.as_ptr(), data.len(), out.as_mut_ptr()) };
+    out.truncate(n);
+    // Base64 output is strictly ASCII
+    unsafe { String::from_utf8_unchecked(out) }
+}
+
+pub fn b64_decode(s: &str) -> Vec<u8> {
+    let trimmed = s.trim();
+    if trimmed.is_empty() {
+        return Vec::new();
+    }
+    let cap = trimmed.len() + 16;
+    let mut out = vec![0u8; cap];
+    let n = unsafe { zig_base64_decode(trimmed.as_ptr(), trimmed.len(), out.as_mut_ptr(), cap) };
+    out.truncate(n);
+    out
+}
+
+pub fn ws_accept_header(client_key: &str) -> String {
+    let mut out = [0u8; 32];
+    let n = unsafe { zig_ws_accept_key(client_key.as_ptr(), client_key.len(), out.as_mut_ptr()) };
+    String::from_utf8_lossy(&out[..n]).to_string()
+}
+
+#[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 {
+    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
+    String::from_utf8_lossy(&buf[..end]).trim().to_string()
+}
+
+pub fn hardware_status_json() -> JsonVal {
+    let mut caps: StlHwCaps = unsafe { std::mem::zeroed() };
+    let mut cl: StlOpenClInfo = unsafe { std::mem::zeroed() };
+    unsafe {
+        c_get_hw_caps(&mut caps);
+        stl_opencl_query_info(&mut cl);
+    }
+    let mut out = JsonVal::obj();
+    out.set("available", JsonVal::Bool(true));
+    out.set("isa_tier", JsonVal::Num(caps.isa_tier as f64));
+    out.set("tier_name", JsonVal::Str(cstr_to_string(&caps.tier_name)));
+    out.set("cpu_brand", JsonVal::Str(cstr_to_string(&caps.cpu_brand)));
+    out.set("has_sse42", JsonVal::Bool(caps.has_sse42 != 0));
+    out.set("has_avx2", JsonVal::Bool(caps.has_avx2 != 0));
+    out.set("has_bmi2", JsonVal::Bool(caps.has_bmi2 != 0));
+
+    let mut igpu = JsonVal::obj();
+    igpu.set("available", JsonVal::Bool(cl.available != 0));
+    igpu.set("zero_copy_llc", JsonVal::Bool(cl.zero_copy_llc != 0));
+    igpu.set("compute_units", JsonVal::Num(cl.compute_units as f64));
+    igpu.set("break_even_bytes", JsonVal::Num(cl.break_even_bytes as f64));
+    igpu.set("device_name", JsonVal::Str(cstr_to_string(&cl.device_name)));
+    out.set("opencl_igpu", igpu);
+    out
+}
+
+#[inline]
+pub fn close_fd(fd: i32) {
+    if fd >= 0 {
+        unsafe {
+            c_pty_close(fd, -1);
+        }
+    }
+}
+
+#[inline]
+pub fn detect_physical_cores() -> usize {
+    std::thread::available_parallelism()
+        .map(|n| n.get())
+        .unwrap_or(2)
+        .max(1)
+}
+
+/// Asynchronous/Batch log rescan using Gen7.5-Gen9.5 OpenCL 4KB-aligned zero-copy above break-even threshold,
+/// automatically falling back to CPU SIMD on Sandy Bridge or under 15W package TDP constraint.
+pub fn opencl_or_cpu_batch_rescan(bytes: &[u8]) -> [u64; 4] {
+    if bytes.is_empty() {
+        return [0, 0, 0, 0];
+    }
+    let max_lines = (bytes.len() / 16).clamp(64, 524_288);
+    let mut offsets = vec![0u32; max_lines];
+    let mut tags = vec![0u8; max_lines];
+    let mut used_gpu: i32 = 0;
+    let n_lines = unsafe {
+        stl_batch_rescan_logs(
+            bytes.as_ptr(),
+            bytes.len(),
+            offsets.as_mut_ptr(),
+            tags.as_mut_ptr(),
+            max_lines,
+            &mut used_gpu,
+        )
+    };
+    let mut err_cnt = 0u64;
+    let mut amt_cnt = 0u64;
+    let mut mt_cnt = 0u64;
+    for &t in tags.iter().take(n_lines.min(max_lines)) {
+        if (t & (STL_TAG_ERR_HINT as u8)) != 0 {
+            err_cnt += 1;
+        }
+        if (t & (STL_TAG_BRACKET as u8)) != 0 {
+            amt_cnt += 1;
+        }
+        if (t & (STL_TAG_DIGIT as u8)) != 0 {
+            mt_cnt += 1;
+        }
+    }
+    [err_cnt, amt_cnt, mt_cnt, n_lines as u64]
+}
+
+/// Multi-station RMT margin matrix reduction & eye-diagram interpolation (OpenCL iGPU above threshold, CPU fallback).
+pub fn opencl_or_cpu_reduce_rmt_margins(
+    margins_24x8: &[f32; 24 * 8],
+    station_count: usize,
+) -> (Vec<f32>, Vec<f32>) {
+    let sc = station_count.max(1);
+    let mut margins_in = vec![0.0f32; sc * 24 * 4];
+    let mut min_widths = vec![0.0f32; 24];
+    for ch in 0..24 {
+        let base8 = ch * 8;
+        let rx_lo = margins_24x8[base8];
+        let rx_hi = margins_24x8[base8 + 1];
+        let vref_lo = margins_24x8[base8 + 4];
+        let vref_hi = margins_24x8[base8 + 5];
+        margins_in[ch * 4] = rx_lo;
+        margins_in[ch * 4 + 1] = rx_hi;
+        margins_in[ch * 4 + 2] = vref_lo;
+        margins_in[ch * 4 + 3] = vref_hi;
+        min_widths[ch] = (rx_hi - rx_lo).abs().min((vref_hi - vref_lo).abs());
+    }
+    let mut eye_out = vec![0.0f32; sc * 24 * 256];
+    let mut summary_out = vec![0.0f32; sc * 4];
+    let mut used_gpu: i32 = 0;
+    unsafe {
+        stl_batch_rmt_eye_reduce(
+            margins_in.as_ptr(),
+            sc,
+            eye_out.as_mut_ptr(),
+            summary_out.as_mut_ptr(),
+            &mut used_gpu,
+        );
+    }
+    // Downsample channel 0's 16x16 eye grid to 8x8 compact preview (and keep full 24 min widths)
+    let mut eye_8x8 = Vec::with_capacity(64);
+    for r in 0..8 {
+        for c in 0..8 {
+            eye_8x8.push(eye_out[(r * 2) * 16 + (c * 2)]);
+        }
+    }
+    (min_widths, eye_8x8)
+}

Разница между файлами не показана из-за своего большого размера
+ 587 - 0
native/stl_accel/src/main.rs


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

@@ -0,0 +1,431 @@
+// pxe.rs — Three-variant 118.efi PXE & mt86.cfg manager with non-blocking .63 TFTP multi-candidate sync
+
+use crate::json::JsonVal;
+use crate::results::now_ms;
+use std::fs;
+use std::net::{SocketAddr, TcpStream};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::thread;
+use std::time::Duration;
+
+pub const DEFAULT_FORMAL_TSTLIST: &str = "0,1,2,3,4,5,6,7,8,9,10,11,12,13";
+
+pub const PXE_VARIANTS: [(&str, &str, &str, &str, &str); 3] = [
+    (
+        "118_orig.efi",
+        "1. 原始版 (118_orig.efi)",
+        "原始未改",
+        "EFI.zip 原始文件,不改任何字节(适用于标准 DHCP PXE 或本地 U 盘 / EFI 分区)。",
+        "59b3e40267a396cdf1ccb458a61a65844f891ccc3b9c08a545b38bc7600b2034",
+    ),
+    (
+        "118_serial.efi",
+        "2. 串口输出版 (118_serial.efi)",
+        "开启串口日志",
+        "开启 PXE 启动时的串口实时测试进度输出,网络协议获取保持原版。",
+        "bfcbbdf4a46899b70820254ac943c319106c1941329b92d4d4c93c58a865758e",
+    ),
+    (
+        "118_uip_stage1.efi",
+        "3. ICT Stage1 适配 + 串口版 (118_uip_stage1.efi)",
+        "推荐 · 自动拉配置+串口",
+        "适配主板 ICT Stage 1 静态 PXE,自动从 TFTP 拉取 mt86.cfg、实时输出串口进度并回传 HTML 报告。",
+        "8377daf9028c96fcc86abbdb7a4112868191fe6d8eb01e412f13929ff06bb382",
+    ),
+];
+
+pub const STAGE1_PXE_COMMANDS: [&str; 6] = [
+    "pxe umemdiag 118.efi",
+    "pxe umemdiagcfg mt86.cfg",
+    "pxe clientip 192.168.0.160",
+    "pxe subnetmaskip 255.255.255.0",
+    "pxe gatewayip 192.168.0.10",
+    "pxe serverip 192.168.0.10",
+];
+
+/// Local candidate filenames written alongside `mt86.cfg`
+pub const LOCAL_CFG_CANDIDATES: [&str; 6] = [
+    "mt86.cfg",
+    "Default string-mt86.cfg",
+    "118.cfg",
+    "memtest86.cfg",
+    "18-66-96-8a-f7-77-mt86.cfg",
+    "18-66-96-8a-f7-87-mt86.cfg",
+];
+
+fn probe_pxe_ssh(host: &str, timeout_ms: u64) -> bool {
+    let Ok(addr) = format!("{}:22", host.trim()).parse::<SocketAddr>() else {
+        return false;
+    };
+    TcpStream::connect_timeout(&addr, Duration::from_millis(timeout_ms)).is_ok()
+}
+
+pub fn default_pxe_state() -> JsonVal {
+    let mut cfg = JsonVal::obj();
+    cfg.set("tstlist", JsonVal::Str(DEFAULT_FORMAL_TSTLIST.to_string()));
+    cfg.set("numpass", JsonVal::Num(1.0));
+    cfg.set("cpusel", JsonVal::Str("PARALLEL".to_string()));
+    cfg.set("cpunum", JsonVal::Num(384.0));
+    cfg.set("maxcpus", JsonVal::Num(384.0));
+    cfg.set("disablemp", JsonVal::Num(0.0));
+    cfg.set("enableht", JsonVal::Num(1.0));
+    cfg.set("eccpoll", JsonVal::Num(1.0));
+    cfg.set("automode", JsonVal::Num(1.0));
+    cfg.set("exitmode", JsonVal::Num(2.0));
+    cfg.set("skipsplash", JsonVal::Num(1.0));
+
+    let mut st = JsonVal::obj();
+    st.set("active_variant", JsonVal::Str("118_serial.efi".to_string()));
+    st.set("stage1_pxe_enabled", JsonVal::Bool(false));
+    st.set("pxe_host", JsonVal::Str("192.168.2.63".to_string()));
+    st.set("pxe_server_ip", JsonVal::Str("192.168.0.10".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("mt86_cfg", cfg);
+    st.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
+    st
+}
+
+pub fn build_pxe_snapshot(pxe_state: &JsonVal) -> JsonVal {
+    let active_var = pxe_state.get_str_or("active_variant", "118_serial.efi");
+    let stage1_en = pxe_state.get_bool("stage1_pxe_enabled").unwrap_or(false);
+    let mut var_arr = Vec::new();
+    for (vid, label, badge, desc, sha) in PXE_VARIANTS {
+        let mut v = JsonVal::obj();
+        v.set("id", JsonVal::Str(vid.to_string()));
+        v.set("label", JsonVal::Str(label.to_string()));
+        v.set("badge", JsonVal::Str(badge.to_string()));
+        v.set("description", JsonVal::Str(desc.to_string()));
+        v.set("expected_sha256", JsonVal::Str(sha.to_string()));
+        v.set("sha256", JsonVal::Str(sha.to_string()));
+        v.set("active", JsonVal::Bool(vid == active_var));
+        var_arr.push(v);
+    }
+
+    let mut snap = JsonVal::obj();
+    snap.set("active_variant", JsonVal::Str(active_var.clone()));
+    snap.set(
+        "active_sha256",
+        JsonVal::Str(
+            PXE_VARIANTS
+                .iter()
+                .find(|x| x.0 == active_var)
+                .map(|x| x.4)
+                .unwrap_or(PXE_VARIANTS[0].4)
+                .to_string(),
+        ),
+    );
+    snap.set("stage1_pxe_enabled", JsonVal::Bool(stage1_en));
+    snap.set("pxe_host", JsonVal::Str(pxe_state.get_str_or("pxe_host", "192.168.2.63")));
+    snap.set("pxe_server_ip", JsonVal::Str(pxe_state.get_str_or("pxe_server_ip", "192.168.0.10")));
+    snap.set("pxe_client_ip", JsonVal::Str(pxe_state.get_str_or("pxe_client_ip", "192.168.0.160")));
+    snap.set("variants", JsonVal::Arr(var_arr));
+    if let Some(cfg) = pxe_state.get("mt86_cfg") {
+        snap.set("mt86_cfg", cfg.clone());
+    }
+    if let Some(note) = pxe_state.get_str("remote_sync_note") {
+        snap.set("remote_sync_note", JsonVal::Str(note.to_string()));
+    }
+    if let Some(ok) = pxe_state.get_bool("remote_synced") {
+        snap.set("remote_synced", JsonVal::Bool(ok));
+    }
+    snap.set("recent_reports", JsonVal::Arr(Vec::new()));
+    snap
+}
+
+fn parse_test_id_list(arr: &[JsonVal]) -> Vec<i64> {
+    let mut out = Vec::new();
+    for x in arr {
+        let parsed = match x {
+            JsonVal::Num(n) => Some(*n as i64),
+            JsonVal::Str(s) => {
+                let t = s.trim();
+                let digits: String = t
+                    .chars()
+                    .skip_while(|c| !c.is_ascii_digit())
+                    .take_while(|c| c.is_ascii_digit())
+                    .collect();
+                digits.parse::<i64>().ok()
+            }
+            _ => None,
+        };
+        if let Some(n) = parsed {
+            if (0..=13).contains(&n) && !out.contains(&n) {
+                out.push(n);
+            }
+        }
+    }
+    out
+}
+
+pub fn render_mt86_cfg_text(cfg: &JsonVal) -> String {
+    let fallback_tst = cfg.get_str_or("tstlist", DEFAULT_FORMAL_TSTLIST);
+    let tstlist = if let Some(only) = cfg.get_arr("only_tests") {
+        let nums = parse_test_id_list(only);
+        if nums.is_empty() {
+            fallback_tst
+        } else {
+            nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",")
+        }
+    } else if let Some(sel) = cfg.get_arr("selected") {
+        let nums = parse_test_id_list(sel);
+        if nums.is_empty() {
+            fallback_tst
+        } else {
+            nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",")
+        }
+    } else if let Some(algs) = cfg.get_arr("algorithms") {
+        let nums = parse_test_id_list(algs);
+        if nums.is_empty() {
+            fallback_tst
+        } else {
+            nums.iter().map(|n| n.to_string()).collect::<Vec<_>>().join(",")
+        }
+    } else if let Some(skip) = cfg.get_arr("skip_tests") {
+        let skip_set = parse_test_id_list(skip);
+        let nums: Vec<String> = (0..=13)
+            .filter(|n| !skip_set.contains(n))
+            .map(|n| n.to_string())
+            .collect();
+        if nums.is_empty() {
+            "0".to_string()
+        } else {
+            nums.join(",")
+        }
+    } else if fallback_tst.trim().is_empty() {
+        DEFAULT_FORMAL_TSTLIST.to_string()
+    } else {
+        fallback_tst
+    };
+
+    let numpass = cfg.get_i64("numpass").unwrap_or(1).clamp(1, 999);
+    let cpusel = cfg.get_str_or("cpusel", "PARALLEL");
+    let cpunum = cfg.get_i64("cpunum").unwrap_or(384).clamp(1, 1024);
+    let maxcpus = cfg.get_i64("maxcpus").unwrap_or(384).clamp(1, 1024);
+    let disablemp = cfg.get_i64("disablemp").unwrap_or(0).clamp(0, 1);
+    let enableht = cfg.get_i64("enableht").unwrap_or(1).clamp(0, 1);
+    let eccpoll = cfg
+        .get_i64("eccpoll")
+        .or_else(|| cfg.get_bool("ecc").map(|b| if b { 1 } else { 0 }))
+        .unwrap_or(1)
+        .clamp(0, 1);
+    let automode = cfg.get_i64("automode").unwrap_or(1).clamp(0, 2);
+    // Force EXITMODE default = 2 (return to UEFI Shell, do NOT power off host)
+    let exitmode = cfg
+        .get_i64("exitmode")
+        .or_else(|| cfg.get_i64("exit_mode"))
+        .unwrap_or(2)
+        .clamp(0, 3);
+    let skipsplash = cfg.get_i64("skipsplash").unwrap_or(1).clamp(0, 1);
+
+    let mut out = format!(
+        "TSTLIST={}\r\nNUMPASS={}\r\nCPUSEL={}\r\nCPUNUM={}\r\nMAXCPUS={}\r\nDISABLEMP={}\r\nENABLEHT={}\r\nECCPOLL={}\r\nAUTOMODE={}\r\nEXITMODE={}\r\nSKIPSPLASH={}\r\n",
+        tstlist, numpass, cpusel, cpunum, maxcpus, disablemp, enableht, eccpoll, automode, exitmode, skipsplash
+    );
+
+    if let Some(dbg) = cfg.get_i64("debuglog").or_else(|| cfg.get_bool("debuglog").map(|b| if b { 1 } else { 0 })) {
+        if dbg > 0 {
+            out.push_str(&format!("REPORTNUMWARN={}\r\n", dbg));
+        }
+    }
+
+    let lo = cfg
+        .get_str("addr_lim_lo")
+        .or_else(|| cfg.get_str("ADDRLIMLO"))
+        .or_else(|| cfg.get_str("addr_lo"))
+        .unwrap_or("")
+        .trim();
+    let hi = cfg
+        .get_str("addr_lim_hi")
+        .or_else(|| cfg.get_str("ADDRLIMHI"))
+        .or_else(|| cfg.get_str("addr_hi"))
+        .unwrap_or("")
+        .trim();
+    let mem_range = cfg.get_str_or("memory_range", "all");
+    if mem_range != "all" || !lo.is_empty() || !hi.is_empty() {
+        if !lo.is_empty() {
+            out.push_str(&format!("ADDRLIMLO={}\r\n", lo));
+        }
+        if !hi.is_empty() {
+            out.push_str(&format!("ADDRLIMHI={}\r\n", hi));
+        }
+    }
+    out
+}
+
+pub fn write_local_mt86_candidates(pxe_tftp_dir: &Path, cfg_text: &str) -> PathBuf {
+    let _ = fs::create_dir_all(pxe_tftp_dir);
+    let main_path = pxe_tftp_dir.join("mt86.cfg");
+    for cand in LOCAL_CFG_CANDIDATES {
+        let _ = fs::write(pxe_tftp_dir.join(cand), cfg_text.as_bytes());
+    }
+    if let Ok(entries) = fs::read_dir(pxe_tftp_dir) {
+        for entry in entries.flatten() {
+            let fname = entry.file_name().to_string_lossy().to_string();
+            if fname.ends_with("-mt86.cfg") {
+                let _ = fs::write(entry.path(), cfg_text.as_bytes());
+            }
+        }
+    }
+    main_path
+}
+
+pub fn sync_mt86_cfg_to_pxe_host(
+    pxe_host: &str,
+    cfg_path: &Path,
+    variant: &str,
+) -> (bool, String) {
+    if !cfg_path.is_file() {
+        return (false, "本地 mt86.cfg 不存在".to_string());
+    }
+    if let Some(parent) = cfg_path.parent() {
+        if let Ok(txt) = fs::read_to_string(cfg_path) {
+            write_local_mt86_candidates(parent, &txt);
+        }
+    }
+    if !probe_pxe_ssh(pxe_host, 250) {
+        return (false, format!("本地候选已全量写入(PXE 主机 {} 当前离线)", pxe_host));
+    }
+    let scp_ok = Command::new("sshpass")
+        .env("SSHPASS", "123456")
+        .args([
+            "-e",
+            "scp",
+            "-o",
+            "LogLevel=ERROR",
+            "-o",
+            "StrictHostKeyChecking=no",
+            "-o",
+            "UserKnownHostsFile=/dev/null",
+            "-o",
+            "ConnectTimeout=2",
+            &cfg_path.to_string_lossy(),
+            &format!("xjkj@{}:/opt/pxe-server/tftp/mt86.cfg", pxe_host),
+        ])
+        .status()
+        .map(|s| s.success())
+        .unwrap_or(false);
+
+    let remote_cmd = format!(
+        "for d in /opt/pxe-server/tftp /srv/tftp /var/lib/tftpboot; do \
+           if [ -d \"$d\" ]; then \
+             [ \"$d\" != \"/opt/pxe-server/tftp\" ] && cp -f /opt/pxe-server/tftp/mt86.cfg \"$d/mt86.cfg\" 2>/dev/null || true; \
+             cd \"$d\" && \
+             for f in 'Default string-mt86.cfg' 118.cfg memtest86.cfg \
+                      18-66-96-8a-f7-77-mt86.cfg 18-66-96-8A-F7-77-mt86.cfg \
+                      18-66-96-8a-f7-87-mt86.cfg 18-66-96-8A-F7-87-mt86.cfg \
+                      *-mt86.cfg *GB-mt86.cfg; do \
+               [ -e \"$f\" ] && cp -f mt86.cfg \"$f\" 2>/dev/null || true; \
+             done; \
+             cp -f mt86.cfg 'Default string-mt86.cfg' && \
+             cp -f mt86.cfg 118.cfg && \
+             cp -f mt86.cfg memtest86.cfg && \
+             if [ -f '{}' ]; then cp -f '{}' 118.efi; fi; \
+           fi; \
+         done",
+        variant, variant
+    );
+    let ssh_ok = Command::new("sshpass")
+        .env("SSHPASS", "123456")
+        .args([
+            "-e",
+            "ssh",
+            "-o",
+            "LogLevel=ERROR",
+            "-o",
+            "StrictHostKeyChecking=no",
+            "-o",
+            "UserKnownHostsFile=/dev/null",
+            "-o",
+            "ConnectTimeout=2",
+            &format!("xjkj@{}", pxe_host),
+            &remote_cmd,
+        ])
+        .status()
+        .map(|s| s.success())
+        .unwrap_or(false);
+
+    let note = if scp_ok && ssh_ok {
+        format!("已同步覆盖 {} 全部候选配置与 {}", pxe_host, variant)
+    } else {
+        format!("本地候选已保存(远端 {} 同步未完成)", pxe_host)
+    };
+    (scp_ok && ssh_ok, note)
+}
+
+/// Non-blocking fire-and-forget PXE sync so Station Actors never block on SSH/SCP
+pub fn sync_mt86_cfg_async(pxe_host: String, pxe_tftp_dir: PathBuf, cfg_text: String, variant: String) {
+    let cfg_path = write_local_mt86_candidates(&pxe_tftp_dir, &cfg_text);
+    let src_efi = pxe_tftp_dir.join(&variant);
+    let dst_efi = pxe_tftp_dir.join("118.efi");
+    if src_efi.is_file() {
+        let _ = fs::copy(&src_efi, &dst_efi);
+    }
+    thread::spawn(move || {
+        let _ = sync_mt86_cfg_to_pxe_host(&pxe_host, &cfg_path, &variant);
+    });
+}
+
+pub fn sync_mt86_cfg_all_candidates(
+    pxe_host: &str,
+    pxe_tftp_dir: &Path,
+    cfg_text: &str,
+    variant: &str,
+) {
+    sync_mt86_cfg_async(
+        pxe_host.to_string(),
+        pxe_tftp_dir.to_path_buf(),
+        cfg_text.to_string(),
+        variant.to_string(),
+    );
+}
+
+pub fn apply_pxe_configuration(
+    pxe_state: &mut JsonVal,
+    args: &JsonVal,
+    data_dir: &Path,
+    pxe_tftp_dir: &Path,
+) -> Result<JsonVal, String> {
+    let variant = args.get_str_or(
+        "variant",
+        &pxe_state.get_str_or("active_variant", "118_serial.efi"),
+    );
+    if !PXE_VARIANTS.iter().any(|x| x.0 == variant) {
+        return Err(format!("不支持的 118.efi 版本: {}", variant));
+    }
+    let stage1_en = args
+        .get_bool("stage1_pxe_enabled")
+        .unwrap_or_else(|| pxe_state.get_bool("stage1_pxe_enabled").unwrap_or(false));
+    pxe_state.set("active_variant", JsonVal::Str(variant.clone()));
+    pxe_state.set("stage1_pxe_enabled", JsonVal::Bool(stage1_en));
+    if let Some(h) = args.get_str("pxe_host") {
+        if !h.trim().is_empty() {
+            pxe_state.set("pxe_host", JsonVal::Str(h.trim().to_string()));
+        }
+    }
+    let cfg_obj = args
+        .get("mt86_cfg")
+        .cloned()
+        .or_else(|| pxe_state.get("mt86_cfg").cloned())
+        .unwrap_or_else(|| default_pxe_state().get("mt86_cfg").cloned().unwrap_or_else(JsonVal::obj));
+    pxe_state.set("mt86_cfg", cfg_obj.clone());
+
+    let cfg_text = render_mt86_cfg_text(&cfg_obj);
+    let cfg_path = write_local_mt86_candidates(pxe_tftp_dir, &cfg_text);
+    let src_efi = pxe_tftp_dir.join(&variant);
+    let dst_efi = pxe_tftp_dir.join("118.efi");
+    if src_efi.is_file() {
+        let _ = fs::copy(&src_efi, &dst_efi);
+    }
+
+    pxe_state.set("updated_unix_ms", JsonVal::Num(now_ms() as f64));
+    if args.get_bool("sync_remote").unwrap_or(true) {
+        let pxe_host = pxe_state.get_str_or("pxe_host", "192.168.2.63");
+        let (synced, note) = sync_mt86_cfg_to_pxe_host(&pxe_host, &cfg_path, &variant);
+        pxe_state.set("remote_synced", JsonVal::Bool(synced));
+        pxe_state.set("remote_sync_note", JsonVal::Str(note));
+    }
+    let _ = fs::write(data_dir.join("pxe_control_state.json"), pxe_state.to_json());
+    Ok(build_pxe_snapshot(pxe_state))
+}

Разница между файлами не показана из-за своего большого размера
+ 1734 - 0
native/stl_accel/src/results.rs


+ 422 - 0
native/stl_accel/src/storage.rs

@@ -0,0 +1,422 @@
+// storage.rs — Persistent station settings, PXE state, universal per-run archiver, and real-time audit log
+
+use crate::json::{parse_json, JsonVal};
+use crate::pxe::default_pxe_state;
+use crate::results::{now_ms, StationState};
+use std::collections::BTreeMap;
+use std::fs;
+use std::io::Write;
+use std::path::Path;
+
+const QT_CLEAN_PRIVATE_KEYS: &[&str] = &[
+    "password",
+    "passwd",
+    "secret",
+    "authorization",
+    "token",
+    "firmware_settings",
+    "boot_plan",
+    "boot_execution",
+    "raw_line",
+    "raw_sol",
+    "helper_argv",
+    "traceback",
+];
+
+pub fn strip_private_keys_recursive(val: &JsonVal) -> JsonVal {
+    match val {
+        JsonVal::Obj(entries) => {
+            let mut out = BTreeMap::new();
+            for (k, v) in entries {
+                let kl = k.to_ascii_lowercase();
+                if QT_CLEAN_PRIVATE_KEYS.contains(&kl.as_str())
+                    || kl.ends_with("_password")
+                    || kl.ends_with("_secret")
+                    || kl.ends_with("_token")
+                {
+                    continue;
+                }
+                out.insert(k.clone(), strip_private_keys_recursive(v));
+            }
+            JsonVal::Obj(out)
+        }
+        JsonVal::Arr(arr) => JsonVal::Arr(arr.iter().map(strip_private_keys_recursive).collect()),
+        other => other.clone(),
+    }
+}
+
+pub fn load_station_settings(data_dir: &Path, stations: &mut BTreeMap<String, StationState>) {
+    let dir = data_dir.join("station-controls");
+    let _ = fs::create_dir_all(&dir);
+    for (sid, st) in stations.iter_mut() {
+        let p = dir.join(format!("{}.json", sid));
+        let Ok(txt) = fs::read_to_string(&p) else {
+            continue;
+        };
+        let Ok(saved) = parse_json(&txt) else {
+            continue;
+        };
+        if let Some(conns) = saved.get("connections") {
+            if let Some(b) = conns.get("bmc") {
+                if let Some(en) = b.get_bool("enabled") {
+                    st.bmc_enabled = en;
+                }
+                let h = b.get_str_or("host", &st.bmc_host);
+                if !h.is_empty() {
+                    st.bmc_host = h;
+                }
+                let u = b.get_str_or("username", &b.get_str_or("user", &st.bmc_user));
+                if !u.is_empty() {
+                    st.bmc_user = u;
+                }
+                let pw = b.get_str_or("password", "");
+                if !pw.is_empty() {
+                    st.bmc_password = pw;
+                }
+                st.bmc_state = if st.bmc_enabled && !st.bmc_host.is_empty() {
+                    "online".to_string()
+                } else {
+                    "disabled".to_string()
+                };
+            }
+            if let Some(c) = conns.get("console") {
+                if let Some(en) = c.get_bool("enabled") {
+                    st.console_enabled = en;
+                }
+                let tr = c.get_str_or("transport", &st.console_transport);
+                if !tr.is_empty() {
+                    st.console_transport = tr;
+                }
+                let ch = c.get_str_or("host", "");
+                if !ch.is_empty() {
+                    st.console_host = ch;
+                } else if !st.bmc_host.is_empty() && st.console_transport != "tcp_serial" {
+                    st.console_host = st.bmc_host.clone();
+                }
+                if let Some(pt) = c.get_i64("port") {
+                    if pt > 0 {
+                        st.console_port = pt as i32;
+                    } else if st.console_transport == "ssh_console" {
+                        st.console_port = 2200;
+                    }
+                }
+                if let Some(wcb) = c.get_i64("write_chunk_bytes") {
+                    if wcb > 0 {
+                        st.write_chunk_bytes = wcb as usize;
+                    }
+                }
+                if let Some(wgm) = c.get_f64("write_gap_ms") {
+                    if wgm > 0.0 {
+                        st.write_gap_ms = wgm;
+                    }
+                }
+            }
+            if let Some(ch_cfg) = conns.get("chamber") {
+                let sp = ch_cfg.get_str_or("serial_path", "");
+                if !sp.is_empty() && !sp.contains("ttyUSB1") {
+                    st.chamber_serial_path = sp;
+                }
+                if let Some(tc) = ch_cfg.get_f64("target_c") {
+                    st.chamber_target_c = Some(tc);
+                }
+            }
+        }
+        if st.bmc_host == "192.168.2.165" || st.console_host == "192.168.2.165" {
+            st.hot.fw_family = 2;
+        }
+        if let Some(fw) = saved.get("firmware_settings") {
+            if let Some(ovs) = fw.get_arr("uip_overrides") {
+                st.uip_overrides = ovs.clone();
+            }
+            if let Some(raws) = fw.get_arr("uip_raw_commands") {
+                st.uip_raw_commands = raws
+                    .iter()
+                    .filter_map(|x| x.as_str().map(|s| s.to_string()))
+                    .collect();
+            }
+            if let Some(mt) = fw.get("mt_selection") {
+                st.mt_selection = mt.clone();
+            }
+        }
+        if let Some(amt) = saved.get("amt_settings") {
+            st.amt_settings = amt.clone();
+        }
+        if let Some(bp) = saved.get("boot_plan") {
+            st.boot_plan = bp.clone();
+        }
+        if let Some(tb) = saved.get("task_batch") {
+            st.task_batch = strip_private_keys_recursive(tb);
+        }
+        if let Some(th) = saved.get_arr("task_history") {
+            st.task_history = th.iter().map(strip_private_keys_recursive).collect();
+        }
+        if let Some(sp) = saved.get_arr("saved_profiles") {
+            st.saved_profiles = sp.clone();
+        }
+    }
+}
+
+pub fn save_station_settings(data_dir: &Path, st: &StationState) {
+    let dir = data_dir.join("station-controls");
+    let _ = fs::create_dir_all(&dir);
+    let mut fw = JsonVal::obj();
+    fw.set("uip_overrides", JsonVal::Arr(st.uip_overrides.clone()));
+    fw.set(
+        "uip_raw_commands",
+        JsonVal::Arr(
+            st.uip_raw_commands
+                .iter()
+                .map(|s| JsonVal::Str(s.clone()))
+                .collect(),
+        ),
+    );
+    fw.set("mt_selection", st.mt_selection.clone());
+
+    let mut conn_bmc = JsonVal::obj();
+    conn_bmc.set("enabled", JsonVal::Bool(st.bmc_enabled));
+    conn_bmc.set("host", JsonVal::Str(st.bmc_host.clone()));
+    conn_bmc.set("username", JsonVal::Str(st.bmc_user.clone()));
+    conn_bmc.set("user", JsonVal::Str(st.bmc_user.clone()));
+    conn_bmc.set("password", JsonVal::Str(st.bmc_password.clone()));
+
+    let mut conn_con = JsonVal::obj();
+    conn_con.set("enabled", JsonVal::Bool(st.console_enabled));
+    conn_con.set("transport", JsonVal::Str(st.console_transport.clone()));
+    conn_con.set("host", JsonVal::Str(st.console_host.clone()));
+    conn_con.set("port", JsonVal::Num(st.console_port as f64));
+    conn_con.set("write_chunk_bytes", JsonVal::Num(st.write_chunk_bytes as f64));
+    conn_con.set("write_gap_ms", JsonVal::Num(st.write_gap_ms));
+
+    let mut conn_chamber = JsonVal::obj();
+    conn_chamber.set("serial_path", JsonVal::Str(st.chamber_serial_path.clone()));
+    conn_chamber.set(
+        "target_c",
+        st.chamber_target_c.map(JsonVal::Num).unwrap_or(JsonVal::Null),
+    );
+
+    let mut conns = JsonVal::obj();
+    conns.set("bmc", conn_bmc);
+    conns.set("console", conn_con);
+    conns.set("chamber", conn_chamber);
+
+    let mut root = JsonVal::obj();
+    root.set("connections", conns);
+    root.set("firmware_settings", fw);
+    root.set("amt_settings", st.amt_settings.clone());
+    root.set("boot_plan", st.boot_plan.clone());
+    root.set("task_batch", st.task_batch.clone());
+    root.set("task_history", JsonVal::Arr(st.task_history.clone()));
+    root.set("saved_profiles", JsonVal::Arr(st.saved_profiles.clone()));
+    let p = dir.join(format!("{}.json", st.station_id));
+    let _ = fs::write(p, root.to_json());
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn archive_task_run(
+    data_dir: &Path,
+    st: &StationState,
+    run_id: &str,
+    batch_id: &str,
+    profile_index: usize,
+    profile_name: &str,
+    repeat_index: usize,
+    repeat_total: usize,
+    verdict: &str,
+    started_ms: i64,
+    ended_ms: i64,
+    profile_cfg: &JsonVal,
+) -> (String, String, JsonVal) {
+    let dir = data_dir
+        .join("task-runs")
+        .join(&st.station_id)
+        .join(if batch_id.is_empty() { "single" } else { batch_id })
+        .join(run_id);
+    let _ = fs::create_dir_all(&dir);
+
+    let base_off = st.raw_ring.base_offset();
+    let end_off = st.raw_ring.write_offset();
+    let start_off = st.active_run_start_offset.max(base_off).min(end_off);
+    let want_len = (end_off.saturating_sub(start_off) as usize).min(st.raw_ring.capacity());
+    let (raw_vec, _) = st.raw_ring.read_from(start_off, want_len);
+
+    let raw_path = dir.join("sol.raw");
+    let _ = fs::write(&raw_path, &raw_vec);
+
+    let clean_txt = crate::lib::clean_terminal_bytes(&raw_vec);
+    let clean_path = dir.join("sol.clean.log");
+    let _ = fs::write(&clean_path, clean_txt.as_bytes());
+
+    let mut rmt_arr = Vec::new();
+    for r in st.rmt_results.values() {
+        let mut o = JsonVal::obj();
+        o.set("cpu", JsonVal::Num(r.cpu as f64));
+        o.set("state", JsonVal::Str(r.state.clone()));
+        o.set("measurement_rows", JsonVal::Num(r.measurement_rows as f64));
+        o.set("min_dq_width", JsonVal::Num(r.min_dq_width as f64));
+        o.set("min_vref_width", JsonVal::Num(r.min_vref_width as f64));
+        rmt_arr.push(o);
+    }
+    let mut amt_arr = Vec::new();
+    for a in st.amt_results.values() {
+        let mut o = JsonVal::obj();
+        o.set("cpu", JsonVal::Num(a.cpu as f64));
+        o.set("status", JsonVal::Str(a.status.clone()));
+        o.set("algorithm_count", JsonVal::Num(a.algorithm_count as f64));
+        o.set("completed_count", JsonVal::Num(a.completed_count as f64));
+        o.set("evidence", JsonVal::Str(a.evidence.clone()));
+        amt_arr.push(o);
+    }
+    let mut stg_errs = JsonVal::obj();
+    for k in ["training", "rmt", "amt", "mt"] {
+        let arr = st.stage_errors.get(k).cloned().unwrap_or_default();
+        stg_errs.set(k, JsonVal::Arr(arr));
+    }
+
+    let mut disk_summary = JsonVal::obj();
+    disk_summary.set("run_id", JsonVal::Str(run_id.to_string()));
+    disk_summary.set("batch_id", JsonVal::Str(batch_id.to_string()));
+    disk_summary.set("station_id", JsonVal::Str(st.station_id.clone()));
+    disk_summary.set("boot_id", JsonVal::Str(st.boot_id.clone()));
+    disk_summary.set("firmware_family", JsonVal::Str(st.fw_family_name().to_string()));
+    disk_summary.set("profile_index", JsonVal::Num(profile_index as f64));
+    disk_summary.set("profile_name", JsonVal::Str(profile_name.to_string()));
+    disk_summary.set("repeat_index", JsonVal::Num(repeat_index as f64));
+    disk_summary.set("repeat_total", JsonVal::Num(repeat_total as f64));
+    disk_summary.set("verdict", JsonVal::Str(verdict.to_string()));
+    disk_summary.set("started_unix_ms", JsonVal::Str(started_ms.to_string()));
+    disk_summary.set("ended_unix_ms", JsonVal::Str(ended_ms.to_string()));
+    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_clean_path", JsonVal::Str(clean_path.to_string_lossy().to_string()));
+    disk_summary.set("stage_completions", st.stage_completions_json());
+    disk_summary.set("rmt_results", JsonVal::Arr(rmt_arr));
+    disk_summary.set("amt_results", JsonVal::Arr(amt_arr));
+    disk_summary.set("mt_result", st.mt_result.clone());
+    disk_summary.set("stage_errors", stg_errs);
+    disk_summary.set("profile_config", profile_cfg.clone());
+
+    let sum_path = dir.join("summary.json");
+    let _ = fs::write(&sum_path, disk_summary.to_json());
+
+    let state_summary = strip_private_keys_recursive(&disk_summary);
+    (
+        raw_path.to_string_lossy().to_string(),
+        sum_path.to_string_lossy().to_string(),
+        state_summary,
+    )
+}
+
+pub fn load_pxe_state(data_dir: &Path) -> JsonVal {
+    let p = data_dir.join("pxe_control_state.json");
+    if let Ok(txt) = fs::read_to_string(&p) {
+        if let Ok(val) = parse_json(&txt) {
+            return val;
+        }
+    }
+    let def = default_pxe_state();
+    let _ = fs::write(&p, def.to_json());
+    def
+}
+
+pub fn append_event(
+    events: &mut Vec<JsonVal>,
+    seq: &mut u64,
+    sid: &str,
+    kind: &str,
+    severity: &str,
+    message: &str,
+    phase: &str,
+) {
+    *seq += 1;
+    let mut ev = JsonVal::obj();
+    ev.set("sequence", JsonVal::Num(*seq as f64));
+    ev.set("station_id", JsonVal::Str(sid.to_string()));
+    ev.set("run_id", JsonVal::Str(String::new()));
+    ev.set("command_id", JsonVal::Str(String::new()));
+    ev.set("kind", JsonVal::Str(kind.to_string()));
+    ev.set("severity", JsonVal::Str(severity.to_string()));
+    ev.set("observed_unix_ms", JsonVal::Num(now_ms() as f64));
+    ev.set("message", JsonVal::Str(message.to_string()));
+    ev.set("phase", JsonVal::Str(phase.to_string()));
+    events.push(ev);
+    if events.len() > 300 {
+        events.drain(0..100);
+    }
+}
+
+pub fn load_audit_logs(data_dir: &Path) -> (Vec<JsonVal>, u64) {
+    let p = data_dir.join("config_audit.jsonl");
+    let Ok(txt) = fs::read_to_string(&p) else {
+        return (Vec::new(), 0);
+    };
+    let mut items = Vec::new();
+    let mut max_seq: u64 = 0;
+    for line in txt.lines() {
+        let trimmed = line.trim();
+        if trimmed.is_empty() {
+            continue;
+        }
+        if let Ok(val) = parse_json(trimmed) {
+            if let Some(s) = val.get_i64("sequence") {
+                if s as u64 > max_seq {
+                    max_seq = s as u64;
+                }
+            }
+            items.push(val);
+        }
+    }
+    if items.len() > 500 {
+        let drop_n = items.len() - 500;
+        items.drain(0..drop_n);
+    }
+    (items, max_seq)
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn record_audit_log(
+    data_dir: &Path,
+    audit_items: &mut Vec<JsonVal>,
+    audit_seq: &mut u64,
+    events: &mut Vec<JsonVal>,
+    event_seq: &mut u64,
+    sid: &str,
+    operator: &str,
+    category: &str,
+    action: &str,
+    summary: &str,
+    details: JsonVal,
+) -> JsonVal {
+    *audit_seq += 1;
+    let now = now_ms();
+    let mut rec = JsonVal::obj();
+    rec.set("sequence", JsonVal::Num(*audit_seq as f64));
+    rec.set("timestamp_unix_ms", JsonVal::Num(now as f64));
+    rec.set("timestamp_str", JsonVal::Str(now.to_string()));
+    rec.set("station_id", JsonVal::Str(sid.to_string()));
+    rec.set("operator", JsonVal::Str(operator.to_string()));
+    rec.set("category", JsonVal::Str(category.to_string()));
+    rec.set("action", JsonVal::Str(action.to_string()));
+    rec.set("summary", JsonVal::Str(summary.to_string()));
+    rec.set("details", details);
+
+    let line = format!("{}\n", rec.to_json());
+    let p = data_dir.join("config_audit.jsonl");
+    if let Ok(mut f) = fs::OpenOptions::new().create(true).append(true).open(&p) {
+        let _ = f.write_all(line.as_bytes());
+        let _ = f.flush();
+    }
+    audit_items.push(rec.clone());
+    if audit_items.len() > 500 {
+        audit_items.drain(0..100);
+    }
+    append_event(
+        events,
+        event_seq,
+        sid,
+        &format!("audit_{}", action),
+        "info",
+        &format!("[审计 · {}] {}", operator, summary),
+        category,
+    );
+    rec
+}

Разница между файлами не показана из-за своего большого размера
+ 1527 - 0
native/stl_accel/src/workflow.rs


+ 227 - 0
native/stl_accel/stl_accel.h

@@ -0,0 +1,227 @@
+#ifndef STL_ACCEL_H
+#define STL_ACCEL_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* =========================================================================
+ * 1. ISA Tiers & Runtime CPUID / XGETBV Dispatch
+ * ========================================================================= */
+#define STL_ISA_SSE2         0
+#define STL_ISA_SSE42_POPCNT 1
+#define STL_ISA_AVX2_BMI     2
+
+int         stl_cpu_tier_detect(void);
+int         stl_active_isa_tier(void);
+void        stl_force_isa_tier(int tier); /* -1 restores auto-detected tier */
+const char *stl_isa_tier_name(int tier);
+
+/* Assembly entry points (scan_asm.S) */
+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_avx2(const uint8_t *src, size_t len, uint8_t *dst);
+
+/* Dispatched Base64 encoder */
+size_t stl_base64_encode(const uint8_t *src, size_t len, uint8_t *dst);
+
+/* =========================================================================
+ * 2. Single-Pass Zero-Allocation Serial Clean + UEFI Fold + Split + Classify
+ * ========================================================================= */
+#define STL_TAG_BRACKET   (1u << 0) /* '[' banner / stage / tag */
+#define STL_TAG_PROMPT    (1u << 1) /* '>' or '#' prompt candidate */
+#define STL_TAG_ERR_HINT  (1u << 2) /* 'E','F','W','U' error/warning hint */
+#define STL_TAG_DIGIT     (1u << 3) /* '0'..'9' numeric / coord / progress */
+#define STL_TAG_COLON_EQ  (1u << 4) /* ':' or '=' key-value / table row */
+
+#define STL_HALF_LINE_CAP 1024
+
+typedef struct {
+    uint32_t offset;
+    uint32_t len;
+    uint32_t tag_mask;
+    uint8_t  first_nonws;
+    uint8_t  term_kind; /* 1=LF, 2=CR, 4=ROW_JUMP, 5=WRAP */
+    uint16_t reserved;
+} StlCleanLineSpan;
+
+typedef struct {
+    uint32_t esc_state;
+    uint32_t csi_p1;
+    uint32_t csi_p2;
+    uint32_t csi_param_idx;
+    uint32_t cur_row;
+    uint32_t cur_col;
+    uint32_t prev_was_cr;
+    uint32_t half_len;
+    uint32_t tag_mask;
+    uint8_t  first_nonws;
+    uint8_t  csi_priv;
+    uint16_t pad0;
+    uint8_t  half_buf[STL_HALF_LINE_CAP];
+} StlCleanStreamState;
+
+typedef struct {
+    uint8_t          *clean_buf;
+    size_t            clean_cap;
+    size_t            clean_written;
+    StlCleanLineSpan *spans;
+    size_t            spans_cap;
+    size_t            spans_count;
+    size_t            src_consumed;
+} StlCleanOutput;
+
+_Static_assert(sizeof(StlCleanLineSpan) == 16, "StlCleanLineSpan must be 16 bytes");
+_Static_assert(offsetof(StlCleanStreamState, half_buf) == 40, "half_buf must be at offset 40");
+_Static_assert(sizeof(StlCleanOutput) == 56, "StlCleanOutput must be 56 bytes");
+
+void asm_clean_split_classify_sse2(
+    StlCleanStreamState *state, const uint8_t *src, size_t src_len, StlCleanOutput *out);
+void asm_clean_split_classify_sse42(
+    StlCleanStreamState *state, const uint8_t *src, size_t src_len, StlCleanOutput *out);
+void asm_clean_split_classify_avx2(
+    StlCleanStreamState *state, const uint8_t *src, size_t src_len, StlCleanOutput *out);
+
+void stl_clean_stream_init(StlCleanStreamState *state);
+void stl_clean_stream_clear_halfline(StlCleanStreamState *state);
+void stl_clean_split_classify(
+    StlCleanStreamState *state, const uint8_t *src, size_t src_len, StlCleanOutput *out);
+
+/* =========================================================================
+ * 3. Monotonic 64-Bit mmap Ring Buffer (Hugepage + 64B Tail Pad + Guard Page)
+ * ========================================================================= */
+typedef struct {
+    uint8_t *buf;          /* mmap base: [0..cap) ring, [cap..cap+64) zero pad, then PROT_NONE */
+    size_t   cap;          /* power-of-two capacity (default 8 MiB) */
+    size_t   mask;         /* cap - 1 */
+    size_t   mmap_total;   /* total mmap length including guard page */
+    uint64_t base_offset;  /* oldest retained absolute byte offset (monotonic, never decreases) */
+    uint64_t write_offset; /* next write absolute byte offset (monotonic, never decreases) */
+} StlRingBuf;
+
+int      stl_ring_init(StlRingBuf *rb, size_t requested_cap);
+void     stl_ring_destroy(StlRingBuf *rb);
+uint64_t stl_ring_append(StlRingBuf *rb, const uint8_t *data, size_t len);
+size_t   stl_ring_read(
+    const StlRingBuf *rb,
+    uint64_t          req_offset,
+    uint8_t          *dst,
+    size_t            max_len,
+    uint64_t         *out_actual_start,
+    uint64_t         *out_next_offset);
+void     stl_ring_clear_monotonic(StlRingBuf *rb);
+
+/* =========================================================================
+ * 4. Deterministic re2c Line Lexer (parser_re2c.re -> parser_re2c.c)
+ * ========================================================================= */
+typedef enum {
+    STL_LK_NONE               = 0,
+    STL_LK_ICT_BANNER_HOVSEE  = 1,
+    STL_LK_ICT_BANNER_CXMT    = 2,
+    STL_LK_ICT_START_STAGE1   = 3,
+    STL_LK_ICT_START_STAGE2   = 4,
+    STL_LK_ICT_ENTER_HINT     = 5,
+    STL_LK_ICT_PROMPT         = 6,
+    STL_LK_ICT_EXIT           = 7,
+    STL_LK_MRC_START          = 8,
+    STL_LK_MRC_DONE           = 9,
+    STL_LK_DIMM_INVENTORY     = 10,
+    STL_LK_RMT_START          = 11,
+    STL_LK_RMT_ROW            = 12,
+    STL_LK_RMT_STOP           = 13,
+    STL_LK_TRAINING_ERROR     = 14,
+    STL_LK_AMT_BANNER         = 15,
+    STL_LK_AMT_PROMPT         = 16,
+    STL_LK_AMT_PROGRESS       = 17,
+    STL_LK_AMT_SUMMARY        = 18,
+    STL_LK_AMT_ERROR          = 19,
+    STL_LK_UEFI_BANNER        = 20,
+    STL_LK_UEFI_PROMPT_ROOT   = 21,
+    STL_LK_UEFI_PROMPT_EFI    = 22,
+    STL_LK_PXE_BOOT           = 23,
+    STL_LK_MT_BANNER          = 24,
+    STL_LK_MT_PROGRESS        = 25,
+    STL_LK_MT_ERROR           = 26,
+    STL_LK_MT_PASS_COMPLETE   = 27,
+    STL_LK_MT_FAIL_COMPLETE   = 28,
+    STL_LK_INLINE_TEMP        = 29,
+    STL_LK_BIOS_BOOT          = 30
+} StlLineKind;
+
+typedef struct {
+    uint32_t kind;        /* StlLineKind */
+    uint8_t  fw_family;   /* 0=unknown, 1=Hovsee/GNR-4.3.3(24-algo), 2=CxmtDdrTest/GNR-4.3.0(19-algo) */
+    int8_t   cpu;         /* -1 if unspecified, 0 or 1 */
+    int8_t   channel;     /* -1 if unspecified, 0..11 */
+    int8_t   dimm;        /* -1 if unspecified, 0..1 */
+    int8_t   rank;        /* -1 if unspecified, 0..3 */
+    int8_t   bank;        /* -1 if unspecified, validated 0..31 (never >= 32!) */
+    int8_t   subkind;     /* 0=normal, 1=pass, 2=fail, 3=disabled, 4=present, 5=coord_cont */
+    uint8_t  fs_index;    /* 0..9 for FSx:\ prompt */
+    int32_t  val0;        /* algo_id / progress_pct / margin_rx_lo / error_cnt */
+    int32_t  val1;        /* loop_or_total / margin_rx_hi */
+    int32_t  val2;        /* step / margin_tx_lo */
+    int32_t  val3;        /* margin_tx_hi / temp_c_x10 */
+    uint64_t addr;        /* parsed hex address if present */
+} StlRe2cEvent;
+
+_Static_assert(sizeof(StlRe2cEvent) == 40, "StlRe2cEvent must be 40 bytes");
+
+void stl_re2c_parse_line(const uint8_t *line, size_t len, uint32_t tag_mask, StlRe2cEvent *ev);
+int  stl_re2c_detect_halfline_prompt(const uint8_t *buf, size_t len, StlRe2cEvent *ev);
+
+/* =========================================================================
+ * 5. Linux epoll / timerfd / eventfd / Non-Blocking Serial & Socket Helpers
+ * ========================================================================= */
+int     stl_epoll_create(void);
+int     stl_epoll_ctl_fd(int epfd, int op, int fd, uint32_t events, uint64_t token);
+int     stl_epoll_wait_tokens(
+    int epfd, uint64_t *out_tokens, uint32_t *out_events, int max_ev, int timeout_ms);
+int     stl_timerfd_create_ms(uint64_t initial_ms, uint64_t interval_ms);
+int     stl_timerfd_arm_ms(int tfd, uint64_t initial_ms, uint64_t interval_ms);
+void    stl_timerfd_drain(int tfd);
+int     stl_eventfd_create(void);
+void    stl_eventfd_notify(int efd);
+void    stl_eventfd_drain(int efd);
+int     stl_set_nonblocking_nodelay(int fd, int is_tcp);
+int     stl_open_tty_115200_raw(const char *path);
+int64_t stl_ws_writev2(int fd, const uint8_t *hdr, size_t hdr_len, const uint8_t *body, size_t body_len);
+void    stl_pin_thread_to_core(int core_index);
+
+/* =========================================================================
+ * 6. OpenCL Gen7.5-Gen9.5 Zero-Copy Batch Offload (Auto CPU Fallback)
+ * ========================================================================= */
+typedef struct {
+    int      available;        /* 1 if Intel/OpenCL iGPU initialized */
+    int      zero_copy_llc;    /* 1 if unified memory CL_MEM_USE_HOST_PTR supported */
+    uint32_t compute_units;
+    uint64_t break_even_bytes; /* S* threshold (default 262144 = 256 KiB) */
+    char     device_name[96];
+} StlOpenClInfo;
+
+void   stl_opencl_query_info(StlOpenClInfo *out_info);
+int    stl_opencl_has_tdp_headroom(void);
+/* Batch historical log newline/error-marker pre-index; auto-falls back to CPU SIMD below S* or low TDP */
+size_t stl_batch_rescan_logs(
+    const uint8_t *buf_4k_aligned,
+    size_t         len,
+    uint32_t      *out_line_offsets,
+    uint8_t       *out_line_tags,
+    size_t         max_lines,
+    int           *used_gpu);
+/* Multi-station RMT margin matrix min/max/mean & 16x16 eye-diagram bilinear interpolation */
+int    stl_batch_rmt_eye_reduce(
+    const float *margins_in, /* [station_count * 24 * 4] (rx_lo, rx_hi, tx_lo, tx_hi) */
+    size_t       station_count,
+    float       *eye_grid_out, /* [station_count * 24 * 256] (16x16 normalized eye surface) */
+    float       *summary_out,  /* [station_count * 4] (min_timing, min_vref, mean_timing, mean_vref) */
+    int         *used_gpu);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* STL_ACCEL_H */

+ 344 - 0
native/stl_accel/zig_kernels.zig

@@ -0,0 +1,344 @@
+// zig_kernels.zig — Pure x86-64 SSE2 SIMD Kernels (v0.8.1.18)
+// 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).
+
+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)
+pub export fn zig_ws_accept_key(
+    key_ptr: [*]const u8,
+    key_len: usize,
+    out_ptr: [*]u8,
+) callconv(.c) usize {
+    const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+    var sha1 = std.crypto.hash.Sha1.init(.{});
+    sha1.update(key_ptr[0..key_len]);
+    sha1.update(magic);
+    var digest: [20]u8 = undefined;
+    sha1.final(&digest);
+    const encoded = std.base64.standard.Encoder.encode(out_ptr[0..28], &digest);
+    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(
+    src_ptr: [*]const u8,
+    src_len: usize,
+    dst_ptr: [*]u8,
+    dst_cap: usize,
+) callconv(.c) usize {
+    const max_len = std.base64.standard.Decoder.calcSizeForSlice(src_ptr[0..src_len]) catch return 0;
+    if (max_len > dst_cap) return 0;
+    std.base64.standard.Decoder.decode(dst_ptr[0..max_len], src_ptr[0..src_len]) catch return 0;
+    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
+pub export fn zig_batch_rescan_logs_cpu(
+    buf_ptr: [*]const u8,
+    len: usize,
+    out_offsets: [*]u32,
+    out_tags: [*]u8,
+    max_lines: usize,
+) callconv(.c) usize {
+    if (max_lines == 0 or len == 0) return 0;
+    const Vec16 = @Vector(16, u8);
+    const v_lf: Vec16 = @splat('\n');
+    const v_cr: Vec16 = @splat('\r');
+    const v_br: Vec16 = @splat('[');
+    const v_gt: Vec16 = @splat('>');
+    const v_hash: Vec16 = @splat('#');
+    const v_E: Vec16 = @splat('E');
+    const v_F: Vec16 = @splat('F');
+    const v_W: Vec16 = @splat('W');
+    const v_U: Vec16 = @splat('U');
+
+    var line_count: usize = 0;
+    var line_start: usize = 0;
+    var cur_tag: u8 = 0;
+    var prev_cr: bool = false;
+    var i: usize = 0;
+
+    while (i < len and line_count < max_lines) {
+        while (!prev_cr and i + 16 <= len) {
+            const chunk: Vec16 = buf_ptr[i..][0..16].*;
+            const m_lf = @as(u16, @bitCast(chunk == v_lf));
+            const m_cr = @as(u16, @bitCast(chunk == v_cr));
+            if ((m_lf | m_cr) != 0) break;
+            if (@as(u16, @bitCast(chunk == v_br)) != 0) cur_tag |= 1;
+            if ((@as(u16, @bitCast(chunk == v_gt)) | @as(u16, @bitCast(chunk == v_hash))) != 0) cur_tag |= 2;
+            if ((@as(u16, @bitCast(chunk == v_E)) | @as(u16, @bitCast(chunk == v_F)) |
+                @as(u16, @bitCast(chunk == v_W)) | @as(u16, @bitCast(chunk == v_U))) != 0) cur_tag |= 4;
+            i += 16;
+        }
+        if (i >= len) break;
+        const c = buf_ptr[i];
+        if (c == '\n') {
+            if (prev_cr) {
+                prev_cr = false;
+                line_start = i + 1;
+                i += 1;
+                continue;
+            }
+            if (i > line_start) {
+                out_offsets[line_count] = @intCast(line_start);
+                out_tags[line_count] = cur_tag;
+                line_count += 1;
+            }
+            cur_tag = 0;
+            line_start = i + 1;
+        } else if (c == '\r') {
+            if (i > line_start) {
+                out_offsets[line_count] = @intCast(line_start);
+                out_tags[line_count] = cur_tag;
+                line_count += 1;
+            }
+            cur_tag = 0;
+            prev_cr = true;
+            line_start = i + 1;
+        } else {
+            prev_cr = false;
+            if (c == '[') cur_tag |= 1;
+            if (c == '>' or c == '#') cur_tag |= 2;
+            if (c == 'E' or c == 'F' or c == 'W' or c == 'U') cur_tag |= 4;
+        }
+        i += 1;
+    }
+    if (line_start < len and line_count < max_lines) {
+        out_offsets[line_count] = @intCast(line_start);
+        out_tags[line_count] = cur_tag;
+        line_count += 1;
+    }
+    return line_count;
+}
+
+// 5. SSE2 4-wide Float Multi-Station RMT Margin Matrix Reduction & 16x16 Eye Interpolation
+pub export fn zig_rmt_eye_reduce_cpu(
+    margins_in: [*]const f32,
+    station_count: usize,
+    eye_grid_out: [*]f32,
+    summary_out: [*]f32,
+) callconv(.c) void {
+    const Vec4f = @Vector(4, f32);
+    var st: usize = 0;
+    while (st < station_count) : (st += 1) {
+        var min_timing: f32 = 999.0;
+        var min_vref: f32 = 999.0;
+        var sum_timing: f32 = 0.0;
+        var sum_vref: f32 = 0.0;
+        var active_ch: f32 = 0.0;
+
+        var ch: usize = 0;
+        while (ch < 24) : (ch += 1) {
+            const base_in = (st * 24 + ch) * 4;
+            const rx_lo = @abs(margins_in[base_in + 0]);
+            const rx_hi = @abs(margins_in[base_in + 1]);
+            const tx_lo = @abs(margins_in[base_in + 2]);
+            const tx_hi = @abs(margins_in[base_in + 3]);
+
+            const timing_span = rx_lo + rx_hi;
+            const vref_span = tx_lo + tx_hi;
+            if (timing_span > 0.0 or vref_span > 0.0) {
+                if (timing_span < min_timing) min_timing = timing_span;
+                if (vref_span < min_vref) min_vref = vref_span;
+                sum_timing += timing_span;
+                sum_vref += vref_span;
+                active_ch += 1.0;
+            }
+
+            // 16x16 normalized diamond/elliptical eye opening interpolation using 4-wide SSE2
+            const half_t = @max((rx_lo + rx_hi) * 0.5, 0.001);
+            const half_v = @max((tx_lo + tx_hi) * 0.5, 0.001);
+            const grid_base = (st * 24 + ch) * 256;
+            var row: usize = 0;
+            while (row < 16) : (row += 1) {
+                const ny = (@as(f32, @floatFromInt(row)) - 7.5) / 7.5 * 32.0;
+                const vy_norm = @abs(ny) / half_v;
+                const v_vy: Vec4f = @splat(vy_norm * vy_norm);
+                const v_inv_ht: Vec4f = @splat(1.0 / half_t);
+                const v_one: Vec4f = @splat(1.0);
+                const v_zero: Vec4f = @splat(0.0);
+
+                var col: usize = 0;
+                while (col < 16) : (col += 4) {
+                    const c0 = (@as(f32, @floatFromInt(col + 0)) - 7.5) / 7.5 * 32.0;
+                    const c1 = (@as(f32, @floatFromInt(col + 1)) - 7.5) / 7.5 * 32.0;
+                    const c2 = (@as(f32, @floatFromInt(col + 2)) - 7.5) / 7.5 * 32.0;
+                    const c3 = (@as(f32, @floatFromInt(col + 3)) - 7.5) / 7.5 * 32.0;
+                    const vx = Vec4f{ @abs(c0), @abs(c1), @abs(c2), @abs(c3) } * v_inv_ht;
+                    const dist2 = vx * vx + v_vy;
+                    const margin = @max(v_zero, v_one - dist2);
+                    eye_grid_out[grid_base + row * 16 + col ..][0..4].* = margin;
+                }
+            }
+        }
+
+        const out_s = st * 4;
+        if (active_ch > 0.0) {
+            summary_out[out_s + 0] = min_timing;
+            summary_out[out_s + 1] = min_vref;
+            summary_out[out_s + 2] = sum_timing / active_ch;
+            summary_out[out_s + 3] = sum_vref / active_ch;
+        } else {
+            summary_out[out_s + 0] = 0.0;
+            summary_out[out_s + 1] = 0.0;
+            summary_out[out_s + 2] = 0.0;
+            summary_out[out_s + 3] = 0.0;
+        }
+    }
+}

+ 0 - 118
native/stl_sol_bridge.py

@@ -1,118 +0,0 @@
-#!/usr/bin/env python3
-"""One IPMI SOL session. Raw stdin/stdout, JSON status on stderr.
-
-Wait for ipmitool's successful activation banner before reporting ready.
-A disconnect is an error: no silent reconnection, command replay or takeover.
-"""
-import contextlib
-import json
-import os
-import pty
-import re
-import select
-import signal
-import subprocess
-import sys
-import time
-import tty
-
-READY = re.compile(br"\[SOL Session operational[^\r\n]*\](?:\r?\n)?")
-
-
-def status(event, code=0):
-    print(json.dumps({"event": event, "code": code}), file=sys.stderr, flush=True)
-
-
-def main():
-    if sys.argv[1:] == ["--help"]:
-        print("STL_SOL_HOST, STL_SOL_USER, STL_SOL_PASSWORD; optional STL_SOL_CIPHER_SUITE=17", file=sys.stderr)
-        return 0
-    host, user, secret = (os.environ.get(k) for k in ("STL_SOL_HOST", "STL_SOL_USER", "STL_SOL_PASSWORD"))
-    if not all((host, user, secret)):
-        status("error", 1002)
-        return 2
-    stopped = False
-
-    def stop(signum, frame):
-        nonlocal stopped
-        stopped = True
-
-    signal.signal(signal.SIGTERM, stop)
-    signal.signal(signal.SIGINT, stop)
-    env = os.environ.copy()
-    env["IPMI_PASSWORD"] = secret
-    env.pop("IPMITOOL_PASSWORD", None)
-    command = ["ipmitool", "-I", "lanplus", "-H", host, "-U", user,
-               "-E", "-C", env.get("STL_SOL_CIPHER_SUITE", "17"), "sol", "activate"]
-    master, slave = pty.openpty()
-    tty.setraw(slave)
-    proc = None
-    try:
-        proc = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave, env=env, close_fds=True)
-        os.close(slave)
-        slave = None
-        status("connecting")
-        ready = False
-        pending = b""
-        deadline = time.monotonic() + 20
-        while not stopped:
-            if not ready and time.monotonic() >= deadline:
-                status("error", 1007)
-                return 2
-            readable, _, _ = select.select([master] + ([sys.stdin.fileno()] if ready else []), [], [], 0.2)
-            if master in readable:
-                try:
-                    data = os.read(master, 8192)
-                except OSError:
-                    data = b""
-                if not data:
-                    if not stopped:
-                        status("error", 1008)
-                        return 2
-                    break
-                if not ready:
-                    pending = (pending + data)[-65536:]
-                    if b"already active" in pending.lower() or b"in use" in pending.lower():
-                        status("error", 1006)
-                        return 2
-                    banner = READY.search(pending)
-                    if not banner:
-                        continue
-                    ready = True
-                    status("ready")
-                    data = pending[banner.end():]
-                    pending = b""
-                if data:
-                    sys.stdout.buffer.write(data)
-                    sys.stdout.buffer.flush()
-            if ready and sys.stdin.fileno() in readable:
-                data = os.read(sys.stdin.fileno(), 65536)
-                if not data:
-                    break
-                while data:
-                    written = os.write(master, data)
-                    data = data[written:]
-            if proc.poll() is not None:
-                status("error", 1008)
-                return 2
-        status("closed")
-        return 0
-    except OSError:
-        status("error", 1005)
-        return 2
-    finally:
-        if slave is not None:
-            os.close(slave)
-        if proc and proc.poll() is None:
-            proc.terminate()
-            try:
-                proc.wait(timeout=2)
-            except subprocess.TimeoutExpired:
-                proc.kill()
-                proc.wait()
-        with contextlib.suppress(OSError):
-            os.close(master)
-
-
-if __name__ == "__main__":
-    sys.exit(main())

+ 0 - 168
native/stl_ssh_console_bridge.py

@@ -1,168 +0,0 @@
-#!/usr/bin/env python3
-"""OpenBMC host console over SSH: raw stdin/stdout, JSON status on stderr.
-
-This connects to the configured host-console SSH port, not the BMC Linux shell.
-It never sends a CR, changes BIOS settings, reconnects, or replays input by itself.
-"""
-import contextlib
-import json
-import os
-from pathlib import Path
-import pty
-import select
-import signal
-import subprocess
-import sys
-import time
-import tty
-
-
-def status(event, code=0):
-    print(json.dumps({"event": event, "code": code}), file=sys.stderr, flush=True)
-
-
-class SshStatus:
-    """Interpret only SSH's independent diagnostic stream, never console bytes."""
-    def __init__(self):
-        self.buffer = b""
-        self.authenticated = False
-        self.shell_accepted = False
-        self.error = 0
-
-    @property
-    def ready(self):
-        return self.authenticated and self.shell_accepted and not self.error
-
-    def feed(self, data):
-        self.buffer = (self.buffer + data)[-65536:]
-        text = self.buffer.lower()
-        self.authenticated = self.authenticated or b"authenticated to " in text
-        self.shell_accepted = self.shell_accepted or b"shell request accepted on channel " in text
-        if b"remote host identification has changed" in text or b"host key verification failed" in text:
-            self.error = 1011
-        elif b"permission denied" in text or b"authentication failed" in text:
-            self.error = 1010
-        elif b"shell request failed" in text or b"pty allocation request failed" in text:
-            self.error = 1012
-
-
-def main():
-    if sys.argv[1:] == ["--help"]:
-        print("STL_SOL_HOST, STL_SOL_USER, STL_SOL_PASSWORD; optional STL_SSH_PORT=2200, "
-              "STL_SSH_KNOWN_HOSTS=data/ssh_known_hosts", file=sys.stderr)
-        return 0
-    host, user, secret = (os.environ.get(k) for k in ("STL_SOL_HOST", "STL_SOL_USER", "STL_SOL_PASSWORD"))
-    try:
-        port = int(os.environ.get("STL_SSH_PORT", "2200"))
-        if not all((host, user, secret)) or host.startswith("-") or not 1 <= port <= 65535:
-            raise ValueError("Invalid SSH console settings")
-        known_hosts = Path(os.environ.get("STL_SSH_KNOWN_HOSTS", "data/ssh_known_hosts")).resolve()
-        known_hosts.parent.mkdir(parents=True, exist_ok=True)
-    except (ValueError, OSError):
-        status("error", 1002)
-        return 2
-
-    stopped = False
-    def stop(signum, frame):
-        nonlocal stopped
-        stopped = True
-    signal.signal(signal.SIGTERM, stop)
-    signal.signal(signal.SIGINT, stop)
-
-    env = os.environ.copy()
-    env["SSHPASS"] = secret
-    # The child only needs sshpass's environment name; never place secrets in argv.
-    env.pop("STL_SOL_PASSWORD", None)
-    env["LC_ALL"] = "C"
-    command = ["sshpass", "-e", "ssh", "-tt", "-vv", "-p", str(port), "-l", user,
-               "-o", "StrictHostKeyChecking=accept-new",
-               "-o", "UserKnownHostsFile=" + str(known_hosts),
-               "-o", "NumberOfPasswordPrompts=1",
-               "-o", "PreferredAuthentications=password,keyboard-interactive",
-               "-o", "PubkeyAuthentication=no", "-o", "ConnectTimeout=8",
-               "-o", "ConnectionAttempts=1", "-o", "ServerAliveInterval=10",
-               "-o", "ServerAliveCountMax=2", "-o", "EscapeChar=none", host]
-
-    master, slave = pty.openpty()
-    tty.setraw(slave)
-    proc = None
-    try:
-        proc = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=subprocess.PIPE,
-                                env=env, close_fds=True, start_new_session=True)
-        os.close(slave)
-        slave = None
-        status("connecting")
-        parsed = SshStatus()
-        ready = False
-        master_open = True
-        stderr_open = True
-        deadline = time.monotonic() + 20
-        while not stopped:
-            if not ready and time.monotonic() >= deadline:
-                status("error", 1007)
-                return 2
-            sources = ([master] if master_open else []) + ([proc.stderr.fileno()] if stderr_open else [])
-            if ready:
-                sources.append(sys.stdin.fileno())
-            readable, _, _ = select.select(sources, [], [], 0.2)
-            if stderr_open and proc.stderr.fileno() in readable:
-                data = os.read(proc.stderr.fileno(), 8192)
-                if not data:
-                    stderr_open = False
-                else:
-                    parsed.feed(data)
-                    if parsed.error:
-                        status("error", parsed.error)
-                        return 2
-                    if not ready and parsed.ready:
-                        ready = True
-                        status("ready")
-            if master_open and master in readable:
-                try:
-                    data = os.read(master, 8192)
-                except OSError:
-                    data = b""
-                if not data:
-                    master_open = False
-                else:
-                    # Raw remote console output is evidence even if it precedes
-                    # the local SSH acknowledgement by a few scheduling ticks.
-                    sys.stdout.buffer.write(data)
-                    sys.stdout.buffer.flush()
-            if ready and sys.stdin.fileno() in readable:
-                data = os.read(sys.stdin.fileno(), 65536)
-                if not data:
-                    break
-                while data:
-                    size = os.write(master, data)
-                    data = data[size:]
-            if proc.poll() is not None and not master_open and not stderr_open:
-                status("error", 1008 if ready else parsed.error or 1010)
-                return 2
-        status("closed")
-        return 0
-    except OSError:
-        status("error", 1005)
-        return 2
-    finally:
-        if slave is not None:
-            os.close(slave)
-        if proc:
-            # sshpass and SSH share this private process group. Releasing the
-            # network connection does not send exit/Ctrl-C to the BIOS program.
-            with contextlib.suppress(ProcessLookupError):
-                os.killpg(proc.pid, signal.SIGTERM)
-            try:
-                proc.wait(timeout=1)
-            except subprocess.TimeoutExpired:
-                with contextlib.suppress(ProcessLookupError):
-                    os.killpg(proc.pid, signal.SIGKILL)
-                proc.wait()
-            if proc.stderr:
-                proc.stderr.close()
-        with contextlib.suppress(OSError):
-            os.close(master)
-
-
-if __name__ == "__main__":
-    sys.exit(main())

qt-client/port.json → port.json


+ 8 - 0
proto/stl/v1/bench.proto

@@ -50,6 +50,14 @@ service BenchService {
   rpc ListArtifacts(RunKey) returns (ArtifactList);
   rpc ReadArtifact(ReadArtifactRequest) returns (ByteChunk);
   rpc GetRunReport(RunKey) returns (RunReport);
+  // Unified stage intent, dual-mode queue/batch, DIMM replacement, and config audit RPCs.
+  rpc SubmitTaskBatch(google.protobuf.Struct) returns (google.protobuf.Struct);
+  rpc ControlTaskBatch(google.protobuf.Struct) returns (google.protobuf.Struct);
+  rpc GetTaskBatch(StationKey) returns (google.protobuf.Struct);
+  rpc GetTaskStatus(StationKey) returns (google.protobuf.Struct);
+  rpc SetStageIntent(google.protobuf.Struct) returns (google.protobuf.Struct);
+  rpc ConfirmDimmReplacement(google.protobuf.Struct) returns (google.protobuf.Struct);
+  rpc QueryAuditLogs(google.protobuf.Struct) returns (google.protobuf.Struct);
 }
 
 message StationKey { string station_id = 1; }

+ 0 - 30
pyproject.toml

@@ -1,30 +0,0 @@
-[build-system]
-requires = ["setuptools>=77"]
-build-backend = "setuptools.build_meta"
-
-[project]
-name = "xjkj-stl-backend"
-version = "0.8.1.17"
-description = "Four-station memory thermal test backend with WebSocket and gRPC"
-readme = "README.md"
-requires-python = ">=3.11"
-dependencies = ["grpcio==1.84.0", "protobuf==7.36.2", "aiohttp==3.14.5"]
-
-[project.optional-dependencies]
-dev = ["grpcio-tools==1.84.0", "pytest>=8,<10", "pytest-asyncio>=1,<2"]
-
-[project.scripts]
-stl-server = "stl_backend.server:main"
-stl-client = "stl_backend.cli:main"
-
-[tool.setuptools.packages.find]
-where = ["src"]
-
-[tool.setuptools.package-data]
-stl_backend = ["web/*.html", "web/*.css", "web/*.js", "domain/*.json"]
-
-[tool.pytest.ini_options]
-asyncio_mode = "auto"
-pythonpath = ["src"]
-testpaths = ["tests"]
-

+ 0 - 60
qt-client/DDR5_SLT_Monitor.pro

@@ -1,60 +0,0 @@
-#-------------------------------------------------------------------------------
-# DDR5 RDIMM SLT 上位机监控平台 —— 多工位测试监控
-# Qt 5 / C++11 / Linux + Windows(MinGW)
-#
-# 编译:
-#   qmake DDR5_SLT_Monitor.pro
-#   make -j4
-#-------------------------------------------------------------------------------
-
-QT       += core gui serialport websockets
-greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
-
-# QCustomPlot 2.1.1(GPLv3,src/3rdparty/qcustomplot/GPL.txt):温控曲线用
-QT       += printsupport
-
-TARGET    = DDR5_SLT_Monitor
-TEMPLATE  = app
-CONFIG   += c++11
-
-# 界面代码全部由 src/mainwindow.ui 生成
-INCLUDEPATH += $$PWD/src
-INCLUDEPATH += $$PWD/src/3rdparty/qcustomplot
-DEPENDPATH  += $$PWD/src
-
-SOURCES += \
-    src/main.cpp \
-    src/mainwindow.cpp \
-    src/overviewview.cpp \
-    src/detailview.cpp \
-    src/powerbutton.cpp \
-    src/stationdata.cpp \
-    src/localplans.cpp \
-    src/backendlink.cpp \
-    src/comworker.cpp \
-    src/sltproto.cpp \
-    src/comanager.cpp \
-    src/3rdparty/qcustomplot/qcustomplot.cpp
-
-HEADERS += \
-    src/appconfig.h \
-    src/mainwindow.h \
-    src/overviewview.h \
-    src/detailview.h \
-    src/powerbutton.h \
-    src/stationdata.h \
-    src/localplans.h \
-    src/backendlink.h \
-    src/uiformat.h \
-    src/comworker.h \
-    src/sltproto.h \
-    src/comanager.h \
-    src/3rdparty/qcustomplot/qcustomplot.h
-
-FORMS += \
-    src/mainwindow.ui
-
-RESOURCES += \
-    src/resources.qrc
-
-# 源码/样式统一按 UTF-8 处理(Linux g++ 默认即 UTF-8)

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


+ 0 - 52
qt-client/config.json

@@ -1,52 +0,0 @@
-{
-  "_comment": "内存参数配置:详情页「内存参数设置」页签从这里加载默认值,键名与界面控件一一对应。errhandle / ap 为开关(true=enable,false=disable),其余为数值(mem vdd / mem vddq 单位 mV,时序参数单位 tCK)。",
-  "memoryParams": {
-    "mem vdd": 1070,
-    "mem vddq": 1070,
-    "tCL": 44,
-    "tRCD": 43,
-    "tRP": 43,
-    "tRAS": 86,
-    "tRFC": 425,
-    "tRTP": 20,
-    "trrd_l": 13,
-    "tWTR_S": 7,
-    "tWTR_L": 27,
-    "tWR": 80,
-    "tCCD_L": 13,
-    "trefi": 23046,
-    "tRFCsb": 123,
-    "errhandle": false,
-    "ap": false
-  },
-  "backend": {
-    "url": "ws://192.168.2.79:8080/ws?view=qt-clean"
-  },
-  "qtPlan": {
-    "run_rmt": true,
-    "run_amt": true,
-    "run_mt": true,
-    "uip": {
-      "action": "continue_uip",
-      "run_rmt": true,
-      "apply_memory_params": false
-    },
-    "amt": {
-      "action": "start_amt",
-      "run_amt": true,
-      "exit_after": true,
-      "test_command": "amemdiag 1",
-      "settings": {
-        "test_command": "amemdiag 1"
-      }
-    },
-    "uefi": {
-      "action": "start_mt",
-      "run_mt": true,
-      "settings": {
-        "efi_path": "118.efi"
-      }
-    }
-  },
-  "_qt_note": "Qt 纯净临时版:计划保存在本机 qt-plans.json。run_rmt / run_amt / run_mt 均为可选项布尔开关(默认全部开启:run_rmt=true、run_amt=true、run_mt=true);AMT 开启时默认执行 amemdiag 1(默认不自动跳过任何算法);MT 开启时在 UEFI Shell 阶段默认依次发送 fs0:、cd EFI、118.efi(默认不自动跳过任何测试项,完成后退回 FS0:\\EFI> 且不自动关机)。"
-}

+ 0 - 21
qt-client/live-config-off/config.json

@@ -1,21 +0,0 @@
-{
-  "backend": {
-    "url": "ws://127.0.0.1:8080/ws?view=qt-clean"
-  },
-  "memoryParams": {
-    "errhandle": false
-  },
-  "qtPlan": {
-    "uip": {
-      "action": "continue_uip",
-      "apply_memory_params": true
-    },
-    "amt": {
-      "action": "skip_amt",
-      "exit_after": true
-    },
-    "uefi": {
-      "action": "hold"
-    }
-  }
-}

+ 0 - 24
qt-client/live-config-off/port.json

@@ -1,24 +0,0 @@
-{
-  "serialPorts": [
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    },
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    },
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    },
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    }
-  ]
-}

+ 0 - 19
qt-client/live-config-on/config.json

@@ -1,19 +0,0 @@
-{
-  "backend": {
-    "url": "ws://127.0.0.1:8080/ws?view=qt-clean"
-  },
-  "memoryParams": {},
-  "qtPlan": {
-    "uip": {
-      "action": "continue_uip",
-      "apply_memory_params": false
-    },
-    "amt": {
-      "action": "skip_amt",
-      "exit_after": true
-    },
-    "uefi": {
-      "action": "hold"
-    }
-  }
-}

+ 0 - 24
qt-client/live-config-on/port.json

@@ -1,24 +0,0 @@
-{
-  "serialPorts": [
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    },
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    },
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    },
-    {
-      "port": "",
-      "serialNumber": "",
-      "baud": 115200
-    }
-  ]
-}

BIN
qt-client/src/assets/logo-mark.png


+ 0 - 510
qt-client/src/backendlink.cpp

@@ -1,510 +0,0 @@
-#include "backendlink.h"
-
-#include "appconfig.h"
-#include "localplans.h"
-#include <QDateTime>
-#include <QDebug>
-#include <QFile>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QUrl>
-#include <QUuid>
-
-namespace {
-QString stationId(int index) { return QStringLiteral("S%1").arg(index + 1); }
-int stationIndex(const QJsonObject &object)
-{
-    const QString id = object.value(QStringLiteral("station_id")).toString();
-    for (int i = 0; i < 4; ++i)
-        if (id == stationId(i)) return i;
-    return -1;
-}
-QString errorMessage(const QJsonValue &value)
-{
-    return value.isObject() ? value.toObject().value(QStringLiteral("message")).toString()
-                            : value.toString();
-}
-}
-
-BackendLink::BackendLink(QObject *parent) : QObject(parent)
-{
-    connect(&m_ws, &QWebSocket::connected, this, &BackendLink::onConnected);
-    connect(&m_ws, &QWebSocket::disconnected, this, &BackendLink::onDisconnected);
-    connect(&m_ws, &QWebSocket::textMessageReceived, this, &BackendLink::onTextMessage);
-    connect(&m_ws, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
-            this, [this](QAbstractSocket::SocketError) {
-        qInfo().noquote() << "[backend]" << m_ws.errorString();
-        if (m_ws.state() == QAbstractSocket::UnconnectedState && !m_reconnect.isActive())
-            m_reconnect.start();
-    });
-    m_reconnect.setSingleShot(true);
-    m_reconnect.setInterval(3000);
-    connect(&m_reconnect, &QTimer::timeout, this, &BackendLink::openSocket);
-    m_pendingTimer.setInterval(1000);
-    connect(&m_pendingTimer, &QTimer::timeout, this, &BackendLink::checkPending);
-}
-
-BackendLink::~BackendLink()
-{
-    // QWebSocket emits disconnect-related signals while being destroyed. Stop
-    // those callbacks before Run/request members (declared after it) are gone.
-    m_reconnect.stop();
-    m_pendingTimer.stop();
-    disconnect(&m_ws, nullptr, this, nullptr);
-    disconnect(this, nullptr, nullptr, nullptr);
-    m_ws.abort();
-    m_requests.clear();
-}
-
-void BackendLink::start()
-{
-    m_url = QStringLiteral("ws://192.168.2.79:8080/ws?view=qt-clean");
-    QFile file(appConfigPath(QStringLiteral("config.json")));
-    if (file.open(QIODevice::ReadOnly)) {
-        const QString configured = QJsonDocument::fromJson(file.readAll()).object()
-            .value(QStringLiteral("backend")).toObject().value(QStringLiteral("url")).toString();
-        if (!configured.isEmpty()) m_url = configured;
-    }
-    const QString overrideUrl = qEnvironmentVariable("STL_QT_BACKEND_URL");
-    if (!overrideUrl.isEmpty()) m_url = overrideUrl;
-    openSocket();
-    m_pendingTimer.start();
-}
-
-void BackendLink::openSocket()
-{
-    if (m_ws.state() != QAbstractSocket::UnconnectedState) return;
-    m_connectStartedMs = QDateTime::currentMSecsSinceEpoch();
-    m_ws.open(QUrl(m_url));
-}
-
-void BackendLink::onConnected()
-{
-    m_reconnect.stop();
-    m_connectStartedMs = 0;
-    m_lastReceivedMs = QDateTime::currentMSecsSinceEpoch();
-    emit connectionChanged(true);
-    qInfo().noquote() << "[backend] Qt clean connected";
-    sendRequest(QStringLiteral("GetState"), {}, -1, [this](const QJsonObject &state) { applyState(state); });
-    // Pending controls are queried, never blindly replayed after reconnect.
-    for (Run &run : m_runs) run.queried = 0;
-    checkPending();
-}
-
-void BackendLink::onDisconnected()
-{
-    emit connectionChanged(false);
-    m_requests.clear();
-    for (int i = 0; i < 4; ++i) {
-        if (m_runs[i].active)
-            qWarning().noquote() << "[backend] connection lost, pending command will only be queried" << i;
-    }
-    m_reconnect.start();
-}
-
-void BackendLink::sendRequest(const QString &method, const QJsonObject &params, int station,
-                             const std::function<void(const QJsonObject &)> &onOk,
-                             const std::function<void(const QString &)> &onError)
-{
-    if (!isConnected()) return;
-    const QString id = QStringLiteral("qt-%1").arg(++m_idCounter);
-    Request request;
-    request.method = method;
-    request.station = station;
-    request.sent = QDateTime::currentMSecsSinceEpoch();
-    request.onOk = onOk;
-    request.onError = onError;
-    m_requests.insert(id, request);
-    const QJsonObject frame{{QStringLiteral("v"), 1}, {QStringLiteral("id"), id},
-                            {QStringLiteral("method"), method}, {QStringLiteral("params"), params}};
-    m_ws.sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
-}
-
-void BackendLink::onTextMessage(const QString &json)
-{
-    m_lastReceivedMs = QDateTime::currentMSecsSinceEpoch();
-    const QJsonObject frame = QJsonDocument::fromJson(json.toUtf8()).object();
-    const QString event = frame.value(QStringLiteral("event")).toString();
-    if (event == QStringLiteral("state")) {
-        applyState(frame.value(QStringLiteral("result")).toObject());
-        return;
-    }
-    if (event == QStringLiteral("logs")) {
-        // Qt's test log contains only captured BIOS UART, never event summaries.
-        return;
-    }
-    if (event == QStringLiteral("bios_uart")) {
-        applyBiosUart(frame.value(QStringLiteral("result")).toObject());
-        return;
-    }
-    const QString id = frame.value(QStringLiteral("id")).toString();
-    if (!m_requests.contains(id)) return;
-    const Request request = m_requests.take(id);
-    if (frame.value(QStringLiteral("ok")).toBool()) {
-        if (request.onOk) request.onOk(frame.value(QStringLiteral("result")).toObject());
-    } else {
-        const QString message = errorMessage(frame.value(QStringLiteral("error")));
-        if (request.onError) request.onError(message);
-        else if (request.station >= 0) failRun(request.station, message);
-        else qWarning().noquote() << "[backend]" << message;
-    }
-}
-
-void BackendLink::refreshPlan(int station)
-{
-    if (station < 0 || station >= 4) return;
-    m_runs[station].plan = LocalPlans().plan(station);
-    advancePlan(station);
-}
-
-bool BackendLink::isBusy(int station) const
-{
-    return station >= 0 && station < 4 && m_runs[station].active;
-}
-
-bool BackendLink::startTest(int station)
-{
-    if (station < 0 || station >= 4) return false;
-    if (!isConnected()) {
-        qWarning() << "[backend] cannot start: disconnected" << station;
-        return false;
-    }
-    for (auto it = m_requests.begin(); it != m_requests.end(); ) {
-        if (it.value().station == station)
-            it = m_requests.erase(it);
-        else
-            ++it;
-    }
-    Run &run = m_runs[station];
-    run.active = true;
-    run.bootConfirmed = false;
-    run.bootId.clear();
-    run.startedUnixMs = 0;
-    run.sawMatchingBoot = false;
-    run.commandId.clear();
-    run.commandMethod.clear();
-    run.queried = 0;
-    run.inputs.clear();
-    run.amtStartedCpus.clear();
-    run.mtStarted = false;
-    run.plan = LocalPlans().plan(station);
-    qInfo() << "[backend] local plan started (forced restart), waiting for BIOS" << station;
-    return sendControl(station, QStringLiteral("StartTest"), {});
-}
-
-bool BackendLink::sendControl(int station, const QString &method, QJsonObject params)
-{
-    Run &run = m_runs[station];
-    if (!isConnected() || !run.commandId.isEmpty()) return false;
-    run.commandId = QStringLiteral("qt-%1").arg(QUuid::createUuid().toString(QUuid::WithoutBraces));
-    run.commandMethod = method;
-    run.queried = QDateTime::currentMSecsSinceEpoch();
-    params.insert(QStringLiteral("command_id"), run.commandId);
-    params.insert(QStringLiteral("station_id"), stationId(station));
-    sendRequest(method, params, station, [this, station](const QJsonObject &command) {
-        observeCommand(station, command);
-    });
-    return true;
-}
-
-void BackendLink::applyState(const QJsonObject &result)
-{
-    const QString serverId = result.value(QStringLiteral("server_id")).toString();
-    if (!serverId.isEmpty() && serverId != m_serverId) {
-        const bool restarted = !m_serverId.isEmpty();
-        m_serverId = serverId;
-        for (int i = 0; i < 4; ++i) {
-            if (restarted && m_runs[i].active)
-                failRun(i, QStringLiteral("后端已重启,旧操作不自动重放;请检查当前状态后重新开始"));
-        }
-    }
-    for (const QJsonValue &value : result.value(QStringLiteral("stations")).toArray()) {
-        const QJsonObject state = value.toObject();
-        const int station = stationIndex(state);
-        if (station < 0) continue;
-        m_runs[station].latest = state;
-        observeCommand(station, state.value(QStringLiteral("command")).toObject());
-        advancePlan(station);
-        emit stationState(station, state);
-    }
-}
-
-void BackendLink::observeCommand(int station, const QJsonObject &command)
-{
-    Run &run = m_runs[station];
-    if (run.commandId.isEmpty() || command.value(QStringLiteral("command_id")).toString() != run.commandId)
-        return;
-    const QString state = command.value(QStringLiteral("state")).toString().toLower();
-    if (state != QStringLiteral("succeeded") && state != QStringLiteral("failed")
-        && state != QStringLiteral("interrupted")) return;
-    const QString method = run.commandMethod;
-    run.commandId.clear();
-    run.commandMethod.clear();
-    if (state != QStringLiteral("succeeded")) {
-        const QString message = errorMessage(command.value(QStringLiteral("error")));
-        run.active = false;
-        emit commandFinished(station, method, false, message);
-        qWarning().noquote() << "[backend] operation failed" << station << (message.isEmpty() ? state : message);
-        return;
-    }
-    if (method == QStringLiteral("StartTest")) {
-        run.bootId = command.value(QStringLiteral("result")).toObject()
-            .value(QStringLiteral("boot_id")).toVariant().toString();
-        run.startedUnixMs = command.value(QStringLiteral("result")).toObject()
-            .value(QStringLiteral("started_unix_ms")).toVariant().toLongLong();
-        if (run.bootId.isEmpty()) {
-            failRun(station, QStringLiteral("开始响应缺少新启动编号,未执行后续阶段动作"));
-            return;
-        }
-        run.bootConfirmed = true;
-        qInfo() << "[backend] new BIOS boot confirmed" << station;
-        if (run.latest.value(QStringLiteral("boot_id")).toVariant().toString() != run.bootId)
-            sendRequest(QStringLiteral("GetState"), {}, -1, [this](const QJsonObject &state) { applyState(state); });
-    }
-    emit commandFinished(station, method, true, {});
-    advancePlan(station);
-    emit stationState(station, run.latest);
-}
-
-void BackendLink::advancePlan(int station)
-{
-    Run &run = m_runs[station];
-    if (!run.active || !run.bootConfirmed || !isConnected()) return;
-    const QString observedBoot = run.latest.value(QStringLiteral("boot_id")).toVariant().toString();
-    const qint64 observedStarted = run.latest.value(QStringLiteral("started_unix_ms")).toVariant().toLongLong();
-    const bool matchingBoot = !run.bootId.isEmpty() && observedBoot == run.bootId;
-    const bool currentRun = matchingBoot || (run.startedUnixMs > 0 && observedStarted >= run.startedUnixMs);
-    const QString runState = run.latest.value(QStringLiteral("run_state")).toString();
-    // A Start reply can precede its new snapshot. An older UEFI/failed snapshot
-    // is ignored, but an explicit failure belonging to this run must not hide
-    // behind a changed boot id or a still-pending stage command.
-    if (currentRun && runState == QStringLiteral("failed")) {
-        failRun(station, matchingBoot ? QStringLiteral("本轮固件执行失败,已停止后续阶段动作")
-                                     : QStringLiteral("本轮 BIOS 启动已变化且后端报告失败,已停止后续阶段动作"));
-        return;
-    }
-    if (!matchingBoot) {
-        if (run.sawMatchingBoot && currentRun && !observedBoot.isEmpty())
-            failRun(station, QStringLiteral("本轮 BIOS 意外再次启动,已停止后续阶段动作"));
-        return;
-    }
-    run.sawMatchingBoot = true;
-    if (!run.commandId.isEmpty()) return;
-    if (runState == QStringLiteral("completed")) {
-        run.active = false;
-        return;
-    }
-    const QJsonObject input = run.latest.value(QStringLiteral("input")).toObject();
-    const QString id = input.value(QStringLiteral("id")).toString();
-    if (!input.value(QStringLiteral("ready")).toBool() || id.isEmpty() || run.inputs.contains(id)) return;
-    const QString stage = input.value(QStringLiteral("stage")).toString();
-    QJsonObject params{{QStringLiteral("input_id"), id}};
-    QString action;
-    if (stage == QStringLiteral("uip1") || stage == QStringLiteral("uip2") || stage == QStringLiteral("uip")) {
-        const QJsonObject uip = run.plan.value(QStringLiteral("uip")).toObject();
-        const QJsonObject memParams = run.plan.value(QStringLiteral("memory_params")).toObject();
-        const bool defaultRunRmt = !uip.contains(QStringLiteral("action"))
-                                   || uip.contains(QStringLiteral("run_rmt"))
-                                   || run.plan.contains(QStringLiteral("run_rmt"));
-        const bool runRmt = run.plan.value(QStringLiteral("run_rmt")).toBool(
-            run.plan.value(QStringLiteral("rmt")).toBool(
-                uip.value(QStringLiteral("run_rmt")).toBool(
-                    memParams.value(QStringLiteral("run_rmt")).toBool(
-                        memParams.value(QStringLiteral("rmt")).toBool(defaultRunRmt)))));
-        action = uip.value(QStringLiteral("action")).toString(QStringLiteral("continue_uip"));
-        if (stage != QStringLiteral("uip2")) {
-            params.insert(QStringLiteral("run_rmt"), runRmt);
-            if (uip.value(QStringLiteral("apply_memory_params")).toBool(false))
-                params.insert(QStringLiteral("memory_params"), memParams);
-        }
-    } else if (stage == QStringLiteral("amt")) {
-        const QJsonObject amt = run.plan.value(QStringLiteral("amt")).toObject();
-        const QJsonObject memParams = run.plan.value(QStringLiteral("memory_params")).toObject();
-        const QString amtAction = amt.value(QStringLiteral("action")).toString();
-        const bool defaultRunAmt = amtAction.isEmpty() ? true : (amtAction == QStringLiteral("start_amt"));
-        const bool runAmt = run.plan.value(QStringLiteral("run_amt")).toBool(
-            run.plan.value(QStringLiteral("amt")).toBool(
-                amt.value(QStringLiteral("run_amt")).toBool(
-                    memParams.value(QStringLiteral("run_amt")).toBool(
-                        memParams.value(QStringLiteral("amt")).toBool(defaultRunAmt)))));
-        action = runAmt ? QStringLiteral("start_amt")
-                        : amt.value(QStringLiteral("action")).toString(QStringLiteral("skip_amt"));
-        if (action == QStringLiteral("start_amt") && run.amtStartedCpus.contains(input.value(QStringLiteral("cpu")).toInt())) {
-            if (!input.value(QStringLiteral("test_complete")).toBool(false)) return;
-            action = amt.value(QStringLiteral("exit_after")).toBool(true)
-                ? QStringLiteral("skip_amt") : QStringLiteral("hold");
-        }
-        if (action == QStringLiteral("start_amt")) {
-            params.insert(QStringLiteral("run_amt"), true);
-            QJsonObject amtSettings;
-            const QString testCmd = amt.value(QStringLiteral("test_command")).toString(QStringLiteral("amemdiag 1")).trimmed();
-            amtSettings.insert(QStringLiteral("test_command"), testCmd.isEmpty() ? QStringLiteral("amemdiag 1") : testCmd);
-            params.insert(QStringLiteral("amt"), amtSettings);
-        }
-    } else if (stage == QStringLiteral("uefi")) {
-        const QJsonObject uefi = run.plan.value(QStringLiteral("uefi")).toObject();
-        const QJsonObject memParams = run.plan.value(QStringLiteral("memory_params")).toObject();
-        const QString uefiAction = uefi.value(QStringLiteral("action")).toString();
-        const bool defaultRunMt = uefiAction.isEmpty() ? true : (uefiAction == QStringLiteral("start_mt"));
-        const bool runMt = run.plan.value(QStringLiteral("run_mt")).toBool(
-            run.plan.value(QStringLiteral("mt")).toBool(
-                uefi.value(QStringLiteral("run_mt")).toBool(
-                    memParams.value(QStringLiteral("run_mt")).toBool(
-                        memParams.value(QStringLiteral("mt")).toBool(defaultRunMt)))));
-        if (runMt) {
-            action = QStringLiteral("start_mt");
-        } else if (uefiAction == QStringLiteral("skip_mt") || run.plan.contains(QStringLiteral("run_mt"))
-                   || run.plan.contains(QStringLiteral("mt")) || uefi.contains(QStringLiteral("run_mt"))
-                   || memParams.contains(QStringLiteral("run_mt")) || memParams.contains(QStringLiteral("mt"))) {
-            action = input.value(QStringLiteral("actions")).toArray().contains(QStringLiteral("skip_mt"))
-                ? QStringLiteral("skip_mt") : QStringLiteral("hold");
-        } else {
-            action = uefiAction.isEmpty() ? QStringLiteral("hold") : uefiAction;
-        }
-        if (action == QStringLiteral("start_mt")) {
-            if (run.mtStarted) action = QStringLiteral("hold");
-            else {
-                QJsonObject mtSettings = uefi.value(QStringLiteral("settings")).toObject();
-                if (mtSettings.value(QStringLiteral("efi_path")).toString().isEmpty())
-                    mtSettings.insert(QStringLiteral("efi_path"), QStringLiteral("118.efi"));
-                params.insert(QStringLiteral("run_mt"), true);
-                params.insert(QStringLiteral("mt"), mtSettings);
-            }
-        } else if (action == QStringLiteral("skip_mt")) {
-            params.insert(QStringLiteral("run_mt"), false);
-        }
-    } else return;
-    if (action == QStringLiteral("hold")) {
-        run.inputs.insert(id);
-        run.active = false;
-        qInfo() << "[backend] waiting for operator at" << stage << station;
-        return;
-    }
-    const QJsonArray actions = input.value(QStringLiteral("actions")).toArray();
-    if (!actions.contains(action)) return;
-    params.insert(QStringLiteral("action"), action);
-    run.inputs.insert(id);
-    if (!sendControl(station, QStringLiteral("StageAction"), params)) run.inputs.remove(id);
-    else if (action == QStringLiteral("start_amt")) run.amtStartedCpus.insert(input.value(QStringLiteral("cpu")).toInt());
-    else if (action == QStringLiteral("start_mt")) run.mtStarted = true;
-}
-
-void BackendLink::applyBiosUart(const QJsonObject &result)
-{
-    const int station = stationIndex(result);
-    if (station < 0) return;
-    const QString session = result.value(QStringLiteral("session_id")).toString();
-    if (session.isEmpty()) return;
-    if (m_uartSession[station] != session) {
-        m_uartSession[station] = session;
-        m_uartOffset[station] = 0;
-        m_uartPending[station].clear();
-        m_uartPendingSince[station] = 0;
-    }
-    const quint64 first = result.value(QStringLiteral("offset")).toVariant().toULongLong();
-    QByteArray bytes = QByteArray::fromBase64(result.value(QStringLiteral("data_base64")).toString().toLatin1());
-    const quint64 end = first + static_cast<quint64>(bytes.size());
-    if (end <= m_uartOffset[station]) return; // Reconnect replay: already displayed.
-    if (first > m_uartOffset[station]) {
-        qWarning() << "[backend] BIOS UART stream gap" << station << first << m_uartOffset[station];
-        // The next reconnect replays from offset zero; never invent a missing line.
-        return;
-    }
-    bytes.remove(0, static_cast<int>(m_uartOffset[station] - first));
-    m_uartOffset[station] = end;
-    m_uartPending[station].append(bytes);
-    int newline = -1;
-    while ((newline = m_uartPending[station].indexOf('\n')) >= 0) {
-        QByteArray line = m_uartPending[station].left(newline);
-        m_uartPending[station].remove(0, newline + 1);
-        if (line.endsWith('\r')) line.chop(1); // Normalize CRLF for QPlainTextEdit only.
-        emit logLine(station, QString::fromUtf8(line));
-    }
-    // BIOS prompts and UEFI TUI lines often omit the final newline. Do not
-    // withhold a long or idle raw line indefinitely.
-    if (m_uartPending[station].isEmpty()) {
-        m_uartPendingSince[station] = 0;
-    } else if (m_uartPending[station].size() > 16384) {
-        emit logLine(station, QString::fromUtf8(m_uartPending[station]));
-        m_uartPending[station].clear();
-        m_uartPendingSince[station] = 0;
-    } else {
-        m_uartPendingSince[station] = QDateTime::currentMSecsSinceEpoch();
-    }
-}
-
-void BackendLink::failRun(int station, const QString &message)
-{
-    Run &run = m_runs[station];
-    const QString method = run.commandMethod;
-    run.active = false;
-    run.commandId.clear();
-    run.commandMethod.clear();
-    qWarning().noquote() << "[backend]" << station << message;
-    emit commandFinished(station, method, false, message);
-}
-
-void BackendLink::checkPending()
-{
-    const qint64 now = QDateTime::currentMSecsSinceEpoch();
-    if (!isConnected()) {
-        // Qt can remain in ConnectingState after an unreachable network hop.
-        if (m_connectStartedMs > 0 && now - m_connectStartedMs > 10000) {
-            qWarning() << "[backend] connection attempt timed out; retrying";
-            m_connectStartedMs = 0;
-            m_ws.abort();
-            if (!m_reconnect.isActive()) m_reconnect.start();
-        }
-        return;
-    }
-    // The clean backend sends a state every second. A silent TCP half-open
-    // must not leave the Qt UI showing a misleading connected indicator.
-    if (m_lastReceivedMs > 0 && now - m_lastReceivedMs > 20000) {
-        qWarning() << "[backend] state stream silent for 20 seconds; reconnecting";
-        m_lastReceivedMs = 0;
-        m_ws.abort();
-        if (!m_reconnect.isActive()) m_reconnect.start();
-        return;
-    }
-    const auto keys = m_requests.keys();
-    for (const QString &id : keys) {
-        const Request request = m_requests.value(id);
-        if (now - request.sent < 10000) continue;
-        m_requests.remove(id);
-        if (request.onError) request.onError(QStringLiteral("响应超时"));
-        else if (request.station >= 0)
-            qWarning() << "[backend] awaiting command state" << request.station;
-    }
-    for (int i = 0; i < 4; ++i) {
-        if (!m_uartPending[i].isEmpty() && m_uartPendingSince[i] > 0) {
-            const QByteArray trimmed = m_uartPending[i].trimmed();
-            bool dotsOnly = !trimmed.isEmpty();
-            for (char ch : trimmed) {
-                if (ch != '.') {
-                    dotsOnly = false;
-                    break;
-                }
-            }
-            const qint64 flushDelayMs = dotsOnly ? 3000 : 500;
-            if (now - m_uartPendingSince[i] >= flushDelayMs) {
-                QByteArray line = m_uartPending[i];
-                m_uartPending[i].clear();
-                m_uartPendingSince[i] = 0;
-                if (line.endsWith('\r')) line.chop(1);
-                emit logLine(i, QString::fromUtf8(line));
-            }
-        }
-        Run &run = m_runs[i];
-        if (now - run.queried < 3000) continue;
-        if (run.commandId.isEmpty()) {
-            if (run.active && run.bootConfirmed && run.latest.value(QStringLiteral("boot_id")).toVariant().toString() != run.bootId) {
-                run.queried = now;
-                sendRequest(QStringLiteral("GetState"), {}, -1, [this](const QJsonObject &state) { applyState(state); });
-            }
-            continue;
-        }
-        run.queried = now;
-        const QJsonObject params{{QStringLiteral("command_id"), run.commandId}};
-        sendRequest(QStringLiteral("GetCommand"), params, i, [this, i](const QJsonObject &command) { observeCommand(i, command); });
-    }
-}

+ 0 - 92
qt-client/src/backendlink.h

@@ -1,92 +0,0 @@
-#ifndef BACKENDLINK_H
-#define BACKENDLINK_H
-
-#include <functional>
-#include <QByteArray>
-#include <QHash>
-#include <QJsonObject>
-#include <QJsonArray>
-#include <QObject>
-#include <QSet>
-#include <QString>
-#include <QTimer>
-#include <QWebSocket>
-
-// Qt clean client. Widgets only start a local plan and consume clean snapshots.
-// Parameter names, BIOS parsing and hardware actions are owned by the backend.
-class BackendLink : public QObject
-{
-    Q_OBJECT
-public:
-    explicit BackendLink(QObject *parent = nullptr);
-    ~BackendLink() override;
-    void start();
-    bool isConnected() const { return m_ws.state() == QAbstractSocket::ConnectedState; }
-    bool startTest(int station);
-    void refreshPlan(int station);
-    bool isBusy(int station) const;
-    QString bootId(int station) const { return station >= 0 && station < 4 ? m_runs[station].bootId : QString(); }
-    QString url() const { return m_url; }
-
-signals:
-    void connectionChanged(bool connected);
-    void logLine(int station, const QString &line);
-    void stationState(int station, const QJsonObject &state);
-    void commandFinished(int station, const QString &method, bool success, const QString &error);
-
-private slots:
-    void onConnected();
-    void onDisconnected();
-    void onTextMessage(const QString &json);
-    void checkPending();
-
-private:
-    struct Request {
-        QString method;
-        int station = -1;
-        qint64 sent = 0;
-        std::function<void(const QJsonObject &)> onOk;
-        std::function<void(const QString &)> onError;
-    };
-    struct Run {
-        bool active = false;
-        bool bootConfirmed = false;
-        QString bootId;
-        qint64 startedUnixMs = 0;
-        bool sawMatchingBoot = false;
-        QJsonObject plan;
-        QJsonObject latest;
-        QSet<QString> inputs;
-        QSet<int> amtStartedCpus;
-        bool mtStarted = false;
-        QString commandId;
-        QString commandMethod;
-        qint64 queried = 0;
-    };
-    void openSocket();
-    void sendRequest(const QString &method, const QJsonObject &params, int station = -1,
-                     const std::function<void(const QJsonObject &)> &onOk = {},
-                     const std::function<void(const QString &)> &onError = {});
-    void applyState(const QJsonObject &result);
-    void applyBiosUart(const QJsonObject &result);
-    void observeCommand(int station, const QJsonObject &command);
-    void advancePlan(int station);
-    bool sendControl(int station, const QString &method, QJsonObject params);
-    void failRun(int station, const QString &message);
-
-    QWebSocket m_ws;
-    QTimer m_reconnect;
-    QTimer m_pendingTimer;
-    QString m_url;
-    int m_idCounter = 0;
-    qint64 m_connectStartedMs = 0;
-    qint64 m_lastReceivedMs = 0;
-    QHash<QString, Request> m_requests;
-    Run m_runs[4];
-    quint64 m_uartOffset[4] = {0, 0, 0, 0};
-    QString m_uartSession[4];
-    QByteArray m_uartPending[4];
-    qint64 m_uartPendingSince[4] = {0, 0, 0, 0};
-    QString m_serverId;
-};
-#endif

+ 0 - 116
qt-client/src/demofeed.cpp

@@ -1,116 +0,0 @@
-#include "demofeed.h"
-
-#include "stationdata.h"
-
-#include <QDateTime>
-#include <QRandomGenerator>
-#include <QtGlobal>
-
-#include <cmath>
-
-namespace {
-
-// 走表周期:1000ms 一次,跟真实设备的采样节奏一致。
-// 现在只用来刷新「运行时间」,温度 / 状态都保持空态。
-const int kSampleIntervalMs = 1000;
-
-} // namespace
-
-DemoDataSource::DemoDataSource(StationStore *store, QObject *parent)
-    : QObject(parent)
-    , m_store(store)
-{
-    m_timer.setInterval(kSampleIntervalMs);
-    connect(&m_timer, &QTimer::timeout, this, &DemoDataSource::tick);
-}
-
-void DemoDataSource::start()
-{
-    seed();
-    m_timer.start();
-}
-
-void DemoDataSource::seed()
-{
-    const QStringList names = channelNames();
-    const QStringList devices = {QStringLiteral("SLT-HT-001"), QStringLiteral("SLT-HT-002"),
-                                 QStringLiteral("SLT-HT-003"), QStringLiteral("SLT-HT-004")};
-    const QStringList tasks = {QStringLiteral("TASK-20261021-001"), QStringLiteral("TASK-20261019-019"),
-                               QStringLiteral("TASK-20261019-020"), QStringLiteral("TASK-20261019-021")};
-    const QStringList ports = {QStringLiteral("COM3"), QStringLiteral("COM4"),
-                               QStringLiteral("COM5"), QStringLiteral("COM6")};
-
-    for (int i = 0; i < m_store->count() && i < devices.size(); ++i) {
-        StationData d;
-        d.deviceId = devices.at(i);
-        d.taskId = tasks.at(i);
-        d.product = QStringLiteral("DDR5 RDIMM");
-        d.mode = QStringLiteral("高温模式");
-        d.port = ports.at(i);
-        d.targetTemp = 70.0;
-
-        // 空态:还没开始测试 —— 温度无数据(界面 --℃)、运行时间从 00:00:00 起步
-        d.currentTemp = -1.0;
-        d.startTime = QDateTime();
-
-        // 24 个通道一律未装载(IDLE),不预置任何 PASS / FAIL
-        for (const QString &name : names)
-            d.channels.append(ChannelInfo(name, -1.0, ChannelInfo::Idle));
-
-        // 日志不再预置假数据:等后端 / 串口报文接入后由 StationStore::appendLog() 实时写入
-
-        m_store->initStation(i, d);
-    }
-}
-
-void DemoDataSource::tick()
-{
-    ++m_tick;
-
-    if (m_simulate)
-        pushSimulatedTemperatures();
-
-    // 演示数据(温度抖动 / PASS-FAIL 随机)已按要求停掉,界面保持空态:
-    // 现在 tick 只做一件事 —— 让已经点过「开始测试」的工位,运行时间每秒往下走。
-    for (int i = 0; i < m_store->count(); ++i) {
-        if (m_store->station(i).startTime.isValid())
-            m_store->touchRuntime(i);
-    }
-}
-
-void DemoDataSource::pushSimulatedTemperatures()
-{
-    // 造一组「像设备回的」字节:温度在 68~72℃ 之间缓慢起伏,
-    // 并故意留几个 0xFF,好让界面上同时出现「蓝色已装载」和「灰色 --℃」两种格子。
-    // 四个工位的相位错开一点,看起来不像同一条曲线在复制。
-    for (int i = 0; i < m_store->count(); ++i) {
-        const double phase = m_tick / 9.0 + i * 1.7;
-
-        QByteArray ct;                        // CT7428 八路
-        for (int c = 0; c < 8; ++c) {
-            // 第 3 路固定无效:验证「跳过 0xFF 再取平均」
-            if (c == 2) {
-                ct.append(char(0xFF));
-                continue;
-            }
-            const double t = 69.0 + std::sin(phase + c * 0.35) * 2.0
-                           + (QRandomGenerator::global()->generateDouble() - 0.5) * 0.6;
-            ct.append(char(qRound(qBound(0.0, t, 254.0))));
-        }
-        m_store->applyCtTemperatures(i, ct);
-
-        QByteArray ch;                        // 24 路 BMC
-        for (int c = 0; c < 24; ++c) {
-            // 最后 4 路固定无效:模拟没插条的通道
-            if (c >= 20) {
-                ch.append(char(0xFF));
-                continue;
-            }
-            const double t = 70.0 + std::sin(phase + c * 0.22) * 1.6
-                           + (QRandomGenerator::global()->generateDouble() - 0.5) * 0.5;
-            ch.append(char(qRound(qBound(0.0, t, 254.0))));
-        }
-        m_store->applyChannelTemperatures(i, ch);
-    }
-}
-

+ 0 - 741
qt-client/src/detailview.cpp

@@ -1,741 +0,0 @@
-#include "detailview.h"
-
-#include "appconfig.h"
-#include "localplans.h"
-#include "stationdata.h"
-
-#include "qcustomplot.h"
-#include "ui_mainwindow.h"
-
-#include <QCheckBox>
-#include <QCoreApplication>
-#include <QDateTime>
-#include <QDebug>
-#include <QDir>
-#include <QFile>
-#include <QFontMetrics>
-#include <QFileInfo>
-#include <QHBoxLayout>
-#include <QFrame>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QIntValidator>
-#include <QJsonValue>
-#include <QLabel>
-#include <QLineEdit>
-#include <QMouseEvent>
-#include <QPlainTextEdit>
-#include <QPushButton>
-#include <QScrollBar>
-#include <QStyle>
-
-namespace {
-
-const int kTabCount = 3;   // 温控曲线 / 异常记录 / 内存参数设置
-
-// 顺序必须与 tools/gen_ui.py 的 PARAM_COLS / PARAM_CHECKS 保持一致
-const char *const kParamKeys[] = {
-    "mem vdd", "mem vddq", "tCL", "tRCD", "tRP", "tRAS",
-    "tRFC", "tRTP", "trrd_l", "tWTR_S", "tWTR_L", "tWR",
-    "tCCD_L", "trefi", "tRFCsb",
-};
-const int kParamKeyCount = int(sizeof(kParamKeys) / sizeof(kParamKeys[0]));
-
-const char *const kParamChecks[] = {"errhandle", "ap"};
-const int kParamCheckCount = int(sizeof(kParamChecks) / sizeof(kParamChecks[0]));
-
-// 图例前面那个小色块的画法。
-// QCustomPlot 默认是照抄曲线画笔(1.6px)画一条细线,右端还会多画 5px,
-// 缩到 18×8 的图标框里就成了「一根毛边小横杠」。这里自己画:
-//   Pill = 3px 圆头短棒(默认)、Dot = 小圆点、None = 只要文字
-enum LegendSwatch { SwatchPill, SwatchDot, SwatchNone };
-const LegendSwatch kSwatch = SwatchPill;
-
-// 色块的尺寸由 setupCurvePlot() 按图例字体算好,画的时候直接用:
-//   g_swatchH   = 大写字母高度(色块要和字一样高)
-//   g_swatchTop = ascent - capHeight(图标框里色块该往下挪多少才和字对齐)
-int g_swatchH = 10;
-int g_swatchTop = 3;
-
-class CurveGraph : public QCPGraph
-{
-public:
-    CurveGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
-        : QCPGraph(keyAxis, valueAxis)
-    {
-    }
-
-protected:
-    // 只在图例里生效:曲线本身仍然用 setPen() 设的 1.6px 细线
-    void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const override
-    {
-        if (kSwatch == SwatchNone)
-            return;
-
-        const QColor color("#2f7fc1");
-        painter->setRenderHint(QPainter::Antialiasing, true);
-
-        if (kSwatch == SwatchDot) {
-            painter->setPen(Qt::NoPen);
-            painter->setBrush(color);
-            const qreal r = qMin(rect.height() / 2.0 - 0.5, 4.0);
-            painter->drawEllipse(rect.center(), r, r);
-            return;
-        }
-
-        // 直角矩形,高度 = 大写字母高度,垂直位置和文字的大写字母对齐(不要圆角)
-        const QRectF bar(rect.left(), rect.top() + g_swatchTop, rect.width(), g_swatchH);
-        painter->setPen(Qt::NoPen);
-        painter->setBrush(color);
-        painter->drawRect(bar);
-    }
-};
-
-} // namespace
-
-DetailView::DetailView(Ui::MainWindow *ui, StationStore *store, QObject *parent)
-    : QObject(parent)
-    , m_ui(ui)
-    , m_store(store)
-{
-    // 布局伸缩比例(.ui 里写 stretch 会被 uic 拒绝)
-    m_ui->detailCols->setStretch(0, 56);
-    m_ui->detailCols->setStretch(1, 44);
-    m_ui->detailLeftCol->setStretch(0, 4);
-    m_ui->detailLeftCol->setStretch(1, 5);
-
-    // 内存参数表单:三列等宽(索引 0/2/4 是三列,1/3 是列间分隔线);
-    // 表单本身吃满页面高度,列里的 Expanding spacer 把行距均分,下方不再留大片空白
-    m_ui->paramForm->setStretch(0, 1);
-    m_ui->paramForm->setStretch(2, 1);
-    m_ui->paramForm->setStretch(4, 1);
-    m_ui->tabPageParamLayout->setStretch(0, 1);
-
-    // 行内让输入框优先吃富余宽度(涨到 160 就停),剩下的才给行尾的弹性空隙。
-    // 不给 stretch 的话,富余宽度会被行尾 spacer 全吃掉,输入框反而停在 sizeHint(≈124)上。
-    // 开关行(第 2 个是 QCheckBox)不参与,免得复选框被拉宽。
-    const QList<QHBoxLayout *> paramRows = m_ui->tabPageParam->findChildren<QHBoxLayout *>();
-    for (QHBoxLayout *row : paramRows) {
-        if (!row->objectName().startsWith(QStringLiteral("paramRow_")) || row->count() < 2)
-            continue;
-        if (qobject_cast<QLineEdit *>(row->itemAt(1)->widget()))
-            row->setStretch(1, 1);
-    }
-
-    cacheChannelWidgets();
-
-    // 内存参数只接受非负整数:挡住小数点、正负号、字母和粘贴进来的脏数据
-    const QList<QLineEdit *> paramEdits = m_ui->tabPageParam->findChildren<QLineEdit *>();
-    for (QLineEdit *e : paramEdits)
-        e->setValidator(new QIntValidator(0, 99999999, e));
-
-    auto createStageCheck = [this](const QString &labelText, const QString &objSuffix, int insertIdx) -> QCheckBox * {
-        QHBoxLayout *box = new QHBoxLayout();
-        box->setSpacing(6);
-        box->setContentsMargins(0, 0, 16, 0);
-        QLabel *lbl = new QLabel(labelText, m_ui->tabPageParam);
-        lbl->setObjectName(QStringLiteral("paramChkName_") + objSuffix);
-        lbl->setProperty("role", QStringLiteral("paramName"));
-        lbl->setAlignment(Qt::AlignLeading | Qt::AlignLeft | Qt::AlignVCenter);
-        QCheckBox *chk = new QCheckBox(m_ui->tabPageParam);
-        chk->setObjectName(QStringLiteral("paramCheck_") + objSuffix);
-        chk->setProperty("role", QStringLiteral("paramCheck"));
-        chk->setMinimumSize(16, 16);
-        chk->setMaximumSize(16, 16);
-        chk->setChecked(true);
-        box->addWidget(lbl);
-        box->addWidget(chk);
-        m_ui->paramSubmitRow->insertLayout(insertIdx, box);
-        connect(chk, &QCheckBox::clicked, this, [this]() {
-            m_stageToggled = true;
-            if (m_index >= 0 && m_chkRmt && m_chkAmt && m_chkMt)
-                emit stageTogglesChanged(m_index, m_chkRmt->isChecked(), m_chkAmt->isChecked(), m_chkMt->isChecked());
-        });
-        return chk;
-    };
-    m_chkRmt = createStageCheck(QStringLiteral("RMT"), QStringLiteral("rmt"), 0);
-    m_chkAmt = createStageCheck(QStringLiteral("AMT"), QStringLiteral("amt"), 1);
-    m_chkMt  = createStageCheck(QStringLiteral("MT"),  QStringLiteral("mt"),  2);
-
-    loadParamConfig();
-
-    m_flush.setSingleShot(true);
-    m_flush.setInterval(120);
-    connect(&m_flush, &QTimer::timeout, this, &DetailView::flushPending);
-
-    connect(m_ui->btnBackMonitor, &QPushButton::clicked, this, &DetailView::backRequested);
-    connect(m_ui->btnParamSubmit, &QPushButton::clicked, this, &DetailView::submitParams);
-    QPushButton *tabs[kTabCount] = {m_ui->detailTab_0, m_ui->detailTab_1, m_ui->detailTab_2};
-    for (int i = 0; i < kTabCount; ++i)
-        connect(tabs[i], &QPushButton::clicked, this, [this, i] { selectTab(i); });
-
-    connect(m_store, &StationStore::logAppended, this, &DetailView::onLogAppended);
-    connect(m_store, &StationStore::channelsChanged, this, &DetailView::onChannelsChanged);
-    connect(m_store, &StationStore::infoChanged, this, &DetailView::onInfoChanged);
-    connect(m_store, &StationStore::temperatureChanged, this, &DetailView::onTemperatureChanged);
-
-    setupCurvePlot();
-}
-
-// ---------------------------------------------------------------------------
-// 参数先读当前工位 Qt 本地计划,未保存的工位读 config.json 默认值。
-// ---------------------------------------------------------------------------
-void DetailView::loadParamConfig()
-{
-    const LocalPlans plans;
-    const QJsonObject params = plans.memoryParams(qMax(0, m_index));
-
-    int filled = 0;
-    for (int i = 0; i < kParamKeyCount; ++i) {
-        // 行号规则与 gen_ui.py 一致:前 6 个在第一列,接着 6 个第二列,最后 3 个第三列
-        const int col = (i < 6) ? 0 : (i < 12 ? 1 : 2);
-        const int row = (i < 6) ? i : (i < 12 ? i - 6 : i - 12);
-
-        const QJsonValue v = params.value(QLatin1String(kParamKeys[i]));
-        QLineEdit *edit = m_ui->tabPageParam->findChild<QLineEdit *>(
-            QStringLiteral("paramEdit_%1_%2").arg(col).arg(row));
-        if (!edit)
-            continue;
-        edit->clear();
-        if (v.isUndefined() || v.isNull())
-            continue;
-
-        edit->setText(v.isDouble() ? QString::number(v.toDouble(), 'g', 12)
-                                   : v.toVariant().toString());
-        ++filled;
-    }
-
-    for (int i = 0; i < kParamCheckCount; ++i) {
-        const QJsonValue v = params.value(QLatin1String(kParamChecks[i]));
-        QCheckBox *chk = m_ui->tabPageParam->findChild<QCheckBox *>(
-            QStringLiteral("paramCheck_2_%1").arg(3 + i)); // 第三列第 4、5 行,接在 3 个输入框后面
-        if (!chk)
-            continue;
-        chk->setChecked(false);
-        if (v.isUndefined() || v.isNull())
-            continue;
-
-        chk->setChecked(v.isBool() ? v.toBool() : v.toInt() != 0);
-        ++filled;
-    }
-
-    const QJsonObject stationPlan = plans.plan(qMax(0, m_index));
-    const QJsonObject uip = stationPlan.value(QStringLiteral("uip")).toObject();
-    const QJsonObject amt = stationPlan.value(QStringLiteral("amt")).toObject();
-    const QJsonObject uefi = stationPlan.value(QStringLiteral("uefi")).toObject();
-    const bool defaultRmt = !uip.contains(QStringLiteral("action"))
-                            || uip.contains(QStringLiteral("run_rmt"))
-                            || stationPlan.contains(QStringLiteral("run_rmt"));
-    const bool rmtChecked = stationPlan.value(QStringLiteral("run_rmt")).toBool(
-        uip.value(QStringLiteral("run_rmt")).toBool(
-            params.value(QStringLiteral("run_rmt")).toBool(
-                params.value(QStringLiteral("rmt")).toBool(defaultRmt))));
-    const QString amtAction = amt.value(QStringLiteral("action")).toString();
-    const bool defaultAmt = amtAction.isEmpty() ? true : (amtAction == QStringLiteral("start_amt"));
-    const bool amtChecked = stationPlan.value(QStringLiteral("run_amt")).toBool(
-        amt.value(QStringLiteral("run_amt")).toBool(
-            params.value(QStringLiteral("run_amt")).toBool(
-                params.value(QStringLiteral("amt")).toBool(defaultAmt))));
-    const QString uefiAction = uefi.value(QStringLiteral("action")).toString();
-    const bool defaultMt = uefiAction.isEmpty() ? true : (uefiAction == QStringLiteral("start_mt"));
-    const bool mtChecked = stationPlan.value(QStringLiteral("run_mt")).toBool(
-        uefi.value(QStringLiteral("run_mt")).toBool(
-            params.value(QStringLiteral("run_mt")).toBool(
-                params.value(QStringLiteral("mt")).toBool(defaultMt))));
-    if (m_chkRmt) m_chkRmt->setChecked(rmtChecked);
-    if (m_chkAmt) m_chkAmt->setChecked(amtChecked);
-    if (m_chkMt)  m_chkMt->setChecked(mtChecked);
-    m_stageToggled = false;
-
-    qInfo().noquote() << "[param] 从 Qt 本地计划加载工位" << qMax(0, m_index) + 1
-                      << filled << "项参数";
-}
-
-// ---------------------------------------------------------------------------
-// 内存参数页:界面输入框 / 开关 → memoryParams 同构 JSON(确定按钮用)
-// 只收集;上层原子保存到 Qt 的 qt-plans.json,config.json 默认值不改。
-// ---------------------------------------------------------------------------
-QJsonObject DetailView::collectParams(bool *valid)
-{
-    *valid = true;
-    QJsonObject params;
-
-    for (int i = 0; i < kParamKeyCount; ++i) {
-        const int col = (i < 6) ? 0 : (i < 12 ? 1 : 2);
-        const int row = (i < 6) ? i : (i < 12 ? i - 6 : i - 12);
-
-        const QLineEdit *edit = m_ui->tabPageParam->findChild<QLineEdit *>(
-            QStringLiteral("paramEdit_%1_%2").arg(col).arg(row));
-        if (!edit || edit->text().trimmed().isEmpty())
-            continue;
-
-        bool ok = false;
-        const qlonglong value = edit->text().trimmed().toLongLong(&ok);
-        if (!ok || !edit->hasAcceptableInput() || value < 0 || value > 99999999) {
-            *valid = false;
-            qWarning().noquote() << "[param] 工位" << m_index + 1 << QLatin1String(kParamKeys[i]) << "必须为非负整数,未保存任何修改";
-            return QJsonObject();
-        }
-        params.insert(QLatin1String(kParamKeys[i]), static_cast<double>(value));
-    }
-
-    for (int i = 0; i < kParamCheckCount; ++i) {
-        const QCheckBox *chk = m_ui->tabPageParam->findChild<QCheckBox *>(
-            QStringLiteral("paramCheck_2_%1").arg(3 + i));
-        if (chk)
-            params.insert(QLatin1String(kParamChecks[i]), chk->isChecked());
-    }
-
-    const QJsonObject stationPlan = LocalPlans().plan(qMax(0, m_index));
-    if (m_stageToggled || stationPlan.contains(QStringLiteral("run_rmt"))
-        || stationPlan.contains(QStringLiteral("run_amt"))
-        || stationPlan.contains(QStringLiteral("run_mt"))) {
-        if (m_chkRmt) params.insert(QStringLiteral("run_rmt"), m_chkRmt->isChecked());
-        if (m_chkAmt) params.insert(QStringLiteral("run_amt"), m_chkAmt->isChecked());
-        if (m_chkMt)  params.insert(QStringLiteral("run_mt"),  m_chkMt->isChecked());
-    }
-
-    return params;
-}
-
-void DetailView::submitParams()
-{
-    if (m_index < 0)
-        return;
-
-    bool valid = false;
-    const QJsonObject params = collectParams(&valid);
-    if (!valid) return;
-    qInfo().noquote() << "[param] 工位" << m_index + 1 << "点确定,收集到"
-                      << params.count() << "项内存参数,保存到 Qt 本地计划";
-    emit paramsSubmitted(m_index, params);
-}
-
-// ---------------------------------------------------------------------------
-// 通道切换:点 24 通道卡片里的任意格子,曲线切到该通道
-// ---------------------------------------------------------------------------
-bool DetailView::eventFilter(QObject *watched, QEvent *event)
-{
-    if (event->type() == QEvent::MouseButtonRelease) {
-        QMouseEvent *me = static_cast<QMouseEvent *>(event);
-        if (me->button() == Qt::LeftButton) {
-            const QString name = watched->objectName();
-            if (name.startsWith(QLatin1String("chCell_")))
-                selectCurveChannel(name.mid(7));   // 去掉 "chCell_" 前缀
-        }
-    }
-    return QObject::eventFilter(watched, event);
-}
-
-void DetailView::selectCurveChannel(const QString &name)
-{
-    if (m_curveChannel == name || name.isEmpty())
-        return;
-
-    m_curveChannel = name;
-    markCurveChannel();
-    renderCurve();
-}
-
-void DetailView::markCurveChannel()
-{
-    const QString want = QStringLiteral("chCell_") + m_curveChannel;
-    for (QFrame *f : m_cellFrames) {
-        const bool on = (f->objectName() == want);
-        if (f->property("selected").toBool() == on)
-            continue;
-        f->setProperty("selected", on);
-        f->style()->unpolish(f);
-        f->style()->polish(f);
-    }
-}
-
-// ---------------------------------------------------------------------------
-// 温控曲线:QCustomPlot,横轴最近 200 个采样点,纵轴 20~90 °C
-// 样式全部在这里设,.ui 里只有控件本体
-// ---------------------------------------------------------------------------
-void DetailView::setupCurvePlot()
-{
-    QCustomPlot *p = m_ui->curvePlot;
-    if (!p)
-        return;
-
-    p->setBackground(QBrush(QColor("#ffffff")));
-    p->setNoAntialiasingOnDrag(true);
-
-    QFont font = p->font();
-    font.setPointSize(9);
-    p->setFont(font);
-
-    const QColor axisColor("#c6d2df");
-    const QColor subTickColor("#dde5ee");
-    const QColor labelColor("#6b7d90");
-    const QColor gridColor("#eef2f7");
-
-    for (QCPAxis *ax : {p->xAxis, p->yAxis}) {
-        ax->setBasePen(QPen(axisColor, 1));
-        ax->setTickPen(QPen(axisColor, 1));
-        ax->setSubTickPen(QPen(subTickColor, 1));
-        ax->setTickLabelColor(labelColor);
-        ax->setLabelColor(labelColor);
-        ax->setTickLength(0, 4);
-        ax->grid()->setPen(QPen(gridColor, 1, Qt::DotLine));
-        ax->grid()->setSubGridVisible(false);
-        ax->grid()->setZeroLinePen(Qt::NoPen);
-    }
-
-    p->xAxis->setLabel(QStringLiteral("采样点"));
-    p->yAxis->setLabel(QStringLiteral("温度 (°C)"));
-    p->xAxis->setRange(0, kTempHistorySize);
-    p->yAxis->setRange(20, 90);
-    p->xAxis->ticker()->setTickCount(6);      // 0 / 40 / 80 / 120 / 160 / 200
-    p->yAxis->ticker()->setTickCount(8);      // 20 ~ 90,每 10 一格
-    p->xAxis->setSubTicks(false);
-    p->yAxis->setSubTicks(false);
-
-    // 用 CurveGraph 代替 addGraph():曲线画法不变,只是把图例里的小色块换成圆头短棒
-    QCPGraph *g = new CurveGraph(p->xAxis, p->yAxis);
-    g->setPen(QPen(QColor("#2f7fc1"), 1.6));
-    g->setLineStyle(QCPGraph::lsLine);
-    g->setScatterStyle(QCPScatterStyle::ssNone);
-    g->setAntialiased(true);
-    g->setName(QStringLiteral("腔体温度"));       // 曲线名,进详情页后会换成「工位号 · 腔体温度」
-
-    // 图例:右上角白色小框,曲线名由 renderCurve() 随工位更新
-    QCPLegend *lg = p->legend;
-    lg->setVisible(true);
-    lg->setBrush(QBrush(QColor(255, 255, 255, 225)));
-    lg->setBorderPen(QPen(QColor("#dde5ee")));
-    lg->setTextColor(QColor("#5d7086"));
-    lg->setFont(font);
-    // 图标框取整行高(这样它在图例行里就是垂直居中的),
-    // 色块本身再按字体度量放进去:高度 = 大写字母高度,顶边 = ascent - capHeight
-    const QFontMetrics lgFm(font);
-    g_swatchH = qMax(8, lgFm.capHeight());
-    g_swatchTop = qMax(0, lgFm.ascent() - lgFm.capHeight());
-    lg->setIconSize(20, lgFm.height());
-    lg->setIconTextPadding(6);
-    lg->setRowSpacing(0);
-    p->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);
-
-    // 最新点:一个白底蓝边的小圆点 + 下面的温度数值(跟着数据一起走,见 renderCurve)
-    m_lastDot = new QCPItemTracer(p);
-    m_lastDot->setGraph(g);
-    m_lastDot->setStyle(QCPItemTracer::tsCircle);
-    m_lastDot->setSize(5);
-    m_lastDot->setPen(QPen(QColor("#2f7fc1"), 1.6));
-    m_lastDot->setBrush(QBrush(Qt::white));
-    m_lastDot->setSelectable(false);
-    m_lastDot->setClipToAxisRect(false);
-
-    m_lastLabel = new QCPItemText(p);
-    m_lastLabel->setSelectable(false);
-    m_lastLabel->setClipToAxisRect(false);
-    m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignHCenter);
-    m_lastLabel->position->setType(QCPItemPosition::ptPlotCoords);
-    m_lastLabel->setPadding(QMargins(2, 6, 2, 1));   // 上边多留点,让标签离开圆点
-    m_lastLabel->setPen(Qt::NoPen);
-    m_lastLabel->setBrush(Qt::NoBrush);              // 不要底色块,只留文字
-    m_lastLabel->setColor(QColor("#2f7fc1"));
-    {
-        QFont lf = font;
-        lf.setPointSizeF(8.5);
-        lf.setBold(true);
-        m_lastLabel->setFont(lf);
-    }
-
-    p->replot();
-}
-
-void DetailView::renderCurve()
-{
-    if (m_index < 0 || m_index >= m_store->count())
-        return;
-
-    QCustomPlot *p = m_ui->curvePlot;
-    if (!p || p->graphCount() == 0)
-        return;
-
-    const StationData &d = m_store->station(m_index);
-
-    // 找当前选中的通道;工位换了但通道名还在(24 个通道各工位同名),所以直接按名字找
-    const ChannelInfo *sel = nullptr;
-    for (const ChannelInfo &c : d.channels) {
-        if (c.name == m_curveChannel) {
-            sel = &c;
-            break;
-        }
-    }
-    if (!sel && !d.channels.isEmpty())
-        sel = &d.channels.first();
-    if (!sel)
-        return;
-
-    const int n = sel->history.size();
-    const int start = sel->historyStart;
-
-    QVector<double> keys(n);
-    QVector<double> values(n);
-    for (int i = 0; i < n; ++i) {
-        keys[i] = start + i;             // 全局采样序号,不回绕
-        values[i] = sel->history.at(i);
-    }
-
-    QCPGraph *g = p->graph(0);
-    g->setData(keys, values, true);
-
-    // 图例显示通道名:CPU0_CHA
-    if (g->name() != sel->name)
-        g->setName(sel->name);
-
-    // 横轴滚动:可见宽度恒为 kTempHistorySize 点,起点跟着最新数据走(刻度数字会一起滚)
-    double lo = start;
-    if (n < kTempHistorySize)
-        lo = 0;                          // 还没满 200 点时从 0 开始铺,不从负数起
-    p->xAxis->setRange(lo, lo + kTempHistorySize);
-
-    // 最新点标记 + 数值标签:贴在最后一个采样点下方
-    if (m_lastDot && m_lastLabel && n > 0) {
-        const double k = keys.last();
-        const double v = values.last();
-
-        m_lastDot->setGraphKey(k);
-        m_lastDot->setVisible(true);
-
-        m_lastLabel->setText(QStringLiteral("%1°C").arg(QString::number(v, 'f', 1)));
-        m_lastLabel->position->setCoords(k, v);
-        m_lastLabel->setVisible(true);
-
-        // 点贴近轴的右边缘时改成右对齐,否则标签会甩到图外
-        const double px = p->xAxis->coordToPixel(k);
-        const QRect rect = p->axisRect()->rect();
-        if (px > rect.right() - 40)
-            m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignRight);
-        else if (px < rect.left() + 40)
-            m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignLeft);
-        else
-            m_lastLabel->setPositionAlignment(Qt::AlignTop | Qt::AlignHCenter);
-    } else if (m_lastDot && m_lastLabel) {
-        m_lastDot->setVisible(false);
-        m_lastLabel->setVisible(false);
-    }
-
-    p->replot(QCustomPlot::rpQueuedReplot);
-}
-
-void DetailView::onTemperatureChanged(int index)
-{
-    if (index != m_index)
-        return; // 不在当前工位:数据留在模型里,切回来整体重铺
-    if (m_ui->detailTabStack->currentIndex() != 0)
-        return; // 曲线页没显示,画了也看不见
-
-    renderCurve();
-}
-
-void DetailView::cacheChannelWidgets()
-{
-    m_cellFrames.clear();
-    m_cellValues.clear();
-
-    const QStringList names = channelNames();
-    for (const QString &name : names) {
-        QFrame *frame = m_ui->detailPage->findChild<QFrame *>(QStringLiteral("chCell_") + name);
-        QLabel *value = m_ui->detailPage->findChild<QLabel *>(QStringLiteral("chCellValue_") + name);
-        if (!frame || !value)
-            continue;
-
-        // 点通道格子 → 曲线切到该通道
-        frame->installEventFilter(this);
-        frame->setCursor(Qt::PointingHandCursor);
-        m_cellFrames.append(frame);
-        m_cellValues.append(value);
-    }
-}
-
-// ---------------------------------------------------------------------------
-// 打开 / 关闭
-// ---------------------------------------------------------------------------
-void DetailView::showStation(int index)
-{
-    if (index < 0 || index >= m_store->count())
-        return;
-
-    m_index = index;
-    loadParamConfig();
-    m_ui->pageStack->setCurrentIndex(1);
-
-    // 纯内存渲染,不依赖任何异步取数 —— 点开即出
-    markCurveChannel();      // 高亮当前曲线对应的通道(默认 CPU0_CHA)
-    renderAll();
-}
-
-void DetailView::leave()
-{
-    m_index = -1;
-    m_flush.stop();
-    m_needTitle = m_needChannels = false;
-}
-
-// ---------------------------------------------------------------------------
-// 全量渲染(首次进入 / 切换工位)
-// ---------------------------------------------------------------------------
-void DetailView::renderAll()
-{
-    renderTitle();
-    renderChannels();
-    renderCurve();
-    renderLogs();
-}
-
-void DetailView::renderTitle()
-{
-    // 标题栏同步显示工位号与当前阶段,与总览卡片头部保持一致
-    const StationData &d = m_store->station(m_index);
-    const QString title = d.deviceId.isEmpty()
-        ? QStringLiteral("—")
-        : (d.deviceId + (d.phase.isEmpty() ? QString() : QStringLiteral(" · ") + d.phase.toUpper()));
-    m_ui->detailDevice->setText(title);
-    if (m_ui->tabPageAlarmHint) {
-        m_ui->tabPageAlarmHint->setText(
-            d.alarms.isEmpty() ? QStringLiteral("暂无异常记录") : d.alarms.join(QLatin1Char('\n')));
-    }
-}
-
-void DetailView::renderChannels()
-{
-    const StationData &d = m_store->station(m_index);
-    const int n = qMin(m_cellFrames.size(), d.channels.size());
-    for (int i = 0; i < n; ++i) {
-        const ChannelInfo &ch = d.channels.at(i);
-
-        QString text;
-        QString state;
-        const QString tempText = (ch.temperature >= 0.0)
-            ? QStringLiteral("%1 ℃").arg(QString::number(ch.temperature, 'f', 1))
-            : QString();
-        if (ch.state == ChannelInfo::Fail) {
-            state = QStringLiteral("fail");
-            text = tempText.isEmpty() ? QStringLiteral("FAIL") : QStringLiteral("FAIL · %1").arg(tempText);
-        } else if (ch.state == ChannelInfo::Pass) {
-            state = QStringLiteral("pass");
-            text = tempText.isEmpty() ? QStringLiteral("PASS") : QStringLiteral("PASS · %1").arg(tempText);
-        } else if (ch.temperature >= 0.0 || ch.present) {
-            state = QStringLiteral("loaded");
-            text = tempText.isEmpty() ? QStringLiteral("ONLINE") : tempText;
-        } else {
-            state = QStringLiteral("idle");
-            text = QStringLiteral("--℃");
-        }
-        m_cellValues[i]->setText(text);
-
-        QFrame *frame = m_cellFrames[i];
-        if (frame->property("state").toString() == state)
-            continue;
-
-        frame->setProperty("state", state);
-        // 兜底重刷:QSS 里值文字的颜色挂在父框的 state 上
-        frame->style()->unpolish(frame);
-        frame->style()->polish(frame);
-        m_cellValues[i]->style()->unpolish(m_cellValues[i]);
-        m_cellValues[i]->style()->polish(m_cellValues[i]);
-    }
-}
-
-void DetailView::renderLogs()
-{
-    const StationData &d = m_store->station(m_index);
-    QPlainTextEdit *log = m_ui->detailLog;
-    const int total = d.logs.size();
-
-    if (m_logStation == m_index && total >= m_logLines) {
-        // 同一工位:只把新增的尾巴整块追加进去。
-        // 实测 7.5 万行:整块 append 约 0.2s,逐行 append 会退化到 13s 以上,
-        // 所以这里必须一次性插入,绝不能 for 循环 appendPlainText。
-        if (total > m_logLines) {
-            log->appendPlainText(d.logs.mid(m_logLines).join(QLatin1Char('\n')));
-            m_logLines = total;
-        }
-    } else {
-        // 换工位:整篇重铺(7.5 万行约 0.4s,属可接受的一次性开销)
-        log->setPlainText(d.logs.join(QLatin1Char('\n')));
-        m_logStation = m_index;
-        m_logLines = total;
-    }
-
-    log->verticalScrollBar()->setValue(log->verticalScrollBar()->maximum());
-}
-
-void DetailView::selectTab(int index)
-{
-    QPushButton *tabs[kTabCount] = {m_ui->detailTab_0, m_ui->detailTab_1, m_ui->detailTab_2};
-    for (int i = 0; i < kTabCount; ++i) {
-        tabs[i]->setProperty("active", i == index ? QStringLiteral("true") : QStringLiteral("false"));
-        tabs[i]->style()->unpolish(tabs[i]);
-        tabs[i]->style()->polish(tabs[i]);
-    }
-    m_ui->detailTabStack->setCurrentIndex(index);
-
-    if (index == 0)      // 切回曲线页时补画一次,避免看到离开期间的旧曲线
-        renderCurve();
-}
-
-// ---------------------------------------------------------------------------
-// 实时刷新:日志走快路径,其余 120ms 合并
-// ---------------------------------------------------------------------------
-void DetailView::onLogAppended(int index, const QString &line)
-{
-    if (index != m_index)
-        return; // 不在当前工位:只留在模型里,切回来时一次性铺全
-
-    QPlainTextEdit *log = m_ui->detailLog;
-    QScrollBar *bar = log->verticalScrollBar();
-    const bool follow = (bar->value() >= bar->maximum() - 4); // 用户往上翻就不抢滚动条
-
-    log->appendPlainText(line);
-    m_logStation = index;
-    m_logLines = m_store->station(index).logs.size();
-
-    if (follow)
-        bar->setValue(bar->maximum());
-}
-
-void DetailView::onChannelsChanged(int index)
-{
-    if (index != m_index)
-        return;
-    m_needChannels = true;
-    requestFlush();
-}
-
-void DetailView::onInfoChanged(int index)
-{
-    if (index != m_index)
-        return;
-    m_needTitle = true;   // 标题栏的工位号跟着任务信息一起变
-    requestFlush();
-}
-
-void DetailView::requestFlush()
-{
-    if (!m_flush.isActive())
-        m_flush.start();
-}
-
-void DetailView::flushPending()
-{
-    if (m_index < 0)
-        return;
-
-    if (m_needTitle) {
-        m_needTitle = false;
-        renderTitle();
-    }
-    if (m_needChannels) {
-        m_needChannels = false;
-        renderChannels();
-        // 曲线看的是通道温度,所以通道数据一变也要重画(只在曲线页可见时做)
-        if (m_ui->detailTabStack->currentIndex() == 0)
-            renderCurve();
-    }
-}

+ 0 - 167
qt-client/src/localplans.cpp

@@ -1,167 +0,0 @@
-#include "localplans.h"
-
-#include "appconfig.h"
-
-#include <QCoreApplication>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QJsonDocument>
-#include <QSaveFile>
-
-LocalPlans::LocalPlans()
-{
-    const QString configPath = appConfigPath(QStringLiteral("config.json"));
-    QFile config(configPath);
-    if (config.open(QIODevice::ReadOnly))
-        m_defaults = QJsonDocument::fromJson(config.readAll()).object();
-    m_path = qEnvironmentVariable("STL_QT_PLANS_FILE");
-    if (m_path.isEmpty()) {
-        const QDir dir(configPath.isEmpty() ? QCoreApplication::applicationDirPath()
-                                          : QFileInfo(configPath).absolutePath());
-        m_path = dir.filePath(QStringLiteral("qt-plans.json"));
-    }
-}
-
-QJsonObject LocalPlans::read() const
-{
-    QFile file(m_path);
-    return file.open(QIODevice::ReadOnly)
-        ? QJsonDocument::fromJson(file.readAll()).object() : QJsonObject();
-}
-
-QJsonObject LocalPlans::plan(int station) const
-{
-    QJsonObject result = m_defaults.value(QStringLiteral("qtPlan")).toObject();
-    if (!result.contains(QStringLiteral("memory_params")))
-        result.insert(QStringLiteral("memory_params"), m_defaults.value(QStringLiteral("memoryParams")));
-    const QJsonObject saved = read().value(QStringLiteral("stations")).toObject()
-                                  .value(QStringLiteral("S%1").arg(station + 1)).toObject();
-    for (auto it = saved.constBegin(); it != saved.constEnd(); ++it)
-        result.insert(it.key(), it.value());
-    return result;
-}
-
-QJsonObject LocalPlans::memoryParams(int station) const
-{
-    return plan(station).value(QStringLiteral("memory_params")).toObject();
-}
-
-bool LocalPlans::saveMemoryParams(int station, const QJsonObject &params, QString *error)
-{
-    if (station < 0 || station >= 4) {
-        if (error) *error = QStringLiteral("工位编号无效");
-        return false;
-    }
-    QJsonObject root = read();
-    QJsonObject stations = root.value(QStringLiteral("stations")).toObject();
-    QJsonObject value = plan(station);
-    QJsonObject mergedParams = params;
-    const QJsonObject previousParams = value.value(QStringLiteral("memory_params")).toObject();
-    const QStringList preservedKeys = {
-        QStringLiteral("rmt"), QStringLiteral("run_rmt"),
-        QStringLiteral("amt"), QStringLiteral("admt"), QStringLiteral("run_amt"),
-        QStringLiteral("mt"), QStringLiteral("run_mt")
-    };
-    for (const QString &key : preservedKeys) {
-        if (!mergedParams.contains(key) && previousParams.contains(key))
-            mergedParams.insert(key, previousParams.value(key));
-    }
-    value.insert(QStringLiteral("memory_params"), mergedParams);
-    QJsonObject uip = value.value(QStringLiteral("uip")).toObject();
-    uip.insert(QStringLiteral("action"), QStringLiteral("continue_uip"));
-    uip.insert(QStringLiteral("apply_memory_params"), true);
-    if (mergedParams.contains(QStringLiteral("run_rmt"))) {
-        const bool rmt = mergedParams.value(QStringLiteral("run_rmt")).toBool(true);
-        value.insert(QStringLiteral("run_rmt"), rmt);
-        uip.insert(QStringLiteral("run_rmt"), rmt);
-    }
-    value.insert(QStringLiteral("uip"), uip);
-    if (mergedParams.contains(QStringLiteral("run_amt"))) {
-        const bool amtOn = mergedParams.value(QStringLiteral("run_amt")).toBool(true);
-        value.insert(QStringLiteral("run_amt"), amtOn);
-        QJsonObject amtObj = value.value(QStringLiteral("amt")).toObject();
-        amtObj.insert(QStringLiteral("run_amt"), amtOn);
-        amtObj.insert(QStringLiteral("action"), amtOn ? QStringLiteral("start_amt") : QStringLiteral("skip_amt"));
-        amtObj.insert(QStringLiteral("exit_after"), true);
-        if (!amtObj.contains(QStringLiteral("test_command")))
-            amtObj.insert(QStringLiteral("test_command"), QStringLiteral("amemdiag 1"));
-        value.insert(QStringLiteral("amt"), amtObj);
-    }
-    if (mergedParams.contains(QStringLiteral("run_mt"))) {
-        const bool mtOn = mergedParams.value(QStringLiteral("run_mt")).toBool(true);
-        value.insert(QStringLiteral("run_mt"), mtOn);
-        QJsonObject uefiObj = value.value(QStringLiteral("uefi")).toObject();
-        uefiObj.insert(QStringLiteral("run_mt"), mtOn);
-        uefiObj.insert(QStringLiteral("action"), mtOn ? QStringLiteral("start_mt") : QStringLiteral("skip_mt"));
-        QJsonObject settings = uefiObj.value(QStringLiteral("settings")).toObject();
-        if (settings.value(QStringLiteral("efi_path")).toString().isEmpty())
-            settings.insert(QStringLiteral("efi_path"), QStringLiteral("118.efi"));
-        uefiObj.insert(QStringLiteral("settings"), settings);
-        value.insert(QStringLiteral("uefi"), uefiObj);
-    }
-    stations.insert(QStringLiteral("S%1").arg(station + 1), value);
-    root.insert(QStringLiteral("version"), 1);
-    root.insert(QStringLiteral("stations"), stations);
-
-    QSaveFile file(m_path);
-    const QByteArray bytes = QJsonDocument(root).toJson(QJsonDocument::Indented);
-    if (!file.open(QIODevice::WriteOnly) || file.write(bytes) != bytes.size() || !file.commit()) {
-        if (error) *error = file.errorString();
-        return false;
-    }
-    return true;
-}
-
-bool LocalPlans::saveStageToggles(int station, bool runRmt, bool runAmt, bool runMt, QString *error)
-{
-    if (station < 0 || station >= 4) {
-        if (error) *error = QStringLiteral("工位编号无效");
-        return false;
-    }
-    QJsonObject root = read();
-    QJsonObject stations = root.value(QStringLiteral("stations")).toObject();
-    QJsonObject value = plan(station);
-    QJsonObject mem = value.value(QStringLiteral("memory_params")).toObject();
-    mem.insert(QStringLiteral("run_rmt"), runRmt);
-    mem.insert(QStringLiteral("run_amt"), runAmt);
-    mem.insert(QStringLiteral("run_mt"), runMt);
-    value.insert(QStringLiteral("memory_params"), mem);
-    value.insert(QStringLiteral("run_rmt"), runRmt);
-    value.insert(QStringLiteral("run_amt"), runAmt);
-    value.insert(QStringLiteral("run_mt"), runMt);
-
-    QJsonObject uip = value.value(QStringLiteral("uip")).toObject();
-    uip.insert(QStringLiteral("action"), QStringLiteral("continue_uip"));
-    uip.insert(QStringLiteral("run_rmt"), runRmt);
-    value.insert(QStringLiteral("uip"), uip);
-
-    QJsonObject amtObj = value.value(QStringLiteral("amt")).toObject();
-    amtObj.insert(QStringLiteral("run_amt"), runAmt);
-    amtObj.insert(QStringLiteral("action"), runAmt ? QStringLiteral("start_amt") : QStringLiteral("skip_amt"));
-    amtObj.insert(QStringLiteral("exit_after"), true);
-    if (!amtObj.contains(QStringLiteral("test_command")))
-        amtObj.insert(QStringLiteral("test_command"), QStringLiteral("amemdiag 1"));
-    value.insert(QStringLiteral("amt"), amtObj);
-
-    QJsonObject uefiObj = value.value(QStringLiteral("uefi")).toObject();
-    uefiObj.insert(QStringLiteral("run_mt"), runMt);
-    uefiObj.insert(QStringLiteral("action"), runMt ? QStringLiteral("start_mt") : QStringLiteral("skip_mt"));
-    QJsonObject settings = uefiObj.value(QStringLiteral("settings")).toObject();
-    if (settings.value(QStringLiteral("efi_path")).toString().isEmpty())
-        settings.insert(QStringLiteral("efi_path"), QStringLiteral("118.efi"));
-    uefiObj.insert(QStringLiteral("settings"), settings);
-    value.insert(QStringLiteral("uefi"), uefiObj);
-
-    stations.insert(QStringLiteral("S%1").arg(station + 1), value);
-    root.insert(QStringLiteral("version"), 1);
-    root.insert(QStringLiteral("stations"), stations);
-
-    QSaveFile file(m_path);
-    const QByteArray bytes = QJsonDocument(root).toJson(QJsonDocument::Indented);
-    if (!file.open(QIODevice::WriteOnly) || file.write(bytes) != bytes.size() || !file.commit()) {
-        if (error) *error = file.errorString();
-        return false;
-    }
-    return true;
-}

+ 0 - 25
qt-client/src/localplans.h

@@ -1,25 +0,0 @@
-#ifndef LOCALPLANS_H
-#define LOCALPLANS_H
-
-#include <QJsonObject>
-#include <QString>
-
-// Qt owns these plans. No backend plan CRUD is used.
-// Saving the parameter form changes only this local file; Start reads it afresh.
-class LocalPlans
-{
-public:
-    LocalPlans();
-    QJsonObject plan(int station) const;
-    QJsonObject memoryParams(int station) const;
-    bool saveMemoryParams(int station, const QJsonObject &params, QString *error = nullptr);
-    bool saveStageToggles(int station, bool runRmt, bool runAmt, bool runMt, QString *error = nullptr);
-    QString path() const { return m_path; }
-
-private:
-    QJsonObject read() const;
-    QString m_path;
-    QJsonObject m_defaults;
-};
-
-#endif

+ 0 - 65
qt-client/src/main.cpp

@@ -1,65 +0,0 @@
-#include "mainwindow.h"
-
-#include <QApplication>
-#include <QDebug>
-#include <QFile>
-#include <QFont>
-#include <QFontDatabase>
-#include <QStringList>
-
-/* 跨平台中文字体回退:按优先级挑选系统上实际存在的字体 */
-static void applyAppFont(QApplication &app)
-{
-    const QStringList prefer = QStringList()
-        << QStringLiteral("Microsoft YaHei UI")
-        << QStringLiteral("Microsoft YaHei")
-        << QStringLiteral("PingFang SC")
-        << QStringLiteral("Noto Sans CJK SC")
-        << QStringLiteral("Source Han Sans SC")
-        << QStringLiteral("WenQuanYi Micro Hei")
-        << QStringLiteral("Segoe UI");
-
-    QFontDatabase db;
-    const QStringList installed = db.families();
-
-    QFont f = app.font();
-    for (int i = 0; i < prefer.size(); ++i) {
-        if (installed.contains(prefer.at(i))) {
-            f.setFamily(prefer.at(i));
-            break;
-        }
-    }
-    f.setPointSize(9);
-    f.setStyleStrategy(QFont::PreferAntialias);
-    app.setFont(f);
-}
-
-/* 从 Qt 资源中加载全局样式表(src/style/app.qss) */
-static void applyStyleSheet(QApplication &app)
-{
-    QFile f(QStringLiteral(":/style/app.qss"));
-    if (f.open(QIODevice::ReadOnly | QIODevice::Text))
-        app.setStyleSheet(QString::fromUtf8(f.readAll()));
-}
-
-int main(int argc, char *argv[])
-{
-#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
-    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
-    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
-#endif
-
-    QApplication app(argc, argv);
-    app.setApplicationName(QStringLiteral("HOVSE SLT Pro"));
-    app.setApplicationVersion(QStringLiteral("0.8.1.17"));
-    app.setOrganizationName(QStringLiteral("XJKJ"));
-
-    applyAppFont(app);
-    applyStyleSheet(app);
-
-    MainWindow w;
-
-    w.showMaximizedArea(); // 启动即铺满屏幕可用区域,右上角 ❐ 可还原
-
-    return app.exec();
-}

+ 0 - 423
qt-client/src/mainwindow.cpp

@@ -1,423 +0,0 @@
-#include "mainwindow.h"
-
-#include "ui_mainwindow.h"
-#include "appconfig.h"
-#include "backendlink.h"
-#include "localplans.h"
-#include "comanager.h"
-#include "comworker.h"
-#include "detailview.h"
-#include "overviewview.h"
-#include "stationdata.h"
-
-#include <QAbstractButton>
-#include <QCoreApplication>
-#include <QDateTime>
-#include <QDebug>
-#include <QDir>
-#include <QEvent>
-#include <QFile>
-#include <QFileInfo>
-#include <QGuiApplication>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QLabel>
-#include <QMouseEvent>
-#include <QPushButton>
-#include <QResizeEvent>
-#include <QScreen>
-#include <QSizeGrip>
-#include <QStyle>
-
-MainWindow::MainWindow(QWidget *parent)
-    : QMainWindow(parent)
-    , ui(new Ui::MainWindow)
-    , m_grip(nullptr)
-    , m_dragging(false)
-    , m_maximized(false)
-    , m_store(nullptr)
-    , m_backend(nullptr)
-    , m_overview(nullptr)
-    , m_detail(nullptr)
-    , m_com(nullptr)
-{
-    ui->setupUi(this);
-
-    // 让工位卡网格占满内容区剩余高度
-    ui->contentBody->setStretch(1, 1);
-
-    // 无边框窗口:标题栏由 .ui 中的 header 绘制,窗口按钮自己实现
-    setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
-    setWindowTitle(QStringLiteral("HOVSE SLT Pro"));
-
-    connect(ui->btnWinMin, &QPushButton::clicked, this, &MainWindow::onMinimize);
-    connect(ui->btnWinMax, &QPushButton::clicked, this, &MainWindow::onMaximize);
-    connect(ui->btnWinClose, &QPushButton::clicked, this, &MainWindow::onClose);
-
-    // 按住标题栏任意空白处可拖动窗口(按钮区域除外),双击最大化/还原
-    watchDrag(ui->header);
-
-    // 右下角缩放手柄(无边框窗口需要自己提供)
-    m_grip = new QSizeGrip(ui->centralwidget);
-    m_grip->setFixedSize(16, 16);
-    m_grip->raise();
-
-    // 数据层:模型在后台持续累积,详情页只负责展示
-    // 数据来源:温度走串口协议(ComWorker),通道测试状态(PASS/IDLE)等由后端下发
-    m_store = new StationStore(4, this);
-    m_overview = new OverviewView(ui, m_store, this);
-    // 整卡点击进详情页已移除:只保留卡头「查看详情 >」按钮(见 setupDetail)
-    connect(m_overview, &OverviewView::startTestRequested, this, &MainWindow::startTest);
-    m_detail = new DetailView(ui, m_store, this);
-    connect(m_detail, &DetailView::backRequested, this, &MainWindow::backToMonitor);
-
-    // Qt owns its local plans; the backend pushes curated state and log events.
-    m_backend = new BackendLink(this);
-    connect(m_backend, &BackendLink::logLine, this, [this](int station, const QString &line) {
-        m_store->appendLog(station, line);
-    });
-    connect(m_backend, &BackendLink::stationState, this, [this](int station, const QJsonObject &state) {
-        m_store->applyBackendState(station, state);
-        m_store->setBackendLink(station, m_backend->isConnected(), m_backend->isBusy(station));
-    });
-    connect(m_backend, &BackendLink::connectionChanged, this, [this](bool connected) {
-        for (int i = 0; i < m_store->count(); ++i)
-            m_store->setBackendLink(i, connected, m_backend->isBusy(i));
-    });
-    connect(m_backend, &BackendLink::commandFinished, this, [this](int station, const QString &, bool, const QString &) {
-        m_store->setBackendLink(station, m_backend->isConnected(), m_backend->isBusy(station));
-    });
-    connect(m_detail, &DetailView::paramsSubmitted, this, &MainWindow::saveLocalParams);
-    connect(m_detail, &DetailView::stageTogglesChanged, this, [this](int station, bool rmt, bool amt, bool mt) {
-        LocalPlans plans;
-        QString error;
-        if (plans.saveStageToggles(station, rmt, amt, mt, &error)) {
-            m_backend->refreshPlan(station);
-            qInfo().noquote() << "[param] 工位" << station + 1 << "阶段开关已更新:RMT=" << rmt << "AMT=" << amt << "MT=" << mt;
-        }
-    });
-
-    setupDetail();
-    setupCom();
-    m_backend->start();
-
-    // 空态初始化:工位号固定 SLT-HT-001~004;24 个通道一律 IDLE,
-    // 任务号 / 产品 / 模式等留空,等后端接入后填充
-    const QStringList deviceIds = {QStringLiteral("SLT-HT-001"), QStringLiteral("SLT-HT-002"),
-                                   QStringLiteral("SLT-HT-003"), QStringLiteral("SLT-HT-004")};
-    for (int i = 0; i < m_store->count(); ++i) {
-        StationData d;
-        if (i < deviceIds.size())
-            d.deviceId = deviceIds.at(i);
-        for (const QString &name : channelNames())
-            d.channels.append(ChannelInfo(name, -1.0, ChannelInfo::Idle));
-        m_store->initStation(i, d);
-    }
-
-    centerOnScreen();
-}
-
-MainWindow::~MainWindow()
-{
-    // Close the socket while all UI/model objects are still alive. QObject's
-    // automatic child destruction happens after this body and after delete ui.
-    delete m_backend;
-    m_backend = nullptr;
-    // ComManager 析构里会停扫描、关串口、退线程
-    delete m_com;
-    m_com = nullptr;
-
-    delete ui;
-}
-
-// ---------------------------------------------------------------------------
-// 多机监控 ⇄ 设备详情页
-// ---------------------------------------------------------------------------
-void MainWindow::setupDetail()
-{
-    QPushButton *detailButtons[4] = {ui->cardDetail_0, ui->cardDetail_1, ui->cardDetail_2,
-                                     ui->cardDetail_3};
-    for (int i = 0; i < 4; ++i) {
-        connect(detailButtons[i], &QPushButton::clicked, this, [this, i] { openDetail(i); });
-    }
-
-    ui->pageStack->setCurrentIndex(0);
-}
-
-void MainWindow::openDetail(int index)
-{
-    // 详情页用模型里的缓存数据同步渲染,点开即出,不等下一次采样
-    m_detail->showStation(index);
-}
-
-void MainWindow::backToMonitor()
-{
-    m_detail->leave();
-    ui->pageStack->setCurrentIndex(0);
-}
-
-void MainWindow::startTest(int index)
-{
-    if (index < 0 || index >= m_store->count()) return;
-    if (m_backend->startTest(index)) {
-        for (int ch = 0; ch < 24; ++ch)
-            m_store->setChannelState(index, ch, ChannelInfo::Idle, -1.0);
-    }
-    m_store->setBackendLink(index, m_backend->isConnected(), m_backend->isBusy(index));
-}
-
-void MainWindow::saveLocalParams(int index, const QJsonObject &params)
-{
-    if (index < 0 || index >= m_store->count()) return;
-    LocalPlans plans;
-    QString error;
-    const bool saved = plans.saveMemoryParams(index, params, &error);
-    if (saved) {
-        m_backend->refreshPlan(index);
-        qInfo().noquote() << "[param] 工位" << index + 1 << "已保存到本工位 Qt 本地计划;下次开始测试在 UIP 阶段应用";
-    }
-    else
-        qWarning().noquote() << "[param] 工位" << index + 1 << "保存失败:" << error;
-}
-
-// ---------------------------------------------------------------------------
-// COM:四工位 USB 转串口连接状态(端口来自 port.json,扫描在 ComWorker 线程)
-// ---------------------------------------------------------------------------
-void MainWindow::setupCom()
-{
-    m_com = new ComManager(this);
-    connect(m_com, &ComManager::stateChanged, this, &MainWindow::onComStateChanged);
-
-    // 温度:串口线程只认字节,换算(取平均 / 0xFF → --℃)全部在 StationStore 里,
-    // 界面不用管数据来源是演示还是真设备,照吃 signals 就行
-    connect(m_com, &ComManager::ctRawArrived, this, [this](int index, const QByteArray &raw) {
-        m_store->applyCtTemperatures(index, raw);
-    });
-    connect(m_com, &ComManager::channelRawArrived, this, [this](int index, const QByteArray &raw) {
-        m_store->applyChannelTemperatures(index, raw);
-    });
-
-    if (qEnvironmentVariable("STL_QT_DISABLE_SERIAL") != QStringLiteral("1"))
-        loadSerialConfig();
-
-    // 先摆上初始状态,等第一次扫描结果回来再刷新
-    for (int i = 0; i < 4; ++i)
-        setComChip(i, ComWorker::Unconfigured, QStringLiteral("COM"), QStringLiteral("等待扫描"));
-
-    m_com->start();
-}
-
-void MainWindow::loadSerialConfig()
-{
-    // 文件名是 port.json(串口专配);config.json 留给内存参数,由 DetailView 读取
-    // 查找规则见 appconfig.h:exe 同级优先,逐级向上找,最后看当前工作目录
-    const QString path = appConfigPath(QStringLiteral("port.json"));
-    if (path.isEmpty()) {
-        qInfo().noquote() << "[com] 未找到 port.json,四个工位串口按未配置处理";
-        return;
-    }
-
-    QFile f(path);
-    if (!f.open(QIODevice::ReadOnly)) {
-        qInfo().noquote() << "[com] 打不开串口配置" << path << f.errorString();
-        return;
-    }
-
-    QJsonParseError err;
-    const QJsonDocument doc = QJsonDocument::fromJson(f.readAll(), &err);
-    if (err.error != QJsonParseError::NoError || !doc.isObject()) {
-        qInfo().noquote() << "[com] 串口配置解析失败" << path << err.errorString();
-        return;
-    }
-
-    const QJsonArray arr = doc.object().value(QStringLiteral("serialPorts")).toArray();
-    qInfo().noquote() << "[com] 配置" << path << "工位串口" << arr.size() << "条";
-
-    for (int i = 0; i < arr.size() && i < 4; ++i) {
-        const QJsonObject o = arr.at(i).toObject();
-        m_com->configure(i,
-                         o.value(QStringLiteral("port")).toString(),
-                         o.value(QStringLiteral("serialNumber")).toString(),
-                         o.value(QStringLiteral("baud")).toInt(115200));
-    }
-}
-
-void MainWindow::onComStateChanged(int index, int state, const QString &portName, const QString &detail)
-{
-    setComChip(index, state, portName, detail);
-}
-
-void MainWindow::setComChip(int index, int state, const QString &portName, const QString &detail)
-{
-    // 每张卡的串口名 / 状态芯片固定为 cardComName_N、cardCom_N,按 index 取
-    QLabel *nameChip = findChild<QLabel *>(QStringLiteral("cardComName_%1").arg(index));
-    QLabel *chip = findChild<QLabel *>(QStringLiteral("cardCom_%1").arg(index));
-    if (!nameChip || !chip) {
-        qInfo().noquote() << "[com] 界面缺少芯片 cardComName_" << index << "/ cardCom_" << index;
-        return;
-    }
-
-    QString prop, text, nameText;
-    switch (state) {
-    case ComWorker::Online:
-        prop = QStringLiteral("online");
-        text = QStringLiteral("● 已连接");
-        nameText = portName;
-        break;
-    case ComWorker::Offline:
-        prop = QStringLiteral("offline");
-        text = QStringLiteral("● 未连接");
-        nameText = portName;    // 配了端口但没插 / 打不开,仍然显示端口名
-        break;
-    default:
-        prop = QStringLiteral("offline");
-        text = QStringLiteral("● 未配置");
-        nameText = QStringLiteral("—");
-        break;
-    }
-
-    nameChip->setText(nameText);
-    chip->setText(text);
-    chip->setProperty("state", prop);
-    // 卡片上不再挂 hover 提示(鼠标扫过卡片会弹框),连接失败原因仍走日志
-    Q_UNUSED(detail);
-    chip->style()->unpolish(chip);
-    chip->style()->polish(chip);
-
-    // 详情页的串口信息跟着实际连接状态走
-    if (m_store && index >= 0 && index < m_store->count() && state != ComWorker::Unconfigured
-        && !portName.isEmpty()) {
-        m_store->setPort(index, portName);
-    }
-}
-
-// ---------------------------------------------------------------------------
-// 窗口外壳
-// ---------------------------------------------------------------------------
-void MainWindow::showMaximizedArea()
-{
-    show();
-    setMaximized(true);
-}
-
-void MainWindow::centerOnScreen()
-{
-    QScreen *screen = QGuiApplication::primaryScreen();
-    if (!screen)
-        return;
-
-    const QRect avail = screen->availableGeometry();
-    const QSize sz = size().boundedTo(avail.size());
-    resize(sz);
-    move(avail.x() + (avail.width() - sz.width()) / 2,
-         avail.y() + (avail.height() - sz.height()) / 2);
-}
-
-void MainWindow::setMaximized(bool on)
-{
-    if (m_maximized == on)
-        return;
-
-    if (on) {
-        m_normalGeometry = geometry();
-
-        QScreen *screen = QGuiApplication::screenAt(frameGeometry().center());
-        if (!screen)
-            screen = QGuiApplication::primaryScreen();
-        if (screen) {
-            const QRect avail = screen->availableGeometry();
-            setGeometry(avail); // 已排除任务栏 / Dock
-        }
-        m_maximized = true;
-    } else {
-        m_maximized = false;
-        setGeometry(m_normalGeometry);
-    }
-
-    if (m_grip)
-        m_grip->setVisible(!m_maximized);
-    ui->btnWinMax->setText(m_maximized ? QStringLiteral("❒") : QStringLiteral("❐"));
-}
-
-void MainWindow::watchDrag(QWidget *root)
-{
-    if (!root)
-        return;
-
-    root->installEventFilter(this);
-    const QList<QWidget *> children = root->findChildren<QWidget *>();
-    for (QWidget *w : children) {
-        if (qobject_cast<QAbstractButton *>(w))
-            continue; // 按钮自行处理鼠标事件
-        w->installEventFilter(this);
-    }
-}
-
-bool MainWindow::eventFilter(QObject *watched, QEvent *event)
-{
-    switch (event->type()) {
-    case QEvent::MouseButtonPress: {
-        QMouseEvent *me = static_cast<QMouseEvent *>(event);
-        if (me->button() == Qt::LeftButton) {
-            m_dragging = true;
-            m_offset = me->globalPos() - frameGeometry().topLeft();
-        }
-        break;
-    }
-    case QEvent::MouseMove: {
-        QMouseEvent *me = static_cast<QMouseEvent *>(event);
-        if (m_dragging && (me->buttons() & Qt::LeftButton)) {
-            if (m_maximized) {
-                // 最大化状态下拖动标题栏:先还原,再让窗口继续跟随鼠标
-                const QPoint global = me->globalPos();
-                setMaximized(false);
-                m_offset = global - frameGeometry().topLeft();
-            }
-            move(me->globalPos() - m_offset);
-            return true;
-        }
-        break;
-    }
-    case QEvent::MouseButtonRelease:
-        m_dragging = false;
-        break;
-    case QEvent::MouseButtonDblClick:
-        toggleMaximized();
-        return true;
-    default:
-        break;
-    }
-
-    return QMainWindow::eventFilter(watched, event);
-}
-
-void MainWindow::resizeEvent(QResizeEvent *event)
-{
-    QMainWindow::resizeEvent(event);
-    if (m_grip) {
-        m_grip->move(ui->centralwidget->width() - m_grip->width(),
-                     ui->centralwidget->height() - m_grip->height());
-        m_grip->raise();
-    }
-}
-
-void MainWindow::toggleMaximized()
-{
-    setMaximized(!m_maximized);
-}
-
-void MainWindow::onMinimize()
-{
-    showMinimized();
-}
-
-void MainWindow::onMaximize()
-{
-    toggleMaximized();
-}
-
-void MainWindow::onClose()
-{
-    close();
-}

+ 0 - 93
qt-client/src/mainwindow.h

@@ -1,93 +0,0 @@
-#ifndef MAINWINDOW_H
-#define MAINWINDOW_H
-
-#include <QJsonObject>
-#include <QMainWindow>
-#include <QPoint>
-#include <QRect>
-#include <QString>
-
-class QSizeGrip;
-class BackendLink;
-class ComManager;
-class StationStore;
-class DetailView;
-class OverviewView;
-
-namespace Ui {
-class MainWindow;
-}
-
-/**
- * 主窗口(主线程)
- * ------------------------------------------------------------------
- * 窗口外壳 + 界面刷新 + 工位串口状态:
- *   · 无边框窗口拖动、最小化/最大化/关闭、右下角缩放
- *   · 四工位 USB 转串口连接状态,按 index 刷新对应工位卡
- *   · 多机监控 ⇄ 设备详情页切换(详情页数据由 StationStore 提供)
- * 通信链路:MainWindow ⇄ ComManager ⇄ ComWorker(QThread)⇄ QSerialPort
- * 数据链路:串口协议 / 后端下发 → StationStore → DetailView → 界面
- */
-class MainWindow : public QMainWindow
-{
-    Q_OBJECT
-
-public:
-    explicit MainWindow(QWidget *parent = nullptr);
-    ~MainWindow() override;
-
-    /** 启动时铺满屏幕可用区域(避开任务栏 / Dock) */
-    void showMaximizedArea();
-
-    /** 数据源只读入口:联调 / 压测时直接灌数据用,界面刷新仍走信号 */
-    StationStore *store() const { return m_store; }
-
-protected:
-    bool eventFilter(QObject *watched, QEvent *event) override;
-    void resizeEvent(QResizeEvent *event) override;
-
-private slots:
-    void onMinimize();
-    void onMaximize();
-    void onClose();
-
-    // ---- 多机监控 ⇄ 设备详情页 ----
-    void openDetail(int index);
-    void backToMonitor();
-
-    // ---- 工位卡右下角「开始测试」圆钮 ----
-    void startTest(int index);
-
-    // ---- COM 串口相关(index = 工位序号 0..3) ----
-    void onComStateChanged(int index, int state, const QString &portName, const QString &detail);
-
-private:
-    void watchDrag(QWidget *root);
-    void toggleMaximized();
-    void setMaximized(bool on);
-    void centerOnScreen();
-
-    void setupCom();
-    void loadSerialConfig();
-    void setComChip(int index, int state, const QString &portName, const QString &detail);
-
-    void setupDetail();
-
-    // Saving the form updates only the Qt-owned per-station plan.
-    void saveLocalParams(int index, const QJsonObject &params);
-
-    Ui::MainWindow *ui;
-    QSizeGrip *m_grip;
-    bool m_dragging;
-    bool m_maximized;
-    QPoint m_offset;
-    QRect m_normalGeometry;
-
-    StationStore *m_store;      // 四工位实时数据(界面只读)
-    BackendLink *m_backend;     // 后端 WebSocket 链路(发参数 / 拉 BIOS 日志)
-    OverviewView *m_overview;   // 多机监控总览视图
-    DetailView *m_detail;       // 设备详情页视图
-    ComManager *m_com;          // 四工位 USB 转串口状态
-};
-
-#endif // MAINWINDOW_H

+ 0 - 103
qt-client/src/powerbutton.cpp

@@ -1,103 +0,0 @@
-#include "powerbutton.h"
-
-#include <QEvent>
-#include <QLinearGradient>
-#include <QPainter>
-#include <QPaintEvent>
-
-PowerButton::PowerButton(QWidget *parent)
-    : QAbstractButton(parent)
-{
-    setCursor(Qt::PointingHandCursor);
-    setFocusPolicy(Qt::NoFocus);          // 键盘焦点交给页面里的输入框,按钮不抢
-    setAttribute(Qt::WA_Hover, true);     // 保证 enterEvent/leaveEvent 可靠触发
-    setToolTip(QStringLiteral("开始测试"));
-    setText(QStringLiteral("开始测试"));   // .ui 里没写 text,构造时给默认文案
-}
-
-QSize PowerButton::sizeHint() const
-{
-    return QSize(74, 64);
-}
-
-QSize PowerButton::minimumSizeHint() const
-{
-    return QSize(64, 58);
-}
-
-void PowerButton::enterEvent(QEvent *event)
-{
-    QAbstractButton::enterEvent(event);
-    update();
-}
-
-void PowerButton::leaveEvent(QEvent *event)
-{
-    QAbstractButton::leaveEvent(event);
-    update();
-}
-
-void PowerButton::paintEvent(QPaintEvent *)
-{
-    QPainter p(this);
-    p.setRenderHint(QPainter::Antialiasing, true);
-
-    // 圆钮:直径取最小边并留出文字的位置,水平居中、贴顶。
-    // 直径 46 + 下面一行 8.5pt 中文(实际需要约 20px 行高)⇒ 控件至少要有 70px 高,
-    // 66px 时最后一排字的下半截会被切掉,所以 infoRow 与按钮高度都按 74 / 72 给足。
-    const qreal d = qMin<qreal>(width() - 8.0, 46.0);
-    const QRectF circle((width() - d) / 2.0, 1.0, d, d);
-
-    QLinearGradient grad(circle.topLeft(), circle.bottomLeft());
-    if (!isEnabled()) {
-        grad.setColorAt(0, QColor("#d4dde6"));
-        grad.setColorAt(1, QColor("#bcc9d6"));
-    } else if (isDown()) {
-        grad.setColorAt(0, QColor("#255f92"));
-        grad.setColorAt(1, QColor("#1a4670"));
-    } else if (underMouse()) {
-        grad.setColorAt(0, QColor("#5aa9e2"));
-        grad.setColorAt(1, QColor("#2f7fc1"));
-    } else {
-        grad.setColorAt(0, QColor("#4a9ad9"));
-        grad.setColorAt(1, QColor("#2a6da8"));
-    }
-
-    p.setBrush(grad);
-    p.setPen(QPen(QColor(255, 255, 255, 70), 1));
-    p.drawEllipse(circle);
-
-    // 内侧一圈淡淡的高光,做出「微微亮着」的开机键质感
-    p.setBrush(Qt::NoBrush);
-    p.setPen(QPen(QColor(255, 255, 255, 40), 1));
-    p.drawEllipse(circle.adjusted(2.5, 2.5, -2.5, -2.5));
-
-    paintPowerGlyph(&p, circle);
-
-    // 下面一行「开始测试」:从圆下方 2px 起写到控件底
-    QFont f = font();
-    f.setPointSizeF(8.5);
-    f.setBold(false);
-    p.setFont(f);
-    p.setPen(isEnabled() ? (underMouse() ? QColor("#2f7fc1") : QColor("#41586f"))
-                         : QColor("#9aa8b6"));
-    const qreal textTop = circle.bottom() + 2.0;
-    const QRectF textRect(0, textTop, width(), height() - textTop);
-    p.drawText(textRect, Qt::AlignHCenter | Qt::AlignVCenter, text());
-}
-
-void PowerButton::paintPowerGlyph(QPainter *p, const QRectF &circle) const
-{
-    const qreal d = circle.width();
-    const qreal inset = d * 0.30;
-    const QRectF ring = circle.adjusted(inset, inset, -inset, -inset);
-
-    const QColor glyph = isEnabled() ? QColor(Qt::white) : QColor("#f2f6fa");
-    p->setBrush(Qt::NoBrush);
-    p->setPen(QPen(glyph, qMax(2.0, d * 0.055), Qt::SolidLine, Qt::RoundCap));
-    // 从 120° 起画 300°,顶部留 60° 缺口给竖杠
-    p->drawArc(ring, 120 * 16, 300 * 16);
-
-    const QPointF c = circle.center();
-    p->drawLine(QPointF(c.x(), ring.top() - d * 0.06), QPointF(c.x(), c.y() - d * 0.05));
-}

+ 0 - 312
qt-client/src/stationdata.cpp

@@ -1,312 +0,0 @@
-#include "stationdata.h"
-
-#include <QChar>
-#include <QJsonArray>
-#include <QtGlobal>
-
-QStringList channelNames()
-{
-    QStringList names;
-    const char *cpus[2] = {"CPU0", "CPU1"};
-    const char *suffix = "ABCDEFGHIJKL";
-    for (int c = 0; c < 2; ++c) {
-        for (int i = 0; i < 12; ++i) {
-            names << QStringLiteral("%1_CH%2")
-                         .arg(QString::fromLatin1(cpus[c]), QChar(QLatin1Char(suffix[i])));
-        }
-    }
-    return names;
-}
-
-StationStore::StationStore(int stationCount, QObject *parent)
-    : QObject(parent)
-    , m_stations(qMax(0, stationCount))
-{
-    // 运行时间走表:1s 一拍,只对已点「开始测试」的工位发 infoChanged 让界面重画
-    m_runtimeTimer.setInterval(1000);
-    connect(&m_runtimeTimer, &QTimer::timeout, this, &StationStore::runtimeTick);
-    m_runtimeTimer.start();
-}
-
-void StationStore::runtimeTick()
-{
-    for (int i = 0; i < m_stations.size(); ++i) {
-        if (m_stations.at(i).startTime.isValid())
-            touchRuntime(i);
-    }
-}
-
-const StationData &StationStore::station(int index) const
-{
-    static const StationData empty;
-    if (index < 0 || index >= m_stations.size())
-        return empty;
-    return m_stations.at(index);
-}
-
-void StationStore::initStation(int index, const StationData &data)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    m_stations[index] = data;
-    emit channelsChanged(index);
-    emit temperatureChanged(index);
-}
-
-void StationStore::appendLog(int index, const QString &line)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    // 只追加,永不裁剪:详情页切走再进来仍是完整历史
-    m_stations[index].logs.append(line);
-    emit logAppended(index, line);
-}
-
-void StationStore::setChannelState(int index, int channel, ChannelInfo::State state, double temperature)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    QVector<ChannelInfo> &channels = m_stations[index].channels;
-    if (channel < 0 || channel >= channels.size())
-        return;
-
-    ChannelInfo &ch = channels[channel];
-    ch.state = state;
-    ch.temperature = temperature;
-    if (state == ChannelInfo::Idle && temperature < 0.0)
-        ch.present = false;
-
-    // 通道刚装载时先落一个点,曲线不用等到下一次采样才有数据
-    if (temperature >= 0.0) {
-        ch.history.append(ch.temperature);
-        while (ch.history.size() > kTempHistorySize) {
-            ch.history.removeFirst();
-            ++ch.historyStart;
-        }
-    }
-
-    emit channelsChanged(index);
-}
-
-void StationStore::setChannelTemperature(int index, int channel, double temperature)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    QVector<ChannelInfo> &channels = m_stations[index].channels;
-    if (channel < 0 || channel >= channels.size())
-        return;
-
-    ChannelInfo &ch = channels[channel];
-    ch.temperature = temperature;
-
-    if (temperature >= 0.0) {
-        ch.history.append(temperature);
-        while (ch.history.size() > kTempHistorySize) {
-            ch.history.removeFirst();
-            ++ch.historyStart;
-        }
-    }
-
-    emit channelsChanged(index);
-}
-
-void StationStore::setCurrentTemp(int index, double temperature)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    StationData &d = m_stations[index];
-    d.currentTemp = temperature;
-
-    // 温控曲线:只保留最近 200 点,旧点从头部挤出去;start 记下队首的全局序号,
-    // 曲线横轴因此跟着数据一起向前滚动(可见宽度恒为 200 点)
-    d.tempHistory.append(temperature);
-    while (d.tempHistory.size() > kTempHistorySize) {
-        d.tempHistory.removeFirst();
-        ++d.tempHistoryStart;
-    }
-
-    emit temperatureChanged(index);
-}
-
-void StationStore::setPort(int index, const QString &port)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-    if (m_stations.at(index).port == port)
-        return;
-
-    m_stations[index].port = port;
-    emit infoChanged(index);
-}
-
-void StationStore::setStartTime(int index, const QDateTime &start)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    m_stations[index].startTime = start;
-    emit infoChanged(index);
-}
-
-void StationStore::touchRuntime(int index)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    emit infoChanged(index);
-}
-
-void StationStore::setBackendLink(int index, bool connected, bool busy)
-{
-    if (index < 0 || index >= m_stations.size()) return;
-    m_stations[index].backendConnected = connected;
-    m_stations[index].backendBusy = busy;
-    emit infoChanged(index);
-}
-
-void StationStore::applyBackendState(int index, const QJsonObject &state)
-{
-    if (index < 0 || index >= m_stations.size()) return;
-    StationData &data = m_stations[index];
-    data.phase = state.value(QStringLiteral("phase")).toString();
-    data.runState = state.value(QStringLiteral("run_state")).toString();
-    data.power = state.value(QStringLiteral("power")).toString();
-    data.verdict = state.value(QStringLiteral("verdict")).toString();
-    data.verdictScope = state.value(QStringLiteral("verdict_scope")).toString();
-    data.canStart = state.value(QStringLiteral("can_start")).toBool(false);
-    const qint64 started = state.value(QStringLiteral("started_unix_ms")).toVariant().toLongLong();
-    data.startTime = started > 0 ? QDateTime::fromMSecsSinceEpoch(started) : QDateTime();
-    // 工位腔体实时温度 (currentTemp) 仅由本地高温罩温控串口 (applyCtTemperatures) 提供,不从服务器后端获取。
-    for (const QJsonValue &value : state.value(QStringLiteral("channels")).toArray()) {
-        const QJsonObject channel = value.toObject();
-        const QString name = channel.value(QStringLiteral("name")).toString();
-        for (int i = 0; i < data.channels.size(); ++i) {
-            if (data.channels[i].name != name) continue;
-            const QString verdict = channel.value(QStringLiteral("state")).toString();
-            const ChannelInfo::State result = verdict == QStringLiteral("pass") ? ChannelInfo::Pass
-                : verdict == QStringLiteral("fail") ? ChannelInfo::Fail : ChannelInfo::Idle;
-            const QJsonValue temperature = channel.value(QStringLiteral("temperature_c"));
-            setChannelState(index, i, result,
-                temperature.isDouble() ? temperature.toDouble() : data.channels[i].temperature);
-            data.channels[i].present = channel.value(QStringLiteral("present")).toBool(false);
-            break;
-        }
-    }
-    QStringList alarms;
-    const QJsonObject stageErrors = state.value(QStringLiteral("stage_errors")).toObject();
-    const char *const stages[] = {"training", "rmt", "amt", "mt"};
-    for (const char *stageKey : stages) {
-        const QJsonArray arr = stageErrors.value(QLatin1String(stageKey)).toArray();
-        for (const QJsonValue &ev : arr) {
-            const QJsonObject obj = ev.toObject();
-            const QString loc = obj.value(QStringLiteral("location")).toString();
-            const QString reason = obj.value(QStringLiteral("reason")).toString();
-            const QString msg = obj.value(QStringLiteral("evidence")).toString().trimmed().isEmpty()
-                ? obj.value(QStringLiteral("message")).toString()
-                : obj.value(QStringLiteral("evidence")).toString().trimmed();
-            QString line = QStringLiteral("[%1] ").arg(QString::fromLatin1(stageKey).toUpper());
-            if (!loc.isEmpty()) line += loc + QStringLiteral(" ");
-            if (!reason.isEmpty() && !msg.contains(reason)) line += reason + QStringLiteral(": ");
-            line += msg;
-            if (!alarms.contains(line))
-                alarms.append(line);
-        }
-    }
-    data.alarms = alarms;
-    emit infoChanged(index);
-}
-
-void StationStore::applyCtTemperatures(int index, const QByteArray &raw8)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    // 本板 CT7428 八路:跳过无效路(0xFF)后取算术平均,当作这一工位的「腔体温度」。
-    // 八路全无效(设备刚上电 / CPLD 失联时整组回 0xFF)→ 写 -1,界面显示 --℃。
-    double sum = 0.0;
-    int valid = 0;
-    for (int i = 0; i < raw8.size(); ++i) {
-        const quint8 b = static_cast<quint8>(raw8.at(i));
-        if (b == 0xFF)      // slt::kTempInvalid
-            continue;
-        sum += b;
-        ++valid;
-    }
-
-    setCurrentTemp(index, valid > 0 ? sum / valid : -1.0);
-}
-
-void StationStore::applyChannelTemperatures(int index, const QByteArray &raw24)
-{
-    if (index < 0 || index >= m_stations.size())
-        return;
-
-    QVector<ChannelInfo> &channels = m_stations[index].channels;
-    if (raw24.size() != channels.size())
-        return;                       // 应答长度不对(比如还夹着别的 CMD)就整帧丢
-
-    bool changed = false;
-    bool curveChanged = false;
-
-    for (int i = 0; i < channels.size(); ++i) {
-        const quint8 b = static_cast<quint8>(raw24.at(i));
-        ChannelInfo &ch = channels[i];
-
-        if (b == 0xFF) {
-            // Temperature validity and test result are independent.
-            if (ch.temperature >= 0.0) {
-                ch.temperature = -1.0;
-                changed = true;
-            }
-            continue;
-        }
-
-        // A temperature sample is never evidence of a passed memory test.
-        const double t = static_cast<double>(b);
-        if (qAbs(ch.temperature - t) > 0.05) {
-            ch.temperature = t;
-            changed = true;
-        }
-
-        // 每个轮询周期给这个通道落一个点:详情页曲线一路一段连续曲线靠它撑起来
-        ch.history.append(t);
-        while (ch.history.size() > kTempHistorySize) {
-            ch.history.removeFirst();
-            ++ch.historyStart;
-        }
-        curveChanged = true;
-    }
-
-    // 24 路逐格改会连发 24 次信号,这里合并成一次刷,避免界面被刷爆
-    if (changed || curveChanged)
-        emit channelsChanged(index);
-}
-
-int StationStore::countState(int index, ChannelInfo::State state) const{
-    int n = 0;
-    const QVector<ChannelInfo> &channels = station(index).channels;
-    for (const ChannelInfo &ch : channels) {
-        if (ch.state == state)
-            ++n;
-    }
-    return n;
-}
-
-int StationStore::loadedChannels(int index) const
-{
-    int count = 0;
-    for (const ChannelInfo &channel : station(index).channels)
-        if (channel.present || channel.temperature >= 0.0 || channel.state != ChannelInfo::Idle)
-            ++count;
-    return count;
-}
-
-bool StationStore::hasFailure(int index) const
-{
-    return countState(index, ChannelInfo::Fail) > 0;
-}

+ 0 - 413
qt-client/src/style/app.qss

@@ -1,413 +0,0 @@
-/* ============================================================================
-   DDR5 RDIMM SLT 上位机监控平台 —— 全局样式表
-   所有颜色 / 字号 / 圆角集中在此,改主题只改这个文件。
-   .ui 中通过动态属性 role / tone / pill 作为选择器钩子。
-   ============================================================================ */
-
-QWidget {
-    color: #20323f;
-}
-
-QWidget#centralwidget {
-    background: #e9edf3;
-}
-
-/* ---------------------------------------------------------------- 顶部标题栏 */
-QFrame[role="header"] {
-    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #334a67, stop:1 #273d57);
-    border-bottom: 1px solid #1f334a;
-}
-
-QLabel[role="logo"] {
-    background: transparent;
-    border: none;
-    padding: 0;
-}
-
-QLabel[role="appTitle"] {
-    color: #ffffff;
-    font-size: 23px;
-    font-weight: 700;
-}
-
-QFrame[role="headerSep"] {
-    background: rgba(255, 255, 255, 0.18);
-}
-
-QPushButton[role="win"] {
-    color: #cfe0f0;
-    background: transparent;
-    border: none;
-    font-size: 13px;
-}
-
-QPushButton[role="win"]:hover {
-    background: rgba(255, 255, 255, 0.14);
-    color: #ffffff;
-}
-
-QPushButton#btnWinClose:hover {
-    background: #e81123;
-    color: #ffffff;
-}
-
-/* ---------------------------------------------------------------- 内容区骨架 */
-QWidget[role="contentArea"] {
-    background: #e9edf3;
-}
-
-QFrame[role="breadcrumb"] {
-    background: #f7f9fb;
-    border-bottom: 1px solid #dbe2ea;
-}
-
-QLabel[role="breadcrumbLabel"] {
-    color: #7b8b9c;
-    font-size: 12px;
-}
-
-QLabel[role="pageTitle"] {
-    color: #16324a;
-}
-
-/* ---------------------------------------------------------------- 卡片外框 */
-QFrame[role="card"],
-QFrame[role="station"] {
-    background: #ffffff;
-    border: 1px solid #d9e0e8;
-    border-radius: 6px;
-}
-
-QFrame[role="vsep"] {
-    background: #e8eef4;
-}
-
-QFrame[role="hsep"] {
-    background: #e5ebf2;
-}
-
-/* ---------------------------------------------------------------- 工位卡片 */
-QLabel[role="cardIcon"] {
-    background: #1a7ec2;
-    color: #ffffff;
-    border-radius: 3px;
-    font-size: 15px;
-}
-
-QLabel[role="cardName"] {
-    /* 与卡头左侧图标方块同色 */
-    color: #1a7ec2;
-    font-size: 17px;
-    font-weight: 700;
-}
-
-/* 卡头右侧:串口名 + COM 连接状态灯 */
-/* 串口名:不要外框,只留等宽字(具体位置跟着信息行的上下两行居中) */
-QLabel[role="cardPort"] {
-    color: #3d5a75;
-    background: transparent;
-    border: none;
-    font-family: Consolas, "Courier New", monospace;
-    font-size: 14px;
-    padding: 0;
-}
-
-QLabel[role="comState"] {
-    border-radius: 9px;
-    font-size: 11px;
-    padding: 1px 7px;
-}
-
-QLabel[role="comState"][state="offline"] {
-    color: #8a97a5;
-    background: #f1f3f6;
-    border: 1px solid #dde3ea;
-}
-
-QLabel[role="comState"][state="connecting"] {
-    color: #a8720a;
-    background: #fdf5e4;
-    border: 1px solid #f0dcb0;
-}
-
-QLabel[role="comState"][state="online"] {
-    color: #1f8047;
-    background: #eaf7ef;
-    border: 1px solid #c4e4d0;
-    font-weight: 700;
-}
-
-/* 信息行里的状态灯:plain=true 时只要文字和状态点,不要圆角底色(写在各 state 规则之后) */
-QLabel[role="comState"][plain="true"] {
-    background: transparent;
-    border: none;
-    border-radius: 0;
-    padding: 0;
-}
-
-QPushButton[role="cardDetail"] {
-    color: #2f7fc1;
-    background: transparent;
-    border: none;
-    font-size: 12px;
-    font-weight: 600;
-    padding: 0 2px;
-}
-
-QPushButton[role="cardDetail"]:hover {
-    color: #155f9f;
-}
-
-QFrame[role="infoRow"] {
-    background: #f8fafc;
-    border: 1px solid #e8eef4;
-    border-radius: 4px;
-}
-
-QLabel[role="fieldLabel"] {
-    color: #8394a5;
-    font-size: 11px;
-}
-
-QLabel[role="fieldValue"] {
-    color: #1d3549;
-    font-size: 13px;
-}
-
-QLabel[role="fieldValueBold"] {
-    color: #12314c;
-    font-size: 16px;
-    font-weight: 700;
-}
-
-QLabel[role="fieldSub"] {
-    color: #98a5b3;
-    font-size: 11px;
-    padding-bottom: 1px;
-}
-
-/* 24 通道格子(总览卡与详情页共用 QFrame[role="chCell"],见下方详情页段落) */
-
-/* ---------------------------------------------------------------- 设备详情页 */
-QLabel[role="detailTitle"] {
-    color: #16324a;
-    font-size: 16px;
-    font-weight: 700;
-}
-
-/* 标题里的分隔符与工位号:静态控件,样式全部在 QSS,代码只填文本 */
-QLabel[role="detailTitleDot"] {
-    color: #b3bfcb;
-    font-size: 16px;
-}
-
-QLabel[role="detailDevice"] {
-    color: #2f7fc1;
-    font-size: 16px;
-    font-weight: 700;
-}
-
-QLabel[role="panelTitle"] {
-    color: #17324a;
-    font-size: 13px;
-    font-weight: 700;
-}
-
-/* 总览卡片的通道标题:与上方分隔线、下方格子各留 5px,避免文字贴边 */
-QLabel[role="ovChTitle"] {
-    color: #17324a;
-    font-size: 13px;
-    font-weight: 700;
-    padding: 5px 0 5px 0;
-}
-
-QPushButton[role="detailBack"] {
-    color: #2f7fc1;
-    background: #ffffff;
-    border: 1px solid #cdd7e1;
-    border-radius: 3px;
-    font-size: 12px;
-}
-
-QPushButton[role="detailBack"]:hover {
-    background: #eef4fa;
-    border-color: #b9cfe2;
-}
-
-/* 24 通道格子 */
-QFrame[role="chCell"] {
-    background: #ffffff;
-    border: 1px solid #dfe6ee;
-    border-radius: 4px;
-}
-
-QFrame[role="chCell"] QLabel[role="chCellName"] {
-    color: #7d8b9a;
-    font-size: 11px;
-}
-
-QFrame[role="chCell"] QLabel[role="chCellValue"] {
-    color: #12314c;
-    font-size: 12px;
-    font-weight: 700;
-}
-
-QFrame[role="chCell"][state="pass"] {
-    background: #f4fbf7;
-    border-color: #cfe8d9;
-}
-
-QFrame[role="chCell"][state="pass"] QLabel[role="chCellValue"] {
-    color: #1f8047;
-}
-
-/* 详情页:已装载通道统一蓝色(原先 PASS 用的蓝),不再区分 PASS / FAIL */
-QFrame[role="chCell"][state="loaded"] {
-    background: #f2f8fe;
-    border-color: #cfe1f3;
-}
-
-QFrame[role="chCell"][state="loaded"] QLabel[role="chCellValue"] {
-    color: #1e6aa8;
-}
-
-/* 当前温控曲线看的是这个通道:蓝框高亮(写在各 state 之后才盖得住它们的 border-color) */
-QFrame[role="chCell"][selected="true"] {
-    border: 2px solid #2f7fc1;
-}
-
-QFrame[role="chCell"][state="fail"] {
-    background: #fdf0ef;
-    border-color: #f3cdcb;
-}
-
-QFrame[role="chCell"][state="fail"] QLabel[role="chCellValue"] {
-    color: #c92f2f;
-}
-
-QFrame[role="chCell"][state="idle"] {
-    background: #f5f7f9;
-    border-color: #e4e9ef;
-}
-
-QFrame[role="chCell"][state="idle"] QLabel[role="chCellValue"] {
-    color: #98a5b3;
-}
-
-/* 页签 */
-QPushButton[role="detailTab"] {
-    color: #5d7086;
-    background: #f4f7fa;
-    border: 1px solid #e2e9f1;
-    border-top-left-radius: 4px;
-    border-top-right-radius: 4px;
-    font-size: 12px;
-    padding: 0 10px;
-}
-
-QPushButton[role="detailTab"]:hover {
-    color: #2f7fc1;
-}
-
-QPushButton[role="detailTab"][active="true"] {
-    color: #1a7ec2;
-    background: #ffffff;
-    border-color: #d9e0e8;
-    font-weight: 700;
-}
-
-QLabel[role="placeholder"] {
-    color: #98a5b3;
-    font-size: 12px;
-}
-
-/* 内存参数设置:三列表单(参数名 / 输入框 / 单位),列间用 1px 分隔线隔开 */
-QLabel[role="paramName"] {
-    color: #5d7086;
-    font-size: 12px;
-}
-
-QLineEdit[role="paramEdit"] {
-    background: #ffffff;
-    border: 1px solid #d7e0ea;
-    border-radius: 3px;
-    color: #33465a;
-    font-size: 12px;
-    padding: 0 8px;
-    selection-background-color: #cfe4f7;
-    selection-color: #16324a;
-}
-
-QLineEdit[role="paramEdit"]:focus {
-    border-color: #6ba6d8;
-}
-
-QCheckBox[role="paramCheck"] {
-    spacing: 0;
-}
-
-/* 参数列分隔线:比 vsep 略深,否则在浅灰底上几乎看不见 */
-QFrame[role="paramSep"] {
-    background: #dde6f0;
-}
-
-/* 内存参数页「确定」按钮(功能暂未接,样式先定) */
-QPushButton[role="paramSubmit"] {
-    color: #ffffff;
-    background: #2f7fc1;
-    border: 1px solid #2f7fc1;
-    border-radius: 4px;
-    font-size: 13px;
-    font-weight: 700;
-}
-
-QPushButton[role="paramSubmit"]:hover {
-    background: #2a72ad;
-    border-color: #2a72ad;
-}
-
-QPushButton[role="paramSubmit"]:pressed {
-    background: #256394;
-    border-color: #256394;
-}
-
-QPushButton[role="paramSubmit"]:disabled {
-    color: #ffffff;
-    background: #a9c4db;
-    border-color: #a9c4db;
-}
-
-QCheckBox[role="paramCheck"]::indicator {
-    width: 14px;
-    height: 14px;
-    border: 1px solid #cbd6e1;
-    border-radius: 2px;
-    background: #ffffff;
-}
-
-QCheckBox[role="paramCheck"]::indicator:checked {
-    border-color: #2f7fc1;
-    background: #2f7fc1;
-}
-
-/* 测试日志 */
-QPlainTextEdit[role="log"] {
-    background: #fbfcfd;
-    border: 1px solid #eef2f7;
-    border-radius: 4px;
-    color: #5d7086;
-    font-family: Consolas, "Courier New", monospace;
-    font-size: 11px;
-    padding: 4px;
-}
-
-QSizeGrip {
-    background: transparent;
-}
-
-QToolTip {
-    background: #17324a;
-    color: #ffffff;
-    border: 1px solid #2e557a;
-    padding: 4px 6px;
-}

+ 0 - 52
qt-client/src/uiformat.h

@@ -1,52 +0,0 @@
-#ifndef UIFORMAT_H
-#define UIFORMAT_H
-
-#include <QDateTime>
-#include <QLatin1Char>
-#include <QString>
-
-/**
- * 界面文本工具(多个视图共用,避免各写一份)
- * 注意:字号 / 颜色一律在 .ui + app.qss 里定义,这里只做纯文本格式化。
- */
-namespace ui {
-
-// 图例小圆点 + 名称 + 计数,如 ● PASS 20
-inline QString legendHtml(const QString &text, int count, const QString &color)
-{
-    return QStringLiteral("<span style='color:%1;font-size:11px'>●</span>&nbsp;"
-                          "<span style='color:#5d7086'>%2</span>&nbsp;"
-                          "<b style='color:%1'>%3</b>")
-        .arg(color, text.toHtmlEscaped())
-        .arg(count);
-}
-
-// 运行时长 HH:mm:ss
-// start 无效 = 这个工位还没点过「开始测试」,统一显示 00:00:00
-inline QString formatElapsed(const QDateTime &start)
-{
-    if (!start.isValid())
-        return QStringLiteral("00:00:00");
-
-    qint64 secs = qMax<qint64>(0, start.secsTo(QDateTime::currentDateTime()));
-    const qint64 h = secs / 3600;
-    secs %= 3600;
-    const qint64 m = secs / 60;
-    const qint64 s = secs % 60;
-    return QStringLiteral("%1:%2:%3")
-        .arg(h, 2, 10, QLatin1Char('0'))
-        .arg(m, 2, 10, QLatin1Char('0'))
-        .arg(s, 2, 10, QLatin1Char('0'));
-}
-
-// 温度文本:还没采到数据(<0)时显示 --℃
-inline QString formatTemp(double celsius)
-{
-    if (celsius < 0.0)
-        return QStringLiteral("--℃");
-    return QStringLiteral("%1°C").arg(QString::number(celsius, 'f', 1));
-}
-
-} // namespace ui
-
-#endif // UIFORMAT_H

+ 0 - 440
qt-client/tests/qt_clean_probe.cpp

@@ -1,440 +0,0 @@
-// This harness instantiates the actual MainWindow and clicks its real buttons.
-// Default mode is read-only. Only --mode start invokes physical host controls.
-#include "mainwindow.h"
-#include "backendlink.h"
-#include "stationdata.h"
-#include "localplans.h"
-#include <QAbstractButton>
-#include <QCheckBox>
-#include <QApplication>
-#include <QCommandLineParser>
-#include <QDateTime>
-#include <QDir>
-#include <QFile>
-#include <QFontDatabase>
-#include <QJsonArray>
-#include <QJsonDocument>
-#include <QJsonObject>
-#include <QLabel>
-#include <QLineEdit>
-#include <QPointer>
-#include <QPlainTextEdit>
-#include <QSaveFile>
-#include <QTemporaryDir>
-#include <QTimer>
-#include <QWebSocket>
-#include <QWebSocketServer>
-#include <functional>
-
-static bool writeJson(const QString &path, const QJsonObject &value)
-{
-    QSaveFile file(path);
-    const QByteArray bytes = QJsonDocument(value).toJson(QJsonDocument::Indented);
-    return file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size() && file.commit();
-}
-
-class Fixture : public QObject
-{
-public:
-    QWebSocketServer server{QStringLiteral("Qt clean contract fixture"), QWebSocketServer::NonSecureMode};
-    QPointer<QWebSocket> socket;
-    int connections = 0;
-    int starts = 0;
-    int actions = 0;
-    bool duplicate = false;
-    bool unexpected = false;
-    bool correctParams = true;
-    bool disconnectTest = false;
-    bool silentMode = false;
-    bool runAmt = false;
-    bool amtResultsReady = false;
-    bool earlyAmtExit = false;
-    int amtLaunches = 0;
-    bool failAtEnd = false;
-    bool unexpectedBootMode = false;
-    bool changedBoot = false;
-    bool oldFailedSnapshotSent = false;
-    int uartReplays = 0;
-    QStringList methods;
-    QSet<QString> inputIds;
-    QJsonObject command;
-    QJsonArray events;
-    int step = -1;
-    qint64 started = 0;
-    quint64 sequence = 0;
-
-    explicit Fixture(bool testAmt = false) : runAmt(testAmt)
-    {
-        server.listen(QHostAddress::LocalHost, 0);
-        connect(&server, &QWebSocketServer::newConnection, this, [this] {
-            socket = server.nextPendingConnection();
-            ++connections;
-            QWebSocket *client = socket;
-            connect(client, &QWebSocket::textMessageReceived, this, [this](const QString &text) { receive(text); });
-            connect(client, &QWebSocket::disconnected, client, &QObject::deleteLater);
-            pushState();
-            if (silentMode) return; // Deliberately silent TCP peer: exercise client watchdog.
-            // A fresh socket starts from byte zero. BackendLink must suppress
-            // already displayed bytes and recover anything missed offline.
-            for (const QJsonValue &row : events) send(row.toObject());
-            ++uartReplays;
-        });
-    }
-    QString url() const { return QStringLiteral("ws://127.0.0.1:%1/ws?view=qt-clean").arg(server.serverPort()); }
-    void send(const QJsonObject &frame)
-    {
-        if (socket && socket->state() == QAbstractSocket::ConnectedState)
-            socket->sendTextMessage(QString::fromUtf8(QJsonDocument(frame).toJson(QJsonDocument::Compact)));
-    }
-    QJsonObject station() const
-    {
-        QString stage, phase = QStringLiteral("uefi"), action;
-        int cpu = 0;
-        if (step == 0 || step == 1) { stage = "uip1"; phase = "uip"; action = "continue_uip"; cpu = step; }
-        else if (step == 2 || step == 3) { stage = "amt"; phase = "amt"; action = runAmt ? "start_amt" : "skip_amt"; cpu = step - 2; }
-        else if (runAmt && (step == 4 || step == 5)) { stage = "amt"; phase = "amt"; action = "skip_amt"; cpu = step - 4; }
-        else if (step == (runAmt ? 6 : 4)) { stage = "uip2"; phase = "uefi"; action = "continue_uip"; }
-        else if (step >= (runAmt ? 7 : 5)) { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
-        else { stage = "uefi"; phase = "uefi"; action = "start_mt"; }
-        const QJsonObject input{{"id", QStringLiteral("fixture-input-%1").arg(step)}, {"stage", stage},
-            {"cpu", cpu}, {"ready", true}, {"test_complete", amtResultsReady}, {"actions", QJsonArray{action}}};
-        return QJsonObject{{"station_id", "S1"}, {"connection", "online"}, {"power", "on"}, {"can_start", true},
-            {"phase", phase}, {"run_state", changedBoot || (failAtEnd && step >= 5)
-                || (step < 0 && command.value("state").toString() == "succeeded")
-                    ? "failed" : (step >= 0 ? "waiting_input" : "idle")},
-            {"started_unix_ms", QString::number(started)},
-            {"boot_id", changedBoot ? "fixture-boot-2" : (step >= 0 ? "fixture-boot-1" : "fixture-boot-0")},
-            {"verdict", failAtEnd && step >= 5 ? "fail" : "not_tested"},
-            {"input", input}, {"command", command},
-            {"channels", QJsonArray{QJsonObject{{"name", "CPU0_CHA"}, {"present", false}, {"state", "idle"}, {"temperature_c", 48.0}}}}};
-    }
-    QJsonObject state() const
-    {
-        return QJsonObject{{"version", "0.8.0-fixture"}, {"mode", "fixture"}, {"server_id", "qt-clean-fixture"},
-            {"stations", QJsonArray{station()}}};
-    }
-    void pushState() { send(QJsonObject{{"v", 1}, {"event", "state"}, {"result", state()}}); }
-    void log(const QString &message)
-    {
-        const QByteArray bytes = (message + QLatin1Char('\n')).toUtf8();
-        const quint64 first = sequence;
-        sequence += static_cast<quint64>(bytes.size());
-        const QJsonObject frame{{"v", 1}, {"event", "bios_uart"}, {"result", QJsonObject{
-            {"station_id", "S1"}, {"session_id", "fixture-uart-session"},
-            {"offset", QString::number(first)}, {"next_offset", QString::number(sequence)},
-            {"data_base64", QString::fromLatin1(bytes.toBase64())}}}};
-        events.append(frame);
-        send(frame);
-    }
-    void receive(const QString &text)
-    {
-        const QJsonObject request = QJsonDocument::fromJson(text.toUtf8()).object();
-        const QString method = request.value("method").toString();
-        const QJsonObject params = request.value("params").toObject();
-        methods << method;
-        auto respond = [this, request](const QJsonObject &result) {
-            send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", true}, {"result", result}});
-        };
-        if (method == "GetState") {
-            if (step < 0 && command.value("state").toString() == "succeeded") oldFailedSnapshotSent = true;
-            respond(state()); return;
-        }
-        if (method == "GetCommand") { respond(command); return; }
-        if (method == "StartTest") {
-            ++starts;
-            command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "queued"}, {"error", ""}};
-            // Reply succeeds before the asynchronously refreshed state. The old
-            // UEFI input must never finish the new client's local plan.
-            QTimer::singleShot(250, this, [this, respond] {
-                const qint64 confirmedStarted = QDateTime::currentMSecsSinceEpoch();
-                command.insert("state", "succeeded");
-                command.insert("result", QJsonObject{{"boot_id", "fixture-boot-1"},
-                    {"started_unix_ms", QString::number(confirmedStarted)}});
-                respond(command);
-                QTimer::singleShot(200, this, [this, confirmedStarted] {
-                    started = confirmedStarted;
-                    step = 0;
-                    log(QStringLiteral("Fixture: fresh BIOS boot confirmed"));
-                    pushState();
-                });
-            });
-            return;
-        }
-        if (method == "StageAction") {
-            ++actions;
-            const QString input = params.value("input_id").toString();
-            if (inputIds.contains(input)) duplicate = true;
-            inputIds.insert(input);
-            const QJsonObject memory = params.value("memory_params").toObject();
-            if (step < 2) correctParams = correctParams && memory.value("tCL").toInt() == 45;
-            if (step == (runAmt ? 6 : 4)) correctParams = correctParams && memory.isEmpty();
-            const QString action = params.value("action").toString();
-            if (action == "start_amt") ++amtLaunches;
-            if ((step == 2 || step == 3) && action != (runAmt ? "start_amt" : "skip_amt")) unexpected = true;
-            if (runAmt && (step == 4 || step == 5) && action == "skip_amt" && !amtResultsReady) earlyAmtExit = true;
-            command = QJsonObject{{"command_id", params.value("command_id")}, {"state", "running"}, {"error", ""}};
-            respond(command);
-            if (unexpectedBootMode && step == 0) {
-                // A new BIOS boot is observed while a submitted stage command
-                // remains running. Failure must not be hidden by either guard.
-                QTimer::singleShot(90, this, [this] {
-                    changedBoot = true;
-                    log(QStringLiteral("Fixture: unexpected BIOS restart during pending stage"));
-                    pushState();
-                });
-                return;
-            }
-            if (step == 0 && socket) {
-                disconnectTest = true;
-                socket->close();
-            }
-            QTimer::singleShot(90, this, [this] {
-                ++step;
-                command.insert("state", "succeeded");
-                log(QStringLiteral("Fixture: stage action %1 completed").arg(actions));
-                pushState();
-                if (runAmt && step == 4) {
-                    QTimer::singleShot(300, this, [this] {
-                        amtResultsReady = true;
-                        log(QStringLiteral("Fixture: actual AMT algorithm results completed"));
-                        pushState();
-                    });
-                }
-            });
-            return;
-        }
-        unexpected = true;
-        send(QJsonObject{{"v", 1}, {"id", request.value("id")}, {"ok", false},
-            {"error", QJsonObject{{"code", "UNEXPECTED_METHOD"}, {"message", method}}}});
-    }
-};
-
-int main(int argc, char **argv)
-{
-    QApplication app(argc, argv);
-    QCommandLineParser parser;
-    parser.addHelpOption();
-    parser.addOption({"mode", "read-only, start, fixture, fixture-amt, fixture-fail, fixture-unexpected-boot, fixture-silent. start physically starts/reboots one host.", "mode", "read-only"});
-    parser.addOption({"url", "Clean backend WebSocket URL", "url"});
-    parser.addOption({"report", "Write JSON verification evidence", "path", "qt-clean-probe.json"});
-    parser.addOption({"screenshot", "Write actual Qt window PNG", "path"});
-    parser.addOption({"station", "Station number 1..4", "number", "1"});
-    parser.addOption({"expect-phase", "Required final phase for a real Start", "phase", "uefi"});
-    parser.addOption({"timeout", "Maximum seconds", "seconds", "90"});
-    parser.process(app);
-    const QString mode = parser.value("mode");
-    if (mode != "read-only" && mode != "start" && mode != "fixture" && mode != "fixture-amt"
-        && mode != "fixture-fail" && mode != "fixture-unexpected-boot" && mode != "fixture-silent") return 2;
-    const int station = parser.value("station").toInt() - 1;
-    if (station < 0 || station > 3) return 2;
-    qputenv("STL_QT_DISABLE_SERIAL", "1");
-    if (!parser.value("url").isEmpty()) qputenv("STL_QT_BACKEND_URL", parser.value("url").toUtf8());
-    QFile style(":/style/app.qss");
-    if (style.open(QIODevice::ReadOnly)) app.setStyleSheet(QString::fromUtf8(style.readAll()));
-    const QStringList families = QFontDatabase().families();
-    for (const QString &family : QStringList{"Noto Sans CJK SC", "WenQuanYi Micro Hei", "DejaVu Sans"}) {
-        if (families.contains(family)) { app.setFont(QFont(family, 9)); break; }
-    }
-
-    QJsonObject checks;
-    QTemporaryDir selfTestDir;
-    const QByteArray oldPlans = qgetenv("STL_QT_PLANS_FILE");
-    qputenv("STL_QT_PLANS_FILE", selfTestDir.filePath("local-plans.json").toUtf8());
-    LocalPlans plans;
-    QString planError;
-    const bool saved = plans.saveMemoryParams(0, QJsonObject{{"tCL", 45}}, &planError);
-    const LocalPlans reloaded;
-    checks.insert("local_plan_saved_and_reloaded", saved && reloaded.memoryParams(0).value("tCL").toInt() == 45);
-    checks.insert("saved_plan_arms_uip_only_for_station", reloaded.plan(0).value("uip").toObject().value("apply_memory_params").toBool()
-        && reloaded.memoryParams(1).value("tCL").toInt() != 45);
-    if (oldPlans.isEmpty()) qunsetenv("STL_QT_PLANS_FILE"); else qputenv("STL_QT_PLANS_FILE", oldPlans);
-    StationStore probeStore(1);
-    StationData data;
-    for (const QString &name : channelNames()) data.channels.append(ChannelInfo(name, -1, ChannelInfo::Idle));
-    probeStore.initStation(0, data);
-    probeStore.applyChannelTemperatures(0, QByteArray(24, char(48)));
-    checks.insert("temperature_never_implies_pass", probeStore.countState(0, ChannelInfo::Pass) == 0
-        && probeStore.station(0).channels.first().temperature == 48.0);
-    probeStore.setChannelState(0, 0, ChannelInfo::Fail, 48);
-    probeStore.applyChannelTemperatures(0, QByteArray(24, char(0xff)));
-    checks.insert("missing_temperature_preserves_fail", probeStore.station(0).channels.first().state == ChannelInfo::Fail
-        && probeStore.station(0).channels.first().temperature < 0.0);
-
-    QTemporaryDir fixtureDir;
-    Fixture *fixture = nullptr;
-    if (mode.startsWith("fixture")) {
-        fixture = new Fixture(mode == "fixture-amt");
-        fixture->failAtEnd = mode == "fixture-fail";
-        fixture->unexpectedBootMode = mode == "fixture-unexpected-boot";
-        fixture->silentMode = mode == "fixture-silent";
-        if (!fixture->server.isListening()) return 2;
-        qputenv("STL_QT_BACKEND_URL", fixture->url().toUtf8());
-        qputenv("STL_QT_CONFIG_DIR", fixtureDir.path().toUtf8());
-        qputenv("STL_QT_PLANS_FILE", fixtureDir.filePath("qt-plans.json").toUtf8());
-        writeJson(fixtureDir.filePath("config.json"), QJsonObject{{"memoryParams", QJsonObject{{"tCL", 44}}},
-            {"qtPlan", QJsonObject{{"uip", QJsonObject{{"action", "continue_uip"}, {"apply_memory_params", false}}},
-            {"amt", QJsonObject{{"action", mode == "fixture-amt" ? "start_amt" : "skip_amt"}, {"exit_after", true}}},
-            {"uefi", QJsonObject{{"action", "hold"}}}}}});
-    }
-    MainWindow window;
-    window.resize(1920, 1080);
-    window.show();
-    BackendLink *backend = window.findChild<BackendLink *>();
-    if (!backend) return 2;
-    const qint64 begin = QDateTime::currentMSecsSinceEpoch();
-    QJsonArray states, phases;
-    QJsonObject latest;
-    int snapshots = 0;
-    int logs = 0;
-    bool clicked = false;
-    bool startedSuccessfully = false;
-    bool finished = false;
-    qint64 fixtureCompletedAt = 0;
-    QString failure;
-    QObject::connect(backend, &BackendLink::stationState, &app, [&](int index, const QJsonObject &state) {
-        if (index != station) return;
-        ++snapshots;
-        latest = state;
-        const QString phase = state.value("phase").toString();
-        if (phases.isEmpty() || phases.last().toString() != phase) phases.append(phase);
-        if (states.isEmpty() || states.last().toObject() != state) states.append(state);
-    });
-    QObject::connect(backend, &BackendLink::logLine, &app, [&](int index, const QString &) { if (index == station) ++logs; });
-    QObject::connect(backend, &BackendLink::commandFinished, &app,
-        [&](int index, const QString &method, bool success, const QString &error) {
-            if (index != station) return;
-            if (!success) failure = error.isEmpty() ? QStringLiteral("command failed") : error;
-            if (method == "StartTest" && success) startedSuccessfully = true;
-        });
-
-    if (fixture && mode != "fixture-silent") {
-        // Calling the real Start slot while offline must neither send nor start timing.
-        QMetaObject::invokeMethod(&window, "startTest", Qt::DirectConnection, Q_ARG(int, 0));
-        checks.insert("offline_start_does_not_start_timer", !window.store()->station(0).startTime.isValid() && fixture->starts == 0);
-        window.findChild<QAbstractButton *>("cardDetail_0")->click();
-        window.findChild<QLineEdit *>("paramEdit_0_2")->setText("45");
-        window.findChild<QLineEdit *>("paramEdit_0_0")->setText("1070");
-        window.findChild<QAbstractButton *>("btnParamSubmit")->click();
-        checks.insert("actual_form_save_is_local", LocalPlans().memoryParams(0).value("tCL").toInt() == 45 && fixture->methods.isEmpty());
-        window.findChild<QLineEdit *>("paramEdit_0_0")->setText("invalid");
-        window.findChild<QAbstractButton *>("btnParamSubmit")->click();
-        checks.insert("invalid_parameter_not_coerced_to_zero", LocalPlans().memoryParams(0).value("mem vdd").toInt() == 1070);
-        checks.insert("param_actions_do_not_pollute_bios_uart_log", window.store()->station(0).logs.isEmpty());
-        window.store()->appendLog(0, QStringLiteral("fixture-unique-live-log"));
-        window.findChild<QAbstractButton *>("btnBackMonitor")->click();
-        window.findChild<QAbstractButton *>("cardDetail_1")->click();
-        checks.insert("partial_plan_clears_other_station_form", window.findChild<QLineEdit *>("paramEdit_0_0")->text().isEmpty()
-            && window.findChild<QLineEdit *>("paramEdit_0_2")->text() == "44");
-        window.findChild<QAbstractButton *>("btnBackMonitor")->click();
-        window.findChild<QAbstractButton *>("cardDetail_0")->click();
-        checks.insert("detail_reopen_does_not_duplicate_live_log", window.findChild<QPlainTextEdit *>("detailLog")
-            ->toPlainText().count(QStringLiteral("fixture-unique-live-log")) == 1);
-        window.findChild<QAbstractButton *>("btnBackMonitor")->click();
-    }
-
-    auto complete = [&](const QString &reason) {
-        if (finished) return;
-        finished = true;
-        checks.insert("actual_mainwindow_created", true);
-        checks.insert("stage_toggle_checkboxes_present",
-            window.findChild<QCheckBox *>("paramCheck_rmt") != nullptr
-            && window.findChild<QCheckBox *>("paramCheck_amt") != nullptr
-            && window.findChild<QCheckBox *>("paramCheck_mt") != nullptr);
-        checks.insert("live_websocket_connected", backend->isConnected());
-        checks.insert("clean_station_snapshot_received", snapshots > 0);
-        checks.insert("no_command_error", failure.isEmpty());
-        if (mode != "read-only" && mode != "fixture-silent") {
-            checks.insert("actual_start_button_clicked", clicked);
-            checks.insert("fresh_bios_start_confirmed", startedSuccessfully
-                && latest.value("started_unix_ms").toVariant().toLongLong() >= begin);
-            checks.insert("fresh_boot_id_matches_command", !backend->bootId(station).isEmpty()
-                && latest.value("boot_id").toVariant().toString() == backend->bootId(station));
-            checks.insert("no_firmware_execution_failure", latest.value("run_state").toString() != "failed"
-                && latest.value("verdict").toString() != "fail");
-            checks.insert("expected_phase_reached", latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0);
-            checks.insert("local_plan_finished_or_waiting", !backend->isBusy(station));
-        }
-        if (fixture && mode != "fixture-silent") {
-            checks.insert("old_failed_snapshot_after_start_ignored", fixture->oldFailedSnapshotSent && startedSuccessfully);
-            checks.insert("exactly_one_host_start", fixture->starts == 1);
-            checks.insert("all_expected_prompt_actions", fixture->actions == (fixture->runAmt ? 7 : 5));
-            checks.insert("no_duplicate_prompt_action", !fixture->duplicate);
-            checks.insert("only_clean_methods", !fixture->unexpected);
-            checks.insert("parameters_and_uip2_separation", fixture->correctParams);
-            checks.insert("reconnected_without_reboot_replay", fixture->disconnectTest && fixture->connections >= 2 && fixture->starts == 1);
-            checks.insert("unknown_channel_remains_idle", window.store()->station(0).channels.first().state == ChannelInfo::Idle);
-            checks.insert("raw_uart_replayed_after_reconnect", fixture->uartReplays >= 2);
-            checks.insert("missed_uart_bytes_displayed_once", window.store()->station(0).logs.join("\n")
-                .count(QStringLiteral("Fixture: stage action 1 completed")) == 1);
-            checks.insert("no_event_log_rpc", !fixture->methods.contains(QStringLiteral("ReadEventQueue")));
-            if (fixture->runAmt) {
-                checks.insert("amt_launched_once_per_cpu", fixture->amtLaunches == 2);
-                checks.insert("amt_exits_only_after_real_result", fixture->amtResultsReady && !fixture->earlyAmtExit);
-            }
-            if (fixture->unexpectedBootMode) {
-                checks.insert("unexpected_boot_failure_is_prompt", !failure.isEmpty()
-                    && reason != QStringLiteral("verification timeout")
-                    && QDateTime::currentMSecsSinceEpoch() - begin < 10000);
-                checks.insert("unexpected_boot_stopped_with_pending_stage", fixture->changedBoot
-                    && fixture->command.value("state").toString() == "running" && !backend->isBusy(station));
-            }
-        }
-        if (mode == "fixture-silent") {
-            checks.insert("silent_websocket_was_reconnected", fixture && fixture->connections >= 2);
-            checks.insert("state_received_after_reconnect", snapshots >= 2);
-            checks.insert("watchdog_never_issued_host_start", fixture && fixture->starts == 0);
-        }
-        if (!parser.value("screenshot").isEmpty())
-            checks.insert("screenshot_saved", window.grab().save(parser.value("screenshot")));
-        bool pass = reason.isEmpty();
-        for (auto i = checks.begin(); i != checks.end(); ++i) pass = pass && i.value().toBool();
-        QJsonArray methods;
-        if (fixture) for (const QString &method : fixture->methods) methods.append(method);
-        const QJsonObject report{{"pass", pass}, {"mode", mode}, {"reason", reason}, {"command_error", failure},
-            {"checks", checks}, {"url", backend->url()}, {"phase_history", phases}, {"snapshots", states},
-            {"snapshot_count", snapshots}, {"log_count", logs}, {"fixture_methods", methods},
-            {"command_boot_id", backend->bootId(station)}, {"elapsed_ms", QDateTime::currentMSecsSinceEpoch() - begin}};
-        const bool written = writeJson(parser.value("report"), report);
-        qInfo().noquote() << QJsonDocument(report).toJson(QJsonDocument::Compact);
-        app.exit(pass && written ? 0 : 1);
-    };
-    QTimer poll;
-    poll.setInterval(100);
-    QObject::connect(&poll, &QTimer::timeout, &app, [&] {
-        if (!failure.isEmpty()) { complete(failure); return; }
-        if (mode == "read-only" || mode == "fixture-silent") {
-            if (mode == "fixture-silent") {
-                if (fixture->connections >= 2 && snapshots >= 2) complete({});
-                return;
-            }
-            if (snapshots > 0 && QDateTime::currentMSecsSinceEpoch() - begin >= 3000) complete({});
-            return;
-        }
-        if (!clicked && snapshots > 0) {
-            QAbstractButton *button = window.findChild<QAbstractButton *>(QStringLiteral("startTest_%1").arg(station));
-            if (!button || !button->isEnabled()) return;
-            clicked = true;
-            button->click();
-            checks.insert("start_button_always_enabled_while_busy", button->isEnabled());
-        }
-        if (clicked && startedSuccessfully && !backend->isBusy(station)
-            && latest.value("phase").toString().compare(parser.value("expect-phase"), Qt::CaseInsensitive) == 0) {
-            if (parser.value("expect-phase").compare("mt", Qt::CaseInsensitive) == 0
-                && latest.value("run_state").toString() != "completed") return;
-            if (fixture) {
-                if (!fixtureCompletedAt) fixtureCompletedAt = QDateTime::currentMSecsSinceEpoch();
-                if (QDateTime::currentMSecsSinceEpoch() - fixtureCompletedAt < 2000) return;
-            }
-            complete({});
-        }
-    });
-    poll.start();
-    QTimer::singleShot(qMax(5, parser.value("timeout").toInt()) * 1000, &app,
-                      [&] { complete(QStringLiteral("verification timeout")); });
-    const int code = app.exec();
-    // These app-context lambdas capture locals declared after window; remove
-    // them before stack unwinding can destroy those captured variables.
-    QObject::disconnect(backend, nullptr, &app, nullptr);
-    delete fixture;
-    return code;
-}

+ 0 - 10
qt-client/tests/qt_clean_probe.pro

@@ -1,10 +0,0 @@
-QT += core gui widgets serialport websockets printsupport
-CONFIG += c++11 console
-CONFIG -= app_bundle
-TARGET = QtCleanProbe
-TEMPLATE = app
-INCLUDEPATH += $$PWD/../src $$PWD/../src/3rdparty/qcustomplot
-SOURCES += $$PWD/qt_clean_probe.cpp $$PWD/../src/mainwindow.cpp $$PWD/../src/overviewview.cpp $$PWD/../src/detailview.cpp $$PWD/../src/powerbutton.cpp $$PWD/../src/stationdata.cpp $$PWD/../src/localplans.cpp $$PWD/../src/backendlink.cpp $$PWD/../src/comworker.cpp $$PWD/../src/sltproto.cpp $$PWD/../src/comanager.cpp $$PWD/../src/3rdparty/qcustomplot/qcustomplot.cpp
-HEADERS += $$PWD/../src/mainwindow.h $$PWD/../src/overviewview.h $$PWD/../src/detailview.h $$PWD/../src/powerbutton.h $$PWD/../src/stationdata.h $$PWD/../src/localplans.h $$PWD/../src/backendlink.h $$PWD/../src/comworker.h $$PWD/../src/sltproto.h $$PWD/../src/comanager.h $$PWD/../src/3rdparty/qcustomplot/qcustomplot.h
-FORMS += $$PWD/../src/mainwindow.ui
-RESOURCES += $$PWD/../src/resources.qrc

+ 0 - 95
scripts/collect_live_evidence.py

@@ -1,95 +0,0 @@
-#!/usr/bin/env python3
-"""Collect actual API and console evidence after a Qt live run (read-only)."""
-import argparse
-import asyncio
-import json
-from pathlib import Path
-import re
-import shlex
-import subprocess
-
-import aiohttp
-
-
-async def rpc(ws, method, params):
-    await ws.send_json({'v': 1, 'id': method, 'method': method, 'params': params})
-    async with asyncio.timeout(20):
-        while True:
-            frame = await ws.receive_json()
-            if frame.get('id') == method:
-                if not frame.get('ok'):
-                    raise RuntimeError(str(frame.get('error')))
-                return frame['result']
-
-
-async def main():
-    parser = argparse.ArgumentParser()
-    parser.add_argument('--label', required=True)
-    parser.add_argument('--output-dir', default='evidence')
-    parser.add_argument('--host', default='192.168.2.79')
-    parser.add_argument('--expect-errhandle', action='store_true')
-    args = parser.parse_args()
-    if not re.fullmatch(r'[a-zA-Z0-9_.-]+', args.label):
-        raise SystemExit('Invalid evidence label')
-    output = Path(args.output_dir) / args.label
-    output.mkdir(parents=True, exist_ok=True)
-    collected = {}
-    async with aiohttp.ClientSession() as session:
-        async with session.ws_connect(f'http://{args.host}:8080/ws') as full:
-            for method, params in (
-                ('GetSystemInfo', {}),
-                ('GetStationControl', {'station_id': 'S1'}),
-                ('GetDiagnostic', {'station_id': 'S1'}),
-                ('GetQueue', {'station_id': 'S1', 'limit': 100}),
-            ):
-                collected[method] = await rpc(full, method, params)
-        async with session.ws_connect(f'http://{args.host}:8080/ws?view=qt-clean') as clean:
-            collected['GetState'] = await rpc(clean, 'GetState', {})
-    (output / 'api.json').write_text(json.dumps(collected, ensure_ascii=False, indent=2) + '\n')
-    session_id = collected['GetDiagnostic']['session_id']
-    if not re.fullmatch(r'D-[a-zA-Z0-9_-]+', session_id):
-        raise RuntimeError('Unexpected diagnostic session identifier')
-    for name in ('sol.raw', 'events.jsonl', 'session.json'):
-        remote = f'/home/user/XJKJ-STL/data/diagnostics/S1/{session_id}/{name}'
-        with (output / name).open('wb') as target:
-            subprocess.run(['ssh', '-T', '-o', 'BatchMode=yes', f'user@{args.host}',
-                            'sudo -n cat ' + shlex.quote(remote)],
-                           stdout=target, stderr=subprocess.PIPE, check=True, timeout=30)
-    raw = (output / 'sol.raw').read_bytes().decode('utf-8', 'replace')
-    plain = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', raw)
-    lines = plain.splitlines()
-    excerpts = []
-    for i, line in enumerate(lines):
-        if ('errhandle' in line.lower() or 'Issue WARM RESET!' in line
-                or '[SYS_BIOS]Version:' in line or 'MRC_STATUS_RESET_REQUIRED' in line):
-            excerpts.append({'line': i + 1, 'text': line[:500], 'following': lines[i + 1:i + 4]})
-    cpus = sorted({int(match.group(1)) for match in re.finditer(
-        r'\[([01])\][^\r\n]*User input command is\s+errhandle disable', plain)})
-    state = next(x for x in collected['GetState']['stations'] if x['station_id'] == 'S1')
-    fw = collected['GetStationControl']['firmware']
-    start = next(x for x in collected['GetQueue']['items']
-                 if x['method'] == 'QtStartTest' and x['state'] == 'succeeded')
-    checks = {
-        'final_uefi_input_ready': state['input']['ready'] and state['input']['stage'] == 'uefi',
-        'start_matches_current_boot': start['result']['boot_id'] == state['boot_id'],
-        'no_false_memory_pass': state['verdict'] != 'pass',
-    }
-    if args.expect_errhandle:
-        checks['both_cpu_errhandle_disable_echoed'] = cpus == [0, 1]
-    summary = {
-        'label': args.label, 'system': collected['GetSystemInfo'],
-        'checks': checks, 'passed': all(checks.values()),
-        'memory_test': 'NOT_TESTED', 'session_id': session_id,
-        'boot_id': state['boot_id'], 'boot_sequence': fw['boot_sequence'],
-        'start': start['result'], 'errhandle_disable_cpu_ids': cpus,
-        'last_uip_apply': collected['GetStationControl']['last_uip_apply'],
-        'excerpts': excerpts,
-    }
-    (output / 'summary.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n')
-    print(json.dumps({k: v for k, v in summary.items()
-                      if k not in ('last_uip_apply', 'excerpts')}, ensure_ascii=False, indent=2))
-    return 0 if summary['passed'] else 1
-
-
-if __name__ == '__main__':
-    raise SystemExit(asyncio.run(main()))

+ 0 - 86
scripts/deploy_qt_release.py

@@ -1,86 +0,0 @@
-#!/usr/bin/env python3
-"""Deploy an already-built Qt-clean candidate, preserving the former container."""
-import argparse
-import datetime
-import json
-import os
-from pathlib import Path
-import subprocess
-import tarfile
-import time
-
-
-def run(argv, **kwargs):
-    return subprocess.run(argv, check=True, text=True, capture_output=True, **kwargs).stdout.strip()
-
-
-def main():
-    parser = argparse.ArgumentParser()
-    parser.add_argument('--image', required=True)
-    parser.add_argument('--release', required=True)
-    args = parser.parse_args()
-    release = Path(args.release).resolve()
-    production = Path('/home/user/XJKJ-STL')
-    evidence = release / 'evidence'
-    evidence.mkdir(parents=True, exist_ok=True)
-    container = 'xjkj-stl-backend'
-    previous = json.loads(run(['docker', 'inspect', container]))[0]
-    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
-    saved_name = 'xjkj-stl-backend-before-qt-' + stamp.lower()
-    backup = production.parent / 'XJKJ-STL-backups' / ('before-qt-' + stamp)
-    backup.mkdir(parents=True)
-    private = release / '.runtime.env'
-    # Preserve the existing authorized runtime credentials without displaying them.
-    values = [value for value in previous['Config']['Env']
-              if value.split('=', 1)[0].startswith('STL_')
-              and not value.startswith('STL_BUILD_COMMIT=')]
-    private.write_text('\n'.join(values) + '\n')
-    private.chmod(0o600)
-    report = {'started_utc': stamp, 'image': args.image,
-              'previous_image': previous['Config']['Image'],
-              'previous_container': saved_name, 'backup': str(backup),
-              'original_source_directory': str(production), 'passed': False}
-    renamed = False
-    try:
-        run(['docker', 'stop', '--time', '120', container])
-        with tarfile.open(backup / 'config-data.tar.gz', 'w:gz') as archive:
-            for name in ('config', 'data'):
-                archive.add(production / name, arcname=name)
-        run(['docker', 'rename', container, saved_name])
-        renamed = True
-        run(['docker', 'run', '-d', '--name', container, '--restart', 'unless-stopped',
-             '--stop-timeout', '120', '--network', 'host', '--env-file', str(private),
-             '-v', str(production / 'config') + ':/app/config:ro',
-             '-v', str(production / 'data') + ':/app/data',
-             args.image, 'python3', '-m', 'stl_backend.server',
-             '--config', 'config/station0-live.json', '--listen', '0.0.0.0:50051',
-             '--web-listen', '0.0.0.0:8080', '--data-dir', '/app/data'])
-        for _ in range(25):
-            p = subprocess.run(['docker', 'exec', container, 'python3', '-c',
-                                "import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/', timeout=2); assert r.status == 200"],
-                               capture_output=True, text=True)
-            if p.returncode == 0:
-                report['passed'] = True
-                break
-            time.sleep(1)
-        if not report['passed']:
-            raise RuntimeError('Candidate did not become HTTP-ready')
-        report['container_id'] = run(['docker', 'inspect', '--format', '{{.Id}}', container])
-        report['runtime_version'] = run(['docker', 'exec', container, 'python3', '-c',
-                                         'import stl_backend; print(stl_backend.__version__)'])
-    except Exception as exc:
-        report['error'] = str(exc)
-        if renamed:
-            subprocess.run(['docker', 'rm', '-f', container], capture_output=True)
-            run(['docker', 'rename', saved_name, container])
-        run(['docker', 'start', container])
-        report['rolled_back'] = True
-        raise
-    finally:
-        private.unlink(missing_ok=True)
-        (evidence / 'deployment.json').write_text(json.dumps(report, indent=2) + '\n')
-        print(json.dumps(report, indent=2), flush=True)
-
-
-if __name__ == '__main__':
-    main()

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


+ 0 - 21
scripts/generate_proto.py

@@ -1,21 +0,0 @@
-"""Generate Python stubs into an isolated package; no hand-written protocol codec."""
-from pathlib import Path
-import subprocess
-import sys
-import grpc_tools
-
-root = Path(__file__).resolve().parents[1]
-out = root / "src" / "stl_backend" / "generated"
-out.mkdir(parents=True, exist_ok=True)
-subprocess.run([
-    sys.executable, "-m", "grpc_tools.protoc",
-    f"-I{root / 'proto' / 'stl' / 'v1'}",
-    f"-I{Path(grpc_tools.__file__).parent / '_proto'}",
-    f"--python_out={out}", f"--grpc_python_out={out}",
-    str(root / "proto" / "stl" / "v1" / "bench.proto"),
-], check=True)
-p = out / "bench_pb2_grpc.py"
-p.write_text(p.read_text().replace("import bench_pb2 as", "from . import bench_pb2 as"))
-(out / "__init__.py").write_text('"""Generated by scripts/generate_proto.py."""\n')
-print("Generated", out)
-

+ 0 - 176
scripts/package_delivery.py

@@ -1,176 +0,0 @@
-#!/usr/bin/env python3
-"""Package committed source and collected evidence; never invent verification results."""
-from __future__ import annotations
-
-import argparse
-from datetime import datetime, timezone
-import hashlib
-import io
-import json
-import os
-from pathlib import Path
-import re
-import subprocess
-import tarfile
-import zipfile
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-def git(*args: str) -> str:
-    return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
-
-
-def private_path(path: str) -> bool:
-    """Exclude runtime credentials and private keys, keeping empty example templates."""
-    name = Path(path).name.lower()
-    if name.endswith(".example"):
-        return False
-    return (name == ".env" or name.startswith(".env.") or name.endswith(".env")
-            or name.endswith((".local.env", ".key", ".pem", ".p12", ".pfx"))
-            or name in {"id_rsa", "id_ed25519", "id_ecdsa"})
-
-
-def file_hash(path: Path) -> str:
-    digest = hashlib.sha256()
-    with path.open("rb") as stream:
-        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
-            digest.update(chunk)
-    return digest.hexdigest()
-
-
-def write_archive(path: Path, files, metadata: dict, secrets: list[bytes]) -> dict:
-    """Hash the actual archived bytes, including ignored raw evidence files."""
-    entries = []
-    overlap = max((len(value) for value in secrets), default=1) - 1
-    try:
-        with zipfile.ZipFile(path, "x", zipfile.ZIP_DEFLATED) as archive:
-            for name, source, mode in files:
-                digest, size, tail = hashlib.sha256(), 0, b""
-                stream = io.BytesIO(source) if isinstance(source, bytes) else source.open("rb")
-                entry = zipfile.ZipInfo(name)
-                entry.create_system = 3
-                entry.external_attr = (0o100000 | mode) << 16
-                entry.compress_type = zipfile.ZIP_DEFLATED
-                with stream, archive.open(entry, "w") as output:
-                    for chunk in iter(lambda: stream.read(1024 * 1024), b""):
-                        scanned = tail + chunk
-                        if any(value in scanned for value in secrets):
-                            raise ValueError(f"Runtime credential found in {name}; archive not retained")
-                        tail = scanned[-overlap:] if overlap else b""
-                        digest.update(chunk)
-                        size += len(chunk)
-                        output.write(chunk)
-                entries.append({"path": name, "bytes": size, "sha256": digest.hexdigest()})
-            manifest = {**metadata, "file_count": len(entries), "files": entries}
-            archive.writestr("MANIFEST.json", json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
-            archive.writestr("SHA256SUMS", "".join(f"{e['sha256']}  {e['path']}\n" for e in entries))
-    except FileExistsError:
-        raise
-    except Exception:
-        path.unlink(missing_ok=True)
-        raise
-    return {"path": str(path), "file": path.name, "bytes": path.stat().st_size,
-            "sha256": file_hash(path), "kind": metadata["archive_type"]}
-
-
-def source_files() -> list[tuple[str, bytes, int]]:
-    data = subprocess.check_output(["git", "archive", "--format=tar", "HEAD"], cwd=ROOT)
-    files = []
-    with tarfile.open(fileobj=io.BytesIO(data)) as archive:
-        for item in archive:
-            if item.isdir():
-                continue
-            if not item.isfile():
-                raise ValueError(f"Unexpected non-file in source tree: {item.name}")
-            if private_path(item.name):
-                raise ValueError(f"Remove tracked runtime credentials before release: {item.name}")
-            files.append(("source/" + item.name, archive.extractfile(item).read(),
-                          0o755 if item.mode & 0o111 else 0o644))
-    return files
-
-
-def evidence_files(data_dir: Path, extra_dirs: list[Path]):
-    roots = [data_dir / "evidence",
-             data_dir / "runs", data_dir / "artifacts", data_dir / "diagnostics", *extra_dirs]
-    files, skipped, seen = [], [], set()
-    for index, folder in enumerate(roots):
-        if not folder.is_dir():
-            continue
-        try:
-            prefix = folder.relative_to(ROOT).as_posix()
-        except ValueError:
-            prefix = f"external-{index}/{folder.name}"
-        for path in sorted(folder.rglob("*")):
-            if path.is_dir():
-                continue
-            name = prefix + "/" + path.relative_to(folder).as_posix()
-            if path.is_symlink() or private_path(name):
-                skipped.append(name)
-                continue
-            if not path.is_file() or path.resolve() in seen:
-                continue
-            seen.add(path.resolve())
-            files.append(("evidence/" + name, path, 0o644))
-    for path in sorted(data_dir.glob("*.log")):
-        if path.is_file() and not path.is_symlink() and path.resolve() not in seen:
-            files.append(("evidence/data/" + path.name, path, 0o644))
-    return files, skipped
-
-
-def main() -> None:
-    parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("--output-dir", type=Path, default=ROOT / "dist")
-    parser.add_argument("--data-dir", type=Path, default=ROOT / "data")
-    parser.add_argument("--evidence-dir", action="append", type=Path, default=[])
-    parser.add_argument("--session", help="Session label; defaults to the UTC packaging timestamp")
-    parser.add_argument("--mode", choices=("hardware", "simulated", "mixed"), default="mixed")
-    parser.add_argument("--secret-env", action="append", default=[],
-                        help="Also reject file bytes containing the value of this environment variable")
-    args = parser.parse_args()
-    try:
-        if git("branch", "--show-current") != "dev":
-            raise ValueError("Release from the dev branch")
-        if git("status", "--porcelain", "--untracked-files=normal"):
-            raise ValueError("Commit source changes before packaging; ignored data/logs may remain")
-        commit = git("rev-parse", "HEAD")
-        version = git("show", "HEAD:VERSION")
-        if not re.fullmatch(r"\d+\.\d+\.\d+", version):
-            raise ValueError("Committed VERSION must be X.Y.Z")
-        now = datetime.now(timezone.utc)
-        stamp = now.strftime("%Y%m%dT%H%M%SZ")
-        session = args.session or stamp
-        if not re.fullmatch(r"[A-Za-z0-9_.-]+", session):
-            raise ValueError("Use letters, digits, dot, dash or underscore in the session label")
-        secret_names = [f"STL_BMC_S{i}_PASSWORD" for i in range(1, 5)] + args.secret_env
-        secrets = [os.environ[name].encode() for name in secret_names if os.environ.get(name)]
-        metadata = {
-            "version": version, "commit": commit, "branch": "dev",
-            "tag": f"v{version}" if f"v{version}" in git("tag", "--points-at", "HEAD").splitlines() else None,
-            "working_tree_dirty": False, "created_utc": now.isoformat(), "session": session,
-            "mode": args.mode, "verification": "See the included review and raw evidence; packaging does not verify hardware",
-            "push_status": "pending_push" if not git("remote") else "not_checked",
-            "windows_transfer": "not_performed_by_this_script",
-            "history_bundle": "omitted; earlier history contains runtime credentials",
-        }
-        source = source_files()
-        source = [item for item in source if item[0] != "source/COMMIT"]
-        source.extend([("source/COMMIT", (commit + "\n").encode(), 0o644),
-                       ("COMMIT", (commit + "\n").encode(), 0o644)])
-        debug, skipped = evidence_files(args.data_dir.resolve(), [p.resolve() for p in args.evidence_dir])
-        args.output_dir.mkdir(parents=True, exist_ok=True)
-        prefix = f"xjkj-stl-v{version}-{commit[:7]}-{stamp}"
-        archives = [write_archive(args.output_dir / f"{prefix}-source-analysis.zip", source,
-                                  {**metadata, "archive_type": "source_and_analysis"}, secrets),
-                    write_archive(args.output_dir / f"{prefix}-{session}-debug-logs.zip", debug,
-                                  {**metadata, "archive_type": "raw_debug_logs", "skipped_files": skipped}, secrets)]
-        summary = {**metadata, "archives": archives}
-        receipt = args.output_dir / f"{prefix}-delivery.json"
-        receipt.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
-        print(json.dumps({**summary, "receipt": str(receipt)}, ensure_ascii=False, indent=2))
-    except (OSError, ValueError, subprocess.CalledProcessError) as exc:
-        parser.exit(1, f"Packaging failed: {exc}\n")
-
-
-if __name__ == "__main__":
-    main()

+ 0 - 44
scripts/probe_bmc.py

@@ -1,44 +0,0 @@
-#!/usr/bin/env python3
-"""Run inside the deployed container; secrets remain in its environment."""
-import argparse
-import datetime
-import json
-import os
-import subprocess
-import time
-
-
-def main():
-    parser = argparse.ArgumentParser()
-    parser.add_argument('--power-off', action='store_true')
-    parser.add_argument('--output')
-    args = parser.parse_args()
-    secret = os.environ.get('STL_BMC_S1_PASSWORD')
-    if not secret:
-        raise SystemExit('STL_BMC_S1_PASSWORD is not available')
-    child_env = dict(os.environ, IPMI_PASSWORD=secret)
-    prefix = ['ipmitool', '-I', 'lanplus', '-H', '192.168.0.100', '-U', 'ADMIN',
-              '-E', '-C', '17', '-N', '2', '-R', '2']
-    report = {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
-              'host': '192.168.0.100', 'checks': []}
-    commands = [['mc', 'info'], ['chassis', 'power', 'status'], ['sol', 'info', '1']]
-    if args.power_off:
-        commands = [['chassis', 'power', 'status'], ['chassis', 'power', 'off']]
-    for command in commands:
-        begin = time.monotonic()
-        p = subprocess.run(prefix + command, env=child_env, capture_output=True,
-                           text=True, timeout=30)
-        report['checks'].append({'command': ' '.join(command), 'returncode': p.returncode,
-                                 'output': (p.stdout + p.stderr).replace(secret, '[redacted]').strip(),
-                                 'elapsed_s': round(time.monotonic()-begin, 3)})
-    report['passed'] = all(x['returncode'] == 0 for x in report['checks'])
-    rendered = json.dumps(report, ensure_ascii=False, indent=2)
-    print(rendered)
-    if args.output:
-        from pathlib import Path
-        Path(args.output).write_text(rendered + '\n')
-    return 0 if report['passed'] else 1
-
-
-if __name__ == '__main__':
-    raise SystemExit(main())

+ 0 - 74
scripts/probe_ipmi_sol.py

@@ -1,74 +0,0 @@
-#!/usr/bin/env python3
-"""Bounded IPMI SOL roundtrip at an independently verified UEFI Shell prompt."""
-import asyncio
-import datetime
-import json
-import os
-from pathlib import Path
-import re
-import subprocess
-
-
-async def main():
-    env = os.environ.copy()
-    env.update(STL_SOL_HOST='192.168.0.100', STL_SOL_USER='ADMIN',
-               STL_SOL_PASSWORD=env['STL_BMC_S1_PASSWORD'], STL_SOL_CIPHER_SUITE='17')
-    folder = Path('/app/data/evidence/qt-clean-080')
-    folder.mkdir(parents=True, exist_ok=True)
-    report = {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
-              'transport': 'ipmi_sol', 'input_hex': '0d', 'statuses': [],
-              'ready': False, 'passed': False}
-    proc = await asyncio.create_subprocess_exec('python3', 'native/stl_sol_bridge.py',
-        env=env, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
-        stderr=asyncio.subprocess.PIPE)
-    stdout_task = asyncio.create_task(proc.stdout.read())
-    try:
-        deadline = asyncio.get_running_loop().time() + 22
-        while asyncio.get_running_loop().time() < deadline:
-            line = await asyncio.wait_for(proc.stderr.readline(), 22)
-            if not line:
-                break
-            status = json.loads(line)
-            report['statuses'].append(status)
-            if status.get('event') == 'ready':
-                report['ready'] = True
-                break
-            if status.get('event') == 'error':
-                break
-        if report['ready']:
-            proc.stdin.write(b'\r')
-            await proc.stdin.drain()
-            await asyncio.sleep(3)
-        proc.stdin.close()
-        try:
-            await asyncio.wait_for(proc.wait(), 5)
-        except asyncio.TimeoutError:
-            proc.terminate()
-            await asyncio.wait_for(proc.wait(), 5)
-        raw = await stdout_task
-        (folder / 'ipmi-sol-roundtrip.raw').write_bytes(raw)
-        text = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', raw.decode('utf-8', 'replace'))
-        report['bytes_received'] = len(raw)
-        report['shell_prompt_seen'] = bool(re.search(r'(?:Shell|FS\d+:[^\r\n>]*)>', text, re.I))
-        report['output_excerpt'] = text[-1500:]
-        report['passed'] = report['ready'] and report['shell_prompt_seen']
-    except Exception as exc:
-        report['error'] = type(exc).__name__ + ': ' + str(exc)
-    finally:
-        if proc.returncode is None:
-            proc.terminate()
-            await proc.wait()
-        if report['ready']:
-            child_env = dict(env, IPMI_PASSWORD=env['STL_SOL_PASSWORD'])
-            result = subprocess.run(['ipmitool', '-I', 'lanplus', '-H', env['STL_SOL_HOST'],
-                '-U', env['STL_SOL_USER'], '-E', '-C', '17', 'sol', 'deactivate'],
-                env=child_env, capture_output=True, text=True, timeout=15)
-            report['cleanup_returncode'] = result.returncode
-        rendered = json.dumps(report, ensure_ascii=False, indent=2)
-        (folder / 'ipmi-sol-roundtrip.json').write_text(rendered + '\n')
-        print(rendered)
-    return 0 if report['passed'] else 1
-
-
-if __name__ == '__main__':
-    raise SystemExit(asyncio.run(main()))

+ 0 - 9
scripts/run_container.sh

@@ -1,9 +0,0 @@
-#!/bin/sh
-set -eu
-cd "$(dirname "$0")/.."
-export STL_VERSION="$(cat VERSION)"
-export STL_BUILD_COMMIT="${STL_BUILD_COMMIT:-$(git rev-parse HEAD 2>/dev/null || cat COMMIT 2>/dev/null || printf unknown)}"
-if docker compose version >/dev/null 2>&1; then
-    exec docker compose --env-file local.env "$@"
-fi
-exec docker-compose --env-file local.env "$@"

+ 0 - 33
scripts/run_qt_fixtures.py

@@ -1,33 +0,0 @@
-#!/usr/bin/env python3
-import json
-import os
-from pathlib import Path
-import subprocess
-
-release = Path('/home/user/XJKJ-STL-qt-clean-0.8.0')
-binary = release / 'qt-client/build-probe/QtCleanProbe'
-evidence = release / 'evidence'
-env = dict(os.environ, QT_QPA_PLATFORM='offscreen')
-env.pop('LD_LIBRARY_PATH', None)
-summary = []
-for mode in ['fixture', 'fixture-amt', 'fixture-fail', 'fixture-unexpected-boot']:
-    report = evidence / ('qt-' + mode + '.json')
-    with (evidence / ('qt-' + mode + '.log')).open('w') as out:
-        p = subprocess.run([str(binary), '--mode', mode, '--report', str(report),
-            '--screenshot', str(evidence / ('qt-' + mode + '.png')), '--timeout', '45'],
-            env=env, stdout=out, stderr=subprocess.STDOUT, timeout=60)
-    data = json.loads(report.read_text()) if report.exists() else {}
-    negative = mode in ('fixture-fail', 'fixture-unexpected-boot')
-    passed = p.returncode == (1 if negative else 0) and data.get('pass') is not negative
-    if negative:
-        passed = passed and data.get('checks', {}).get('no_firmware_execution_failure') is False
-    if mode == 'fixture-unexpected-boot':
-        passed = passed and data.get('checks', {}).get('unexpected_boot_failure_is_prompt') is True
-        passed = passed and data.get('checks', {}).get('unexpected_boot_stopped_with_pending_stage') is True
-    row = {'mode': mode, 'exit_code': p.returncode, 'expected_negative': negative,
-           'passed': passed, 'checks': len(data.get('checks', {})),
-           'false_checks': [key for key, value in data.get('checks', {}).items() if value is False]}
-    summary.append(row)
-    print(json.dumps(row), flush=True)
-(evidence / 'qt-fixtures-summary.json').write_text(json.dumps(summary, indent=2) + '\n')
-raise SystemExit(0 if all(row['passed'] for row in summary) else 1)

Разница между файлами не показана из-за своего большого размера
+ 0 - 846
scripts/test_web_browser.mjs


+ 0 - 112
scripts/test_web_command_recovery.mjs

@@ -1,112 +0,0 @@
-// Exercise the actual app command/queue callbacks with a tiny deterministic DOM.
-import assert from 'node:assert/strict';
-import {readFile} from 'node:fs/promises';
-import vm from 'node:vm';
-
-const source = await readFile(new URL('../src/stl_backend/web/app.js', import.meta.url), 'utf8');
-function fixture() {
-  const elements = new Map(), calls = [];
-  let services, handler;
-  function element(id) {
-    if (!elements.has(id)) {
-      const classes = new Set();
-      elements.set(id, {value:'', textContent:'', innerHTML:'', dataset:{}, disabled:false,
-        classList:{add:value=>classes.add(value),remove:value=>classes.delete(value),contains:value=>classes.has(value),
-          toggle:(value,yes)=>yes?classes.add(value):classes.delete(value)},
-        addEventListener() {}, querySelectorAll:()=>[]});
-    }
-    return elements.get(id);
-  }
-  const window = new EventTarget();
-  Object.assign(window, {
-    stlTransport:{call:async(method,params)=>{calls.push({method,params});return handler(method,params);}},
-    stlFirmware:{init:api=>{services=api;},snapshot:()=>({}),capabilities:()=>({}),render(){},refresh:async()=>{}},
-    stlBootPlan:{init(){}}, stlAmt:{init(){}}, stlDimms:{init(){},render(){}}, stlStages:{init(){},render(){}},
-    stlNavigation:{updateStations(){}},
-  });
-  handler = async method => {
-    if (method==='GetSystemInfo')return {mode:'simulated',version:'0.7.1'};
-    if (method==='ListStations')return {stations:[]};
-    if (method==='GetQueue')return {items:[]};
-    if (method==='ReadEventQueue')return {events:[],next_after_sequence:'0'};
-    if (method==='GetDiagnostic')return {state:'closed'};
-    throw new Error('Unexpected API call '+method);
-  };
-  const baseHandler=handler;
-  vm.runInNewContext(source, {window,document:{getElementById:element,querySelectorAll:()=>[]},
-    TextDecoder,TextEncoder,CustomEvent,setTimeout,clearTimeout,setInterval:()=>0,URL,Blob,atob,btoa});
-  return {services,calls,element,window,setHandler:fn=>{handler=fn;},baseHandler,
-    refreshQueue:()=>element('btn-refresh-commands').onclick()};
-}
-const businessError=(code,message=code)=>Object.assign(new Error(message),{code});
-const f=fixture();
-const lost=businessError('DISCONNECTED','socket closed');
-let accepted=[];
-f.setHandler(async(method,params)=>{
-  if(method==='EnqueueCommand'){accepted.push({...params});throw lost;}
-  if(method==='GetQueueItem')throw businessError('NOT_FOUND');
-  return f.baseHandler(method,params);
-});
-const first=f.services.command('StationPower',{station_id:'S1',action:'host_reset'},'复位 S1');
-const second=f.services.command('StationPower',{station_id:'S2',action:'host_reset'},'复位 S2');
-let firstError,secondError;
-await assert.rejects(first,error=>{firstError=error;return error.code==='DISCONNECTED'&&error.message.includes('提交结果待核对');});
-await assert.rejects(second,error=>{secondError=error;return error.code==='DISCONNECTED';});
-assert.equal(firstError.command_id,accepted[0].command_id);
-assert.equal(secondError.command_id,accepted[1].command_id);
-assert.notEqual(firstError.command_id,secondError.command_id);
-assert.ok(!secondError.message.includes(firstError.command_id),'Each failed write keeps its own id and message');
-assert.equal(lost.message,'socket closed','Shared disconnect reasons are not mutated');
-
-await f.refreshQueue();
-assert.ok(f.calls.some(call=>call.method==='GetQueueItem'&&call.params.command_id===firstError.command_id));
-assert.ok(f.calls.some(call=>call.method==='GetQueueItem'&&call.params.command_id===secondError.command_id));
-assert.ok(f.element('command-queue-updated').textContent.includes('待核对提交 2'));
-assert.ok(f.element('command-queue-error').classList.contains('hidden'),'Unknown acceptance does not fail all queue polling');
-
-const items=accepted.map((request,index)=>({...request,sequence:String(index+1),state:'succeeded',
-  created_unix_ms:'1',updated_unix_ms:'2',detail:'',result:{},error_code:''}));
-f.setHandler(async(method,params)=>{
-  if(method==='EnqueueCommand')throw new Error('A write must never be replayed');
-  if(method==='GetQueue')return {items};
-  if(method==='GetQueueItem')return items.find(item=>item.command_id===params.command_id);
-  return f.baseHandler(method,params);
-});
-await f.refreshQueue();
-assert.equal(f.calls.filter(call=>call.method==='EnqueueCommand').length,2);
-assert.ok(!f.element('command-queue-updated').textContent.includes('待核对提交'));
-assert.ok(f.element('commands-tbody').innerHTML.includes(firstError.command_id));
-assert.ok(f.element('commands-tbody').innerHTML.includes(secondError.command_id));
-
-const denied=fixture();
-denied.setHandler(async(method,params)=>{
-  if(method==='EnqueueCommand')throw businessError('FAILED_PRECONDITION');
-  if(method==='GetQueueItem')throw new Error('Rejected commands must not be tracked as uncertain');
-  return denied.baseHandler(method,params);
-});
-await assert.rejects(denied.services.command('StartAmt',{},'AMT'),error=>error.code==='FAILED_PRECONDITION');
-await denied.refreshQueue();
-assert.equal(denied.calls.filter(call=>call.method==='GetQueueItem').length,0);
-
-const polling=fixture();
-let releaseInfo;
-polling.setHandler((method,params)=>method==='GetSystemInfo'?
-  new Promise(resolve=>{releaseInfo=()=>resolve({mode:'simulated',version:'0.7.1'});}):polling.baseHandler(method,params));
-polling.window.dispatchEvent(new CustomEvent('stl:transport-state',{detail:{state:'open',generation:2}}));
-polling.window.dispatchEvent(new CustomEvent('stl:transport-state',{detail:{state:'open',generation:3}}));
-assert.equal(polling.calls.filter(call=>call.method==='GetSystemInfo').length,1,'Reconnect refresh cannot reenter an active poll');
-assert.equal(polling.calls.filter(call=>call.method==='ListStations').length,1);
-releaseInfo();
-for(let n=0;n<30;n++)await Promise.resolve();
-assert.equal(polling.calls.filter(call=>call.method==='GetQueue').length,1);
-
-const queuePolling=fixture();
-let releaseQueue;
-queuePolling.setHandler((method,params)=>method==='GetQueue'?
-  new Promise(resolve=>{releaseQueue=()=>resolve({items:[]});}):queuePolling.baseHandler(method,params));
-queuePolling.element('command-station-filter').onchange();
-queuePolling.element('command-station-filter').onchange();
-assert.equal(queuePolling.calls.filter(call=>call.method==='GetQueue').length,1,'Queue refresh has its own in-flight guard');
-releaseQueue();
-for(let n=0;n<10;n++)await Promise.resolve();
-console.log('WEB_COMMAND_RECOVERY_SUCCESS: lost acknowledgement ids, independent errors, NOT_FOUND recovery, queue/poll guards, no write replay');

+ 0 - 97
scripts/test_web_transport.mjs

@@ -1,97 +0,0 @@
-// Deterministic browser-transport checks. No server, device or network is used.
-import assert from 'node:assert/strict';
-import {readFile} from 'node:fs/promises';
-import vm from 'node:vm';
-
-const source = await readFile(new URL('../src/stl_backend/web/transport.js', import.meta.url), 'utf8');
-function fixture() {
-  const sockets = [], timers = new Map(), states = [];
-  let nextTimer = 0, now = 0, token = '';
-  class FakeSocket {
-    static OPEN = 1;
-    constructor(url) { this.url=url; this.readyState=0; this.sent=[]; sockets.push(this); }
-    open() { this.readyState=1; this.onopen?.({}); }
-    send(text) { assert.equal(this.readyState,1); this.sent.push(JSON.parse(text)); }
-    answer(id,result) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:true,result})}); }
-    fail(id,code,message) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:false,error:{code,message}})}); }
-    close() { if(this.readyState===3)return; this.readyState=3; this.onclose?.({}); }
-  }
-  const window = new EventTarget();
-  window.addEventListener('stl:transport-state', event=>states.push(event.detail.state));
-  vm.runInNewContext(source, {
-    window, location:{protocol:'https:',host:'bench.example:8443'}, WebSocket:FakeSocket,
-    CustomEvent, sessionStorage:{getItem:()=>token},
-    setTimeout:(fn,delay)=>{const id=++nextTimer;timers.set(id,{fn,when:now+delay});return id;},
-    clearTimeout:id=>timers.delete(id),
-  });
-  const flush = async()=>{await Promise.resolve();await Promise.resolve();};
-  async function tick(ms) {
-    const until=now+ms;
-    while(true) {
-      const next=[...timers].filter(([,timer])=>timer.when<=until).sort((a,b)=>a[1].when-b[1].when)[0];
-      if(!next)break;
-      timers.delete(next[0]);now=next[1].when;next[1].fn();await flush();
-    }
-    now=until;await flush();
-  }
-  return {api:window.stlTransport,sockets,states,timers,flush,tick,setToken:value=>{token=value;}};
-}
-
-const f=fixture();
-f.setToken('test-token');
-const first=f.api.call('GetStationControl',{station_id:'S1'});
-const second=f.api.call('GetQueue',{station_id:'S1'});
-assert.equal(f.sockets.length,1,'Concurrent calls share one connection');
-const socket=f.sockets[0];
-assert.equal(socket.url,'wss://bench.example:8443/ws');
-assert.equal(socket.sent.length,0,'Requests wait for the open handshake');
-socket.open();await f.flush();
-assert.equal(socket.sent.length,2);
-const [one,two]=socket.sent;
-assert.notEqual(one.id,two.id);
-assert.equal(one.v,1);assert.equal(one.authorization,'Bearer test-token');
-assert.deepEqual(one.params,{station_id:'S1'});
-socket.answer(two.id,{items:[]});socket.answer(one.id,{station_id:'S1',dimms:[]});
-assert.equal((await first).station_id,'S1');assert.equal((await second).items.length,0);
-assert.equal(f.api.snapshot().pending,0,'Out-of-order results match their own request IDs');
-
-f.setToken('');
-const missing=f.api.call('UnknownMethod');await f.flush();
-const missingFrame=socket.sent.at(-1);
-assert.equal('authorization' in missingFrame,false,'Empty optional token is omitted');
-const missingCheck=assert.rejects(missing,error=>error.code==='UNIMPLEMENTED'&&error.message.includes('unknown method'));
-socket.fail(missingFrame.id,'UNIMPLEMENTED','unknown method');await missingCheck;
-assert.equal(f.api.snapshot().state,'open','Business error does not break the connection');
-
-const uncertain=f.api.call('EnqueueCommand',{command_id:'original-command',method:'StationPower'});await f.flush();
-const uncertainCheck=assert.rejects(uncertain,error=>error.code==='DISCONNECTED');
-socket.close();await uncertainCheck;
-assert.equal(f.api.snapshot().pending,0);
-await f.tick(2000);
-assert.equal(f.sockets.length,2,'Disconnect opens a fresh channel automatically');
-const restored=f.sockets[1];restored.open();await f.flush();
-assert.equal(restored.sent.length,0,'Uncertain write is not replayed after reconnect');
-assert.equal(f.api.snapshot().generation,2);
-const fresh=f.api.call('GetQueueItem',{command_id:'original-command'});await f.flush();
-restored.answer(restored.sent[0].id,{command_id:'original-command',state:'succeeded'});
-assert.equal((await fresh).state,'succeeded','The UI can recover the original durable queue result');
-
-const late=f.api.call('GetStationControl',{station_id:'S1'});await f.flush();
-const lateId=restored.sent.at(-1).id;
-const timeoutCheck=assert.rejects(late,error=>error.code==='REQUEST_TIMEOUT');
-await f.tick(20000);await timeoutCheck;
-assert.equal(f.api.snapshot().pending,0);
-restored.answer(lateId,{station_id:'S1'});
-assert.equal(f.api.snapshot().pending,0,'Late responses do not recreate timed-out requests');
-const sentBefore=restored.sent.length;
-await f.tick(10000);
-assert.equal(restored.sent.length,sentBefore,'Timeout does not resend a request');
-
-const manual=f.api.reconnect();
-assert.equal(f.sockets.length,3);f.sockets[2].open();await manual;
-assert.equal(f.sockets[2].sent.length,0,'Manual channel reconnect also sends no device operation');
-f.api.disconnect();await f.tick(10000);
-assert.equal(f.sockets.length,3,'Page shutdown stops reconnect attempts');
-assert.equal(f.timers.size,0);
-assert.ok(f.states.includes('open')&&f.states.includes('disconnected')&&f.states.includes('closed'));
-console.log('WEB_TRANSPORT_TEST_SUCCESS: multiplexing, optional token, structured errors, reconnect, no write replay, timeout and shutdown');

+ 0 - 105
scripts/validate_live_actions.py

@@ -1,105 +0,0 @@
-#!/usr/bin/env python3
-"""At UEFI, verify idempotency, stale inputs, real directory I/O and missing EFI."""
-import argparse
-import asyncio
-import datetime
-import json
-from pathlib import Path
-import uuid
-import aiohttp
-
-
-class Client:
-    def __init__(self, ws):
-        self.ws, self.state = ws, None
-    async def call(self, method, params):
-        rid = uuid.uuid4().hex
-        await self.ws.send_json({'v': 1, 'id': rid, 'method': method, 'params': params})
-        async with asyncio.timeout(30):
-            while True:
-                frame = await self.ws.receive_json()
-                if frame.get('event') == 'state':
-                    self.state = frame['result']
-                if frame.get('id') == rid:
-                    if not frame.get('ok'):
-                        raise RuntimeError(str(frame.get('error')))
-                    return frame['result']
-    async def command(self, payload):
-        result = await self.call('StageAction', payload)
-        async with asyncio.timeout(60):
-            while result['state'] not in ('succeeded', 'failed', 'interrupted'):
-                await asyncio.sleep(.2)
-                result = await self.call('GetCommand', {'command_id': payload['command_id']})
-        return result
-    async def station(self):
-        value = await self.call('GetState', {})
-        return next(x for x in value['stations'] if x['station_id'] == 'S1')
-
-
-async def main():
-    parser = argparse.ArgumentParser()
-    parser.add_argument('--host', default='192.168.2.79:8080')
-    parser.add_argument('--output', required=True)
-    args = parser.parse_args()
-    report = {'observed_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
-              'checks': [], 'passed': False, 'memory_verdict': 'NOT_TESTED'}
-    def check(name, value, detail):
-        report['checks'].append({'name': name, 'passed': bool(value), 'detail': detail})
-        print(json.dumps({'name': name, 'passed': bool(value)}, ensure_ascii=False), flush=True)
-        if not value:
-            raise AssertionError(name)
-    try:
-        async with aiohttp.ClientSession() as session:
-            async with session.ws_connect('http://' + args.host + '/ws') as full_ws, \
-                       session.ws_connect('http://' + args.host + '/ws?view=qt-clean') as clean_ws:
-                full, clean = Client(full_ws), Client(clean_ws)
-                info = await full.call('GetSystemInfo', {})
-                report['system'] = info
-                state = await clean.station()
-                check('actual_uefi_ready', state['input']['ready'] and state['input']['stage'] == 'uefi',
-                      {'phase': state['phase'], 'boot_id': state['boot_id']})
-                queue = await full.call('GetQueue', {'station_id': 'S1', 'limit': 100})
-                started = next(x for x in queue['items'] if x['method'] == 'QtStartTest' and x['state'] == 'succeeded')
-                boot = state['boot_id']
-                duplicate = await clean.call('StartTest', {'station_id': 'S1', 'command_id': started['command_id']})
-                check('duplicate_real_start_does_not_reboot', duplicate['state'] == 'succeeded'
-                    and duplicate['result']['boot_id'] == boot and (await clean.station())['boot_id'] == boot,
-                    duplicate)
-                old = next(x for x in queue['items'] if x['method'] == 'QtStageAction'
-                           and x['arguments']['action'] == 'continue_uip')
-                stale = await clean.command({'station_id': 'S1', 'command_id': 'stale-' + uuid.uuid4().hex,
-                    'input_id': old['arguments']['input_id'], 'action': 'continue_uip'})
-                check('stale_real_prompt_rejected', stale['state'] == 'failed'
-                      and stale['error']['code'] == 'FAILED_PRECONDITION', stale)
-                state = await clean.station()
-                listing = await clean.command({'station_id': 'S1', 'command_id': 'listing-' + uuid.uuid4().hex,
-                    'input_id': state['input']['id'], 'action': 'list_uefi_files', 'path': 'FS0:\\EFI'})
-                check('real_uefi_directory_read', listing['state'] == 'succeeded'
-                      and isinstance(listing['result'].get('files'), list), listing)
-                state = await clean.station()
-                missing = 'FS0:\\EFI\\__qt_missing_' + uuid.uuid4().hex + '.efi'
-                mt = await clean.command({'station_id': 'S1', 'command_id': 'missing-' + uuid.uuid4().hex,
-                    'input_id': state['input']['id'], 'action': 'start_mt', 'mt': {'efi_path': missing}})
-                check('missing_efi_is_explicit_failure', mt['state'] == 'failed'
-                      and mt['error']['code'] == 'FAILED_PRECONDITION', mt)
-                state = await clean.station()
-                check('no_memory_pass_after_missing_efi', state['verdict'] != 'pass',
-                      {'verdict': state['verdict'], 'run_state': state['run_state']})
-                # A harmless subsequent directory query proves that errors do not
-                # corrupt the connection, while leaving the host at its Shell.
-                listing2 = await clean.command({'station_id': 'S1', 'command_id': 'listing-' + uuid.uuid4().hex,
-                    'input_id': state['input']['id'], 'action': 'list_uefi_files', 'path': 'FS0:\\EFI'})
-                check('link_usable_after_rejected_efi', listing2['state'] == 'succeeded', listing2)
-                report['passed'] = True
-    except Exception as exc:
-        report['error'] = type(exc).__name__ + ': ' + str(exc)
-        print(report['error'], flush=True)
-    finally:
-        target = Path(args.output)
-        target.parent.mkdir(parents=True, exist_ok=True)
-        target.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
-    return 0 if report['passed'] else 1
-
-
-if __name__ == '__main__':
-    raise SystemExit(asyncio.run(main()))

+ 0 - 503
scripts/validate_qt_clean.py

@@ -1,503 +0,0 @@
-#!/usr/bin/env python3
-"""Validate Qt-clean v1 against a running backend; read-only unless requested.
-
-No firmware parameters or AMT/MT algorithms are submitted by this driver.
---start explicitly authorizes one host start/reset. --drive-default-plan additionally
-continues UIP with CR and exits AMT, ending at the actual UEFI Shell prompt.
-Protocol PASS never means that memory tests passed.
-"""
-from __future__ import annotations
-
-import argparse
-import asyncio
-import contextlib
-import datetime as dt
-import json
-import os
-from pathlib import Path
-import sys
-import time
-from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
-import uuid
-
-import aiohttp
-
-
-TERMINAL = {"succeeded", "failed", "interrupted", "cancelled"}
-STAGE_RANK = {"unknown": -1, "idle": -1, "boot": 0, "booting": 0,
-              "uip": 1, "uip1": 1, "training": 2, "rmt": 3, "amt": 4,
-              "uip2": 5, "post": 5, "uefi": 6, "mt": 7}
-PRIVATE_KEYS = {"password", "passwd", "secret", "authorization", "token",
-                "firmware_settings", "boot_plan", "boot_execution", "raw_line",
-                "raw_sol", "helper_argv", "traceback"}
-
-
-def timestamp():
-    return dt.datetime.now(dt.timezone.utc).isoformat()
-
-
-def safe_url(url, view=None):
-    p = urlsplit(url)
-    host = p.hostname or ""
-    if ":" in host:
-        host = "[" + host + "]"
-    if p.port:
-        host += ":" + str(p.port)
-    values = [(k, v) for k, v in parse_qsl(p.query) if k == "view"]
-    if view is not None:
-        values = [("view", view)]
-    return urlunsplit((p.scheme, host, p.path or "/ws", urlencode(values), ""))
-
-
-def private_fields(value, path=""):
-    found = []
-    if isinstance(value, dict):
-        for key, item in value.items():
-            low = str(key).lower()
-            here = path + "." + str(key)
-            if low in PRIVATE_KEYS or low.endswith("_password") or low.endswith("_secret"):
-                found.append(here)
-            found.extend(private_fields(item, here))
-    elif isinstance(value, list):
-        for i, item in enumerate(value):
-            found.extend(private_fields(item, f"{path}[{i}]"))
-    return found
-
-
-def station_summary(station):
-    return {key: station.get(key) for key in (
-        "station_id", "connection", "power", "phase", "run_state",
-        "started_unix_ms", "boot_id", "verdict", "input", "command")}
-
-
-class RpcFailure(RuntimeError):
-    def __init__(self, method, error):
-        self.method, self.error = method, error or {}
-        super().__init__(f"{method}: {self.error.get('code', 'ERROR')}: "
-                         f"{self.error.get('message', '')}")
-
-
-class Evidence:
-    def __init__(self, args):
-        self.path = Path(args.output).expanduser().resolve()
-        self.token = os.environ.get(args.token_env, "") if args.token_env else ""
-        self.data = {
-            "schema": "qt-clean-validation-v1", "started_utc": timestamp(),
-            "endpoint": safe_url(args.url), "station_id": args.station,
-            "requested": {"start": args.start, "drive_default_plan": args.drive_default_plan,
-                          "check_unconfigured": args.check_unconfigured,
-                          "grpc": bool(args.grpc_address)},
-            "checks": [], "commands": [], "state_transitions": [], "logs": [],
-            "protocol_verdict": "RUNNING", "memory_verdict": "NOT_TESTED",
-            "memory_verdict_reason": "This driver does not run AMT or MT; reaching UEFI is not memory PASS.",
-        }
-
-    def save(self):
-        self.path.parent.mkdir(parents=True, exist_ok=True)
-        tmp = self.path.with_suffix(self.path.suffix + ".tmp")
-        tmp.write_text(json.dumps(self._redacted(self.data), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
-        tmp.replace(self.path)
-
-    def _redacted(self, value):
-        if isinstance(value, dict):
-            return {key: ("[REDACTED]" if str(key).lower() in PRIVATE_KEYS
-                          or str(key).lower().endswith(("_password", "_secret", "_token"))
-                          else self._redacted(item)) for key, item in value.items()}
-        if isinstance(value, list):
-            return [self._redacted(item) for item in value]
-        if isinstance(value, str) and self.token:
-            return value.replace(self.token, "[REDACTED]")
-        return value
-
-    def check(self, name, passed, detail=None, *, skipped=False):
-        row = {"name": name, "status": "SKIP" if skipped else "PASS" if passed else "FAIL",
-               "at_utc": timestamp()}
-        if detail is not None:
-            row["detail"] = detail
-        self.data["checks"].append(row)
-        print(json.dumps(self._redacted(row), ensure_ascii=False), flush=True)
-        self.save()
-        return bool(passed)
-
-    def fail_count(self):
-        return sum(row["status"] == "FAIL" for row in self.data["checks"])
-
-
-class WsClient:
-    def __init__(self, session, url, evidence, token="", *, record_push=True):
-        self.session, self.url, self.evidence = session, url, evidence
-        self.headers = {"Authorization": "Bearer " + token} if token else {}
-        self.record_push = record_push
-        self.ws = self.reader = None
-        self.pending = {}
-        self.counter = 0
-        self.state = None
-        self.state_count = 0
-        self.first_state = asyncio.Event()
-        self.last_summary = {}
-        self.protocol_errors = []
-
-    async def __aenter__(self):
-        self.ws = await self.session.ws_connect(self.url, heartbeat=20, headers=self.headers)
-        self.reader = asyncio.create_task(self._read())
-        return self
-
-    async def __aexit__(self, *exc):
-        await self.ws.close()
-        self.reader.cancel()
-        with contextlib.suppress(asyncio.CancelledError):
-            await self.reader
-
-    async def _read(self):
-        try:
-            async for message in self.ws:
-                if message.type != aiohttp.WSMsgType.TEXT:
-                    if message.type == aiohttp.WSMsgType.ERROR:
-                        raise RuntimeError("WebSocket stream error")
-                    continue
-                try:
-                    frame = json.loads(message.data)
-                except (TypeError, ValueError):
-                    self.protocol_errors.append("non-JSON text response")
-                    continue
-                if not isinstance(frame, dict):
-                    self.protocol_errors.append("response is not an object")
-                    continue
-                request_id = frame.get("id")
-                if request_id in self.pending:
-                    future = self.pending.pop(request_id)
-                    if not future.done():
-                        future.set_result(frame)
-                elif frame.get("event") == "state":
-                    state = frame.get("result")
-                    if isinstance(state, dict):
-                        self.state = state
-                        self.state_count += 1
-                        self.first_state.set()
-                        if self.record_push:
-                            self._record_state(state)
-                    else:
-                        self.protocol_errors.append("state push result is not an object")
-                elif frame.get("event") == "bios_uart" and self.record_push:
-                    result = frame.get("result", {})
-                    if isinstance(result, dict):
-                        self.evidence.data["logs"].append({"station_id": result.get("station_id"),
-                            "session_id": result.get("session_id"), "offset": result.get("offset"),
-                            "next_offset": result.get("next_offset"), "raw_bytes": len(result.get("data_base64", "")) * 3 // 4})
-                    self.evidence.data["logs"] = self.evidence.data["logs"][-4000:]
-                elif request_id is not None:
-                    self.protocol_errors.append("unmatched response id")
-        except Exception as exc:
-            for future in self.pending.values():
-                if not future.done():
-                    future.set_exception(RuntimeError(type(exc).__name__ + ": " + str(exc)))
-
-    def _record_state(self, state):
-        for station in state.get("stations", []):
-            if not isinstance(station, dict):
-                continue
-            summary = station_summary(station)
-            # Ignore naturally changing counters/timestamps unless the useful state changed.
-            key = {k: summary.get(k) for k in ("connection", "power", "phase", "run_state",
-                                              "boot_id", "verdict", "input", "command")}
-            sid = station.get("station_id", "")
-            if key != self.last_summary.get(sid):
-                self.last_summary[sid] = key
-                self.evidence.data["state_transitions"].append({"received_utc": timestamp(), **summary})
-                self.evidence.data["state_transitions"] = self.evidence.data["state_transitions"][-4000:]
-                if sid == self.evidence.data["station_id"]:
-                    print(json.dumps({"station": sid, "phase": summary.get("phase"),
-                                      "run_state": summary.get("run_state"),
-                                      "power": summary.get("power"),
-                                      "input_stage": (summary.get("input") or {}).get("stage")},
-                                     ensure_ascii=False), flush=True)
-
-    async def raw_call(self, method, params=None, *, version=1, timeout=20):
-        self.counter += 1
-        request_id = f"verify-{self.counter}-{uuid.uuid4().hex[:8]}"
-        frame = {"v": version, "id": request_id, "method": method,
-                 "params": {} if params is None else params}
-        future = asyncio.get_running_loop().create_future()
-        self.pending[request_id] = future
-        await self.ws.send_json(frame)
-        try:
-            response = await asyncio.wait_for(future, timeout)
-        finally:
-            self.pending.pop(request_id, None)
-        if response.get("id") != request_id or response.get("v") != 1:
-            raise AssertionError("Invalid response request id or version")
-        return response
-
-    async def call(self, method, params=None, timeout=20):
-        response = await self.raw_call(method, params, timeout=timeout)
-        if response.get("ok") is not True:
-            raise RpcFailure(method, response.get("error"))
-        return response.get("result")
-
-    async def get_state(self):
-        state = await self.call("GetState")
-        if not isinstance(state, dict):
-            raise AssertionError("GetState result must be an object")
-        self.state = state
-        return state
-
-    async def station(self, station_id):
-        state = await self.get_state()
-        return next(s for s in state.get("stations", []) if s.get("station_id") == station_id)
-
-
-async def wait_command(client, command_id, deadline):
-    while time.monotonic() < deadline:
-        result = await client.call("GetCommand", {"command_id": command_id})
-        if result.get("state") in TERMINAL:
-            return result
-        await asyncio.sleep(.5)
-    raise TimeoutError(f"Command {command_id} did not become terminal")
-
-
-async def reject_check(client, evidence, name, method, params, codes, **kwargs):
-    frame = await client.raw_call(method, params, **kwargs)
-    error = frame.get("error") or {}
-    evidence.check(name, frame.get("ok") is False and error.get("code") in codes,
-                   {"code": error.get("code"), "message": error.get("message")})
-
-
-async def readonly_checks(client, evidence, args, session, token):
-    try:
-        await asyncio.wait_for(client.first_state.wait(), 12)
-        evidence.check("automatic_initial_state_push", True,
-                       {"push_count_before_first_request": client.state_count})
-    except TimeoutError:
-        evidence.check("automatic_initial_state_push", False, "No unsolicited state within 12 seconds")
-    state = await client.get_state()
-    evidence.data["initial_state"] = state
-    evidence.check("state_required_fields", all(k in state for k in
-                   ("version", "mode", "server_id", "stations")),
-                   {"version": state.get("version"), "mode": state.get("mode"),
-                    "server_id": state.get("server_id")})
-    stations = state.get("stations", [])
-    ids = [row.get("station_id") for row in stations]
-    evidence.check("station_ids_unique_and_requested_present", args.station in ids and len(ids) == len(set(ids)), ids)
-    required = {"station_id", "connection", "power", "phase", "run_state", "started_unix_ms",
-                "boot_id", "verdict", "input", "command", "channels"}
-    missing = {row.get("station_id", "?"): sorted(required - set(row)) for row in stations if required - set(row)}
-    evidence.check("minimal_station_contract", not missing, missing)
-    forbidden = private_fields(state)
-    evidence.check("no_internal_or_secret_fields_in_clean_state", not forbidden, forbidden)
-    await reject_check(client, evidence, "unknown_rpc_rejected", "NotARealQtMethod", {}, {"UNIMPLEMENTED", "INVALID_ARGUMENT"})
-    await reject_check(client, evidence, "unknown_getstate_field_rejected", "GetState", {"unexpected": True}, {"INVALID_ARGUMENT"})
-    await reject_check(client, evidence, "invalid_params_type_rejected", "GetState", "invalid", {"INVALID_ARGUMENT"})
-    await reject_check(client, evidence, "unsupported_protocol_version_rejected", "GetState", {}, {"INVALID_ARGUMENT"}, version=9)
-    await reject_check(client, evidence, "missing_command_rejected", "GetCommand", {"command_id": "verify-missing-" + uuid.uuid4().hex}, {"NOT_FOUND"})
-    await reject_check(client, evidence, "event_log_not_in_qt_clean", "ReadEventQueue", {"station_id": args.station}, {"UNIMPLEMENTED"})
-    await reject_check(client, evidence, "invalid_uart_offset_rejected", "ReadBiosUart", {"station_id": args.station, "offset": -1}, {"INVALID_ARGUMENT"})
-
-    legacy = {}
-    for view in ("full", "qt"):
-        async with WsClient(session, safe_url(args.url, view), evidence, token, record_push=False) as old:
-            info = await old.call("GetSystemInfo")
-            legacy[view] = info
-            evidence.check(f"legacy_{view}_GetSystemInfo", isinstance(info, dict) and bool(info.get("version")), info)
-            if view == "full":
-                listed = await old.call("ListStations")
-                evidence.check("legacy_full_ListStations", isinstance(listed, dict) and isinstance(listed.get("stations"), list),
-                               {"station_count": len(listed.get("stations", []))})
-                if args.check_unconfigured:
-                    ctl = await old.call("GetStationControl", {"station_id": args.check_unconfigured})
-                    evidence.data["unconfigured_capabilities"] = {
-                        "station_id": args.check_unconfigured, "capabilities": ctl.get("capabilities", {})}
-    evidence.data["legacy_system_info"] = legacy
-    evidence.check("legacy_and_clean_version_match", all(info.get("version") == state.get("version") for info in legacy.values()))
-    # A second connection gets its own complete initial snapshot, independent of the first.
-    async with WsClient(session, args.url, evidence, token, record_push=False) as other:
-        await asyncio.wait_for(other.first_state.wait(), 12)
-        evidence.check("second_client_gets_initial_snapshot", other.state.get("server_id") == state.get("server_id"))
-    evidence.check("first_client_survives_second_disconnect", (await client.get_state()).get("server_id") == state.get("server_id"))
-
-
-async def grpc_check(args, evidence, token):
-    if not args.grpc_address:
-        return
-    if args.backend_source:
-        sys.path.insert(0, str(Path(args.backend_source).resolve() / "src"))
-    try:
-        import grpc
-        from google.protobuf.empty_pb2 import Empty
-        from stl_backend.generated import bench_pb2_grpc
-        metadata = (("authorization", "Bearer " + token),) if token else ()
-        async with grpc.aio.insecure_channel(args.grpc_address) as channel:
-            stub = bench_pb2_grpc.BenchServiceStub(channel)
-            info = await stub.GetSystemInfo(Empty(), timeout=15, metadata=metadata)
-            stations = await stub.ListStations(Empty(), timeout=15, metadata=metadata)
-        evidence.check("native_grpc_readonly_compatibility", bool(info.version) and bool(stations.stations),
-                       {"version": info.version, "mode": info.mode, "station_count": len(stations.stations)})
-    except Exception as exc:
-        evidence.check("native_grpc_readonly_compatibility", False, {"error": type(exc).__name__, "message": str(exc)[:500]})
-
-
-async def unconfigured_check(client, evidence, args):
-    if not args.check_unconfigured:
-        return
-    caps = evidence.data.get("unconfigured_capabilities", {}).get("capabilities", {})
-    if caps.get("bmc_power") is not False:
-        evidence.check("unconfigured_station_has_no_power_capability", False,
-                       "Refused StartTest: full interface did not explicitly report bmc_power=false")
-        return
-    sid = args.check_unconfigured
-    cid = "verify-unconfigured-" + uuid.uuid4().hex
-    before = await client.station(sid)
-    try:
-        accepted = await client.call("StartTest", {"station_id": sid, "command_id": cid})
-        result = accepted if accepted.get("state") in TERMINAL else await wait_command(client, cid, time.monotonic() + 45)
-        error = result.get("error") or {}
-        rejected = result.get("state") == "failed"
-    except RpcFailure as exc:
-        result, error, rejected = None, exc.error, True
-    after = await client.station(sid)
-    evidence.data["unconfigured_start"] = {"station_id": sid, "command_id": cid, "result": result, "error": error}
-    evidence.check("unconfigured_start_rejected_without_boot", rejected and before.get("boot_id") == after.get("boot_id"),
-                   {"error": error, "before_power": before.get("power"), "after_power": after.get("power")})
-
-
-async def start_test(client, evidence, args):
-    station = await client.station(args.station)
-    before = station_summary(station)
-    cid = "verify-start-" + uuid.uuid4().hex
-    params = {"station_id": args.station, "command_id": cid}
-    row = {"method": "StartTest", "params": params, "before": before, "sent_utc": timestamp()}
-    evidence.data["commands"].append(row)
-    evidence.save()
-    accepted = await client.call("StartTest", params)
-    row["accepted"] = accepted
-    replay_pending = await client.call("StartTest", params)
-    row["replay_while_pending"] = replay_pending
-    evidence.check("start_same_id_pending_replay", accepted.get("command_id") == cid and replay_pending.get("command_id") == cid)
-    done = await wait_command(client, cid, time.monotonic() + args.timeout)
-    row["completed"] = done
-    if not evidence.check("start_command_succeeded", done.get("state") == "succeeded", done):
-        raise RuntimeError("Host start did not succeed")
-    result = done.get("result") or {}
-    expected = {"off": "host_on", "on": "host_reset"}.get(result.get("previous_power"))
-    evidence.check("start_power_action_matches_live_power", expected is not None and result.get("power_action") == expected,
-                   {"previous_power": result.get("previous_power"), "power_action": result.get("power_action")})
-    evidence.check("start_requires_new_bios_boot_evidence", result.get("boot_observed") is True and bool(result.get("boot_id"))
-                   and result.get("boot_id") != result.get("previous_boot_id"),
-                   {k: result.get(k) for k in ("previous_boot_id", "boot_id", "boot_observed", "started_unix_ms")})
-    replay_done = await client.call("StartTest", params)
-    row["replay_after_completion"] = replay_done
-    evidence.check("start_same_id_completed_replay", replay_done.get("command_id") == cid
-                   and replay_done.get("state") == "succeeded"
-                   and (replay_done.get("result") or {}).get("boot_id") == result.get("boot_id"))
-    now = await client.station(args.station)
-    evidence.data["boot_evidence"] = result
-    evidence.data["after_start"] = station_summary(now)
-    evidence.check("state_agrees_with_completed_start", now.get("boot_id") == result.get("boot_id"))
-    return result.get("boot_id")
-
-
-async def drive_plan(client, evidence, args, boot_id):
-    deadline = time.monotonic() + args.timeout
-    handled = set()
-    rank, stages = -1, []
-    while time.monotonic() < deadline:
-        station = await client.station(args.station)
-        if station.get("boot_id") != boot_id:
-            raise RuntimeError("Unexpected new BIOS boot during local validation plan; no stage input replayed")
-        phase = station.get("phase", "unknown")
-        new_rank = STAGE_RANK.get(phase, -1)
-        if new_rank >= 0 and new_rank < rank:
-            evidence.check("overall_phase_never_regresses", False, {"previous_rank": rank, "phase": phase})
-            raise RuntimeError("Overall phase regressed")
-        rank = max(rank, new_rank)
-        if not stages or stages[-1] != phase:
-            stages.append(phase)
-            evidence.data["default_plan_stages"] = stages
-            evidence.save()
-        point = station.get("input") or {}
-        if point.get("ready") and point.get("stage") == "uefi":
-            evidence.data["after_default_plan"] = station_summary(station)
-            evidence.check("default_plan_reached_real_uefi_prompt", phase == "uefi", {"stages": stages, "input": point})
-            evidence.check("overall_phase_never_regresses", True, stages)
-            return
-        stage = point.get("stage")
-        action = "continue_uip" if stage in ("uip", "uip1", "uip2") else "skip_amt" if stage == "amt" else None
-        key = point.get("id")
-        if point.get("ready") and action and key and key not in handled:
-            actions = point.get("actions") or []
-            if action not in actions:
-                await asyncio.sleep(.5)
-                continue
-            handled.add(key)
-            cid = "verify-stage-" + uuid.uuid4().hex
-            params = {"command_id": cid, "station_id": args.station,
-                      "input_id": key, "action": action}
-            row = {"method": "StageAction", "params": params, "input": point, "sent_utc": timestamp()}
-            evidence.data["commands"].append(row)
-            evidence.save()
-            row["accepted"] = await client.call("StageAction", params)
-            done = await wait_command(client, cid, min(deadline, time.monotonic() + 90))
-            row["completed"] = done
-            evidence.check("stage_action_" + action + "_" + str(len(handled)), done.get("state") == "succeeded", done)
-            if done.get("state") != "succeeded":
-                raise RuntimeError("Stage action failed; not retrying hardware input")
-            evidence.save()
-        await asyncio.sleep(.5)
-    raise TimeoutError("Default local validation plan did not reach UEFI before deadline")
-
-
-async def run(args, evidence):
-    token = os.environ.get(args.token_env, "") if args.token_env else ""
-    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session:
-        async with WsClient(session, args.url, evidence, token) as client:
-            await readonly_checks(client, evidence, args, session, token)
-            await grpc_check(args, evidence, token)
-            if evidence.fail_count():
-                raise RuntimeError("Read-only contract checks failed; no hardware actions submitted")
-            await unconfigured_check(client, evidence, args)
-            if args.start:
-                boot_id = await start_test(client, evidence, args)
-                if args.drive_default_plan:
-                    await drive_plan(client, evidence, args, boot_id)
-            evidence.data["final_state"] = await client.get_state()
-            evidence.data["state_push_count"] = client.state_count
-            evidence.check("websocket_frames_valid", not client.protocol_errors, client.protocol_errors)
-            evidence.check("final_state_has_no_internal_or_secret_fields", not private_fields(evidence.data["final_state"]))
-
-
-def main():
-    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
-    parser.add_argument("--url", required=True, help="ws://HOST:8080/ws?view=qt-clean")
-    parser.add_argument("--output", required=True, help="JSON evidence file")
-    parser.add_argument("--station", default="S1")
-    parser.add_argument("--timeout", type=float, default=900, help="Seconds per host start / local plan")
-    parser.add_argument("--start", action="store_true", help="Actually start/reset the server host once")
-    parser.add_argument("--drive-default-plan", action="store_true", help="With --start: CR at UIP; exit AMT; stop at UEFI")
-    parser.add_argument("--check-unconfigured", metavar="STATION", help="Explicitly try StartTest on a station with bmc_power=false")
-    parser.add_argument("--grpc-address", help="Optional native gRPC HOST:PORT read-only smoke test")
-    parser.add_argument("--backend-source", help="Backend project root for generated gRPC modules")
-    parser.add_argument("--token-env", help="Environment variable containing API bearer token; never written to evidence")
-    args = parser.parse_args()
-    if args.drive_default_plan and not args.start:
-        parser.error("--drive-default-plan requires --start")
-    if args.timeout <= 0:
-        parser.error("--timeout must be positive")
-    if dict(parse_qsl(urlsplit(args.url).query)).get("view") != "qt-clean":
-        parser.error("--url must explicitly select view=qt-clean")
-    evidence = Evidence(args)
-    evidence.save()
-    try:
-        asyncio.run(run(args, evidence))
-    except KeyboardInterrupt:
-        evidence.check("validation_completed", False, "Interrupted; already accepted hardware commands may continue")
-    except Exception as exc:
-        evidence.check("validation_completed", False, {"error": type(exc).__name__, "message": str(exc)[:1200]})
-    evidence.data["finished_utc"] = timestamp()
-    evidence.data["protocol_verdict"] = "FAIL" if evidence.fail_count() else "PASS"
-    evidence.save()
-    print(json.dumps({"protocol_verdict": evidence.data["protocol_verdict"],
-                      "memory_verdict": evidence.data["memory_verdict"], "output": str(evidence.path)}, ensure_ascii=False))
-    return 1 if evidence.fail_count() else 0
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())

+ 0 - 69
scripts/version.py

@@ -1,69 +0,0 @@
-#!/usr/bin/env python3
-"""Check the three version fields, or set them together. No dependencies."""
-from __future__ import annotations
-
-import argparse
-from pathlib import Path
-import re
-try:
-    import tomllib
-except ModuleNotFoundError:
-    tomllib = None
-
-ROOT = Path(__file__).resolve().parents[1]
-VERSION_FILE = ROOT / "VERSION"
-PROJECT_FILE = ROOT / "pyproject.toml"
-PACKAGE_FILE = ROOT / "src/stl_backend/__init__.py"
-PLAIN_VERSION = re.compile(r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2,}(?:\.dev(?:0|[1-9][0-9]*))?")
-
-
-def read_fields() -> dict[str, str]:
-    package = PACKAGE_FILE.read_text(encoding="utf-8")
-    values = re.findall(r'^__version__ = "([^"]+)"$', package, re.MULTILINE)
-    if len(values) != 1:
-        raise ValueError("Expected exactly one __version__ assignment")
-    project_text = PROJECT_FILE.read_text(encoding="utf-8")
-    project = tomllib.loads(project_text) if tomllib else {"project": {"version": re.findall(r'^version = "([^"]+)"$', project_text, re.MULTILINE)[0]}}
-    return {
-        "VERSION": VERSION_FILE.read_text(encoding="utf-8").strip(),
-        "pyproject.toml": project["project"]["version"],
-        "src/stl_backend/__init__.py": values[0],
-    }
-
-
-def replace_one(text: str, pattern: str, replacement: str) -> str:
-    updated, count = re.subn(pattern, replacement, text, flags=re.MULTILINE)
-    if count != 1:
-        raise ValueError("Expected exactly one version field; no files were changed")
-    return updated
-
-
-def main() -> None:
-    parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("action", choices=("check", "set"))
-    parser.add_argument("version", nargs="?")
-    args = parser.parse_args()
-    if (args.action == "set") != (args.version is not None):
-        parser.error("Use 'check' or 'set X.Y.Z'")
-    try:
-        if args.action == "set":
-            if not PLAIN_VERSION.fullmatch(args.version):
-                raise ValueError("Version must be X.Y.Z, for example 0.1.1")
-            project = replace_one(PROJECT_FILE.read_text(encoding="utf-8"),
-                                  r'^version = "[^"]+"$', f'version = "{args.version}"')
-            package = replace_one(PACKAGE_FILE.read_text(encoding="utf-8"),
-                                  r'^__version__ = "[^"]+"$', f'__version__ = "{args.version}"')
-            PROJECT_FILE.write_text(project, encoding="utf-8")
-            PACKAGE_FILE.write_text(package, encoding="utf-8")
-            VERSION_FILE.write_text(args.version + "\n", encoding="utf-8")
-        fields = read_fields()
-        expected = fields["VERSION"]
-        if not PLAIN_VERSION.fullmatch(expected) or any(v != expected for v in fields.values()):
-            raise ValueError(f"Version mismatch: {fields}; use 'set X.Y.Z' to synchronize")
-        print(f"Version OK: {expected}")
-    except (OSError, ValueError, KeyError) as exc:
-        parser.exit(1, f"Version error: {exc}\n")
-
-
-if __name__ == "__main__":
-    main()

+ 208 - 0
src/3rdparty/libxlsxwriter/License.txt

@@ -0,0 +1,208 @@
+/**
+
+@page license License
+
+Libxlsxwriter is released under a FreeBSD license:
+
+    Copyright 2014-2026, John McNamara <jmcnamara@cpan.org>
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions are
+    met:
+
+    1. Redistributions of source code must retain the above copyright notice,
+       this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+       notice, this list of conditions and the following disclaimer in the
+       documentation and/or other materials provided with the distribution.
+
+    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+    IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+    PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+    The views and conclusions contained in the software and documentation are
+    those of the authors and should not be interpreted as representing
+    official policies, either expressed or implied, of the FreeBSD Project.
+
+
+Libxlsxwriter includes the `queue.h` and `tree.h` macros from FreeBSD. It also
+includes and, unless overridden, uses the optional libraries `minizip`,
+`tmpfileplus` and `md5`. It also includes the `emyg_dtoa` library but doesn't
+use it by default. These components have the following licenses:
+
+
+Queue.h from FreeBSD:
+
+    Copyright (c) 1991, 1993
+     The Regents of the University of California.  All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions
+    are met:
+    1. Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+       notice, this list of conditions and the following disclaimer in the
+       documentation and/or other materials provided with the distribution.
+    4. Neither the name of the University nor the names of its contributors
+       may be used to endorse or promote products derived from this software
+       without specific prior written permission.
+
+    THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+    ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+    OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+    SUCH DAMAGE.
+
+
+Tree.h from FreeBSD:
+
+    Copyright 2002 Niels Provos <provos@citi.umich.edu>
+    All rights reserved.
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted provided that the following conditions
+    are met:
+    1. Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer.
+    2. Redistributions in binary form must reproduce the above copyright
+       notice, this list of conditions and the following disclaimer in the
+       documentation and/or other materials provided with the distribution.
+
+    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+    IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+The `minizip` files used in the libxlsxwriter source tree are taken from the
+`zlib` ` contrib/minizip` directory. [Zlib](http://www.zlib.net) has the
+following License/Copyright:
+
+    (C) 1995-2013 Jean-loup Gailly and Mark Adler
+
+    This software is provided 'as-is', without any express or implied
+    warranty.  In no event will the authors be held liable for any damages
+    arising from the use of this software.
+
+    Permission is granted to anyone to use this software for any purpose,
+    including commercial applications, and to alter it and redistribute it
+    freely, subject to the following restrictions:
+
+    1. The origin of this software must not be misrepresented; you must not
+       claim that you wrote the original software. If you use this software
+       in a product, an acknowledgment in the product documentation would be
+       appreciated but is not required.
+    2. Altered source versions must be plainly marked as such, and must not be
+       misrepresented as being the original software.
+    3. This notice may not be removed or altered from any source distribution.
+
+    Jean-loup Gailly        Mark Adler
+    jloup@gzip.org          madler@alumni.caltech.edu
+
+The `minizip` files have the following additional copyright declarations:
+
+    Copyright (C) 1998-2010 Gilles Vollant
+    (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+    Modifications for Zip64 support
+    Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+Note, it is possible to compile libxlsxwriter without statically linking the
+`minizip` files and instead dynamically linking to `lminizip`, see
+@ref gsg_minizip.
+
+[Tmpfileplus](http://www.di-mgt.com.au/c_function_to_create_temp_file.html)
+has the following license:
+
+    This Source Code Form is subject to the terms of the Mozilla Public
+    License, v. 2.0. If a copy of the MPL was not distributed with this
+    file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+    Copyright (c) 2012-16 David Ireland, DI Management Services Pty Ltd
+    <http://www.di-mgt.com.au/contact/>.
+
+See the [Mozilla Public License, v. 2.0](http://mozilla.org/MPL/2.0/).
+
+Note, it is possible to compile libxlsxwriter using the standard library
+`tmpfile()` function instead of `tmpfileplus`, see @ref gsg_tmpdir.
+
+The [Milo Yip DTOA library](https://github.com/miloyip/dtoa-benchmark) for
+converting doubles to strings. It has the following license:
+
+    Copyright (C) 2015 Doug Currie
+    based on dtoa_milo.h
+    Copyright (C) 2014 Milo Yip
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+
+This Milo Yip DTOA library (emyg_dtoa) is used to avoid issues where the
+standard sprintf() dtoa function changes output based on locale settings. It
+is also 40-50% faster than the standard dtoa for raw numeric data. The use of
+this library is optional. If you wish to use it you can pass
+`USE_DTOA_LIBRARY=1` to make when compiling.
+
+[Openwall MD5](https://openwall.info/wiki/people/solar/software/public-domain-source-code/md5)
+has the following licence:
+
+    This software was written by Alexander Peslyak in 2001.  No copyright is
+    claimed, and the software is hereby placed in the public domain.
+    In case this attempt to disclaim copyright and place the software in the
+    public domain is deemed null and void, then the software is
+    Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
+    general public under the following terms:
+
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted.
+
+    There's ABSOLUTELY NO WARRANTY, express or implied.
+
+    (This is a heavily cut-down "BSD license".)
+
+Note, the MD5 library is used to avoid including duplicate image files in the
+xlsx file. If you don't want to use this code, and the additional licence, you
+can use OpenSSL's MD5 functions instead by passing `USE_OPENSSL_MD5=1` to
+make. If this functionality isn't required it is possible to compile
+libxlsxwriter without image deduplication by passing `USE_NO_MD5=1` to make.
+
+See also @ref gsg_md5.
+
+Next: @ref changes
+*/

+ 26 - 0
src/3rdparty/libxlsxwriter/include/xlsxwriter.h

@@ -0,0 +1,26 @@
+/*
+ * libxlsxwriter
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ * Copyright 2014-2026, John McNamara, jmcnamara@cpan.org.
+ */
+
+/**
+ * @file xlsxwriter.h
+ *
+ * xlsxwriter - A library for creating Excel XLSX files.
+ *
+ */
+#ifndef __LXW_XLSXWRITER_H__
+#define __LXW_XLSXWRITER_H__
+
+#include "xlsxwriter/workbook.h"
+#include "xlsxwriter/worksheet.h"
+#include "xlsxwriter/format.h"
+#include "xlsxwriter/utility.h"
+
+#define LXW_VERSION "1.2.4"
+#define LXW_VERSION_ID 124
+#define LXW_SOVERSION "11"
+
+#endif /* __LXW_XLSXWRITER_H__ */

+ 81 - 0
src/3rdparty/libxlsxwriter/include/xlsxwriter/app.h

@@ -0,0 +1,81 @@
+/*
+ * libxlsxwriter
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ * Copyright 2014-2026, John McNamara, jmcnamara@cpan.org.
+ *
+ * app - A libxlsxwriter library for creating Excel XLSX app files.
+ *
+ */
+#ifndef __LXW_APP_H__
+#define __LXW_APP_H__
+
+#include <stdint.h>
+#include <string.h>
+#include "workbook.h"
+#include "common.h"
+
+/* Define the queue.h TAILQ structs for the App structs. */
+STAILQ_HEAD(lxw_heading_pairs, lxw_heading_pair);
+STAILQ_HEAD(lxw_part_names, lxw_part_name);
+
+typedef struct lxw_heading_pair {
+
+    char *key;
+    char *value;
+
+    STAILQ_ENTRY (lxw_heading_pair) list_pointers;
+
+} lxw_heading_pair;
+
+typedef struct lxw_part_name {
+
+    char *name;
+
+    STAILQ_ENTRY (lxw_part_name) list_pointers;
+
+} lxw_part_name;
+
+/* Struct to represent an App object. */
+typedef struct lxw_app {
+
+    FILE *file;
+
+    struct lxw_heading_pairs *heading_pairs;
+    struct lxw_part_names *part_names;
+    lxw_doc_properties *properties;
+
+    uint32_t num_heading_pairs;
+    uint32_t num_part_names;
+    uint8_t doc_security;
+
+} lxw_app;
+
+
+/* *INDENT-OFF* */
+#ifdef __cplusplus
+extern "C" {
+#endif
+/* *INDENT-ON* */
+
+lxw_app *lxw_app_new(void);
+void lxw_app_free(lxw_app *app);
+void lxw_app_assemble_xml_file(lxw_app *self);
+void lxw_app_add_part_name(lxw_app *self, const char *name);
+void lxw_app_add_heading_pair(lxw_app *self, const char *key,
+                              const char *value);
+
+/* Declarations required for unit testing. */
+#ifdef TESTING
+
+STATIC void _app_xml_declaration(lxw_app *self);
+
+#endif /* TESTING */
+
+/* *INDENT-OFF* */
+#ifdef __cplusplus
+}
+#endif
+/* *INDENT-ON* */
+
+#endif /* __LXW_APP_H__ */

Разница между файлами не показана из-за своего большого размера
+ 3964 - 0
src/3rdparty/libxlsxwriter/include/xlsxwriter/chart.h


+ 545 - 0
src/3rdparty/libxlsxwriter/include/xlsxwriter/chartsheet.h

@@ -0,0 +1,545 @@
+/*
+ * libxlsxwriter
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ * Copyright 2014-2026, John McNamara, jmcnamara@cpan.org.
+ *
+ * chartsheet - A libxlsxwriter library for creating Excel XLSX chartsheet files.
+ *
+ */
+
+/**
+ * @page chartsheet_page The Chartsheet object
+ *
+ * The Chartsheet object represents an Excel chartsheet, which is a type of
+ * worksheet that only contains a chart. The Chartsheet object handles
+ * operations such as adding a chart and setting the page layout.
+ *
+ * See @ref chartsheet.h for full details of the functionality.
+ *
+ * @file chartsheet.h
+ *
+ * @brief Functions related to adding data and formatting to a chartsheet.
+ *
+ * The Chartsheet object represents an Excel chartsheet. It handles operations
+ * such as adding a chart and setting the page layout.
+ *
+ * A Chartsheet object isn't created directly. Instead a chartsheet is created
+ * by calling the workbook_add_chartsheet() function from a Workbook object. A
+ * chartsheet object functions as a worksheet and not as a chart. In order to
+ * have it display data a #lxw_chart object must be created and added to the
+ * chartsheet:
+ *
+ * @code
+ *     #include "xlsxwriter.h"
+ *
+ *     int main() {
+ *
+ *         lxw_workbook   *workbook   = new_workbook("chartsheet.xlsx");
+ *         lxw_worksheet  *worksheet  = workbook_add_worksheet(workbook, NULL);
+ *         lxw_chartsheet *chartsheet = workbook_add_chartsheet(workbook, NULL);
+ *         lxw_chart      *chart      = workbook_add_chart(workbook, LXW_CHART_BAR);
+ *
+ *         //... Set up the chart.
+ *
+ *         // Add the chart to the chartsheet.
+ *         return workbook_close(workbook);
+ *
+ *     }
+ * @endcode
+ *
+ * @image html chartsheet.png
+ *
+ * The data for the chartsheet chart must be contained on a separate
+ * worksheet. That is why it is always created in conjunction with at least
+ * one data worksheet, as shown above.
+ */
+
+#ifndef __LXW_CHARTSHEET_H__
+#define __LXW_CHARTSHEET_H__
+
+#include <stdint.h>
+
+#include "common.h"
+#include "worksheet.h"
+#include "drawing.h"
+#include "utility.h"
+
+/**
+ * @brief Struct to represent an Excel chartsheet.
+ *
+ * The members of the lxw_chartsheet struct aren't modified directly. Instead
+ * the chartsheet properties are set by calling the functions shown in
+ * chartsheet.h.
+ */
+typedef struct lxw_chartsheet {
+
+    FILE *file;
+    lxw_worksheet *worksheet;
+    lxw_chart *chart;
+
+    struct lxw_protection_obj protection;
+    uint8_t is_protected;
+
+    const char *name;
+    const char *quoted_name;
+    const char *tmpdir;
+    uint16_t index;
+    uint8_t active;
+    uint8_t selected;
+    uint8_t hidden;
+    uint16_t *active_sheet;
+    uint16_t *first_sheet;
+    uint16_t rel_count;
+
+    STAILQ_ENTRY (lxw_chartsheet) list_pointers;
+
+} lxw_chartsheet;
+
+
+/* *INDENT-OFF* */
+#ifdef __cplusplus
+extern "C" {
+#endif
+/* *INDENT-ON* */
+
+/**
+ * @brief Insert a chart object into a chartsheet.
+ *
+ * @param chartsheet   Pointer to a lxw_chartsheet instance to be updated.
+ * @param chart        A #lxw_chart object created via workbook_add_chart().
+ *
+ * @return A #lxw_error code.
+ *
+ * The `%chartsheet_set_chart()` function can be used to insert a chart into a
+ * chartsheet. The chart object must be created first using the
+ * `workbook_add_chart()` function and configured using the @ref chart.h
+ * functions.
+ *
+ * @code
+ *     // Create the chartsheet.
+ *     lxw_chartsheet *chartsheet = workbook_add_chartsheet(workbook, NULL);
+ *
+ *     // Create a chart object.
+ *     lxw_chart *chart = workbook_add_chart(workbook, LXW_CHART_LINE);
+ *
+ *     // Add a data series to the chart.
+ *     chart_add_series(chart, NULL, "=Sheet1!$A$1:$A$6");
+ *
+ *     // Insert the chart into the chartsheet.
+ *     chartsheet_set_chart(chartsheet, chart);
+ * @endcode
+ *
+ * @image html chartsheet2.png
+ *
+ * **Note:**
+ *
+ * A chart may only be inserted once into a chartsheet or a worksheet. If
+ * several similar charts are required then each one must be created
+ * separately.
+ *
+ */
+lxw_error chartsheet_set_chart(lxw_chartsheet *chartsheet, lxw_chart *chart);
+
+/* Not currently required since scale options aren't useful in a chartsheet. */
+lxw_error chartsheet_set_chart_opt(lxw_chartsheet *chartsheet,
+                                   lxw_chart *chart,
+                                   lxw_chart_options *user_options);
+
+/**
+ * @brief Make a chartsheet the active, i.e., visible chartsheet.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ *
+ * The `%chartsheet_activate()` function is used to specify which chartsheet
+ * is initially visible in a multi-sheet workbook:
+ *
+ * @code
+ *     lxw_worksheet  *worksheet1  = workbook_add_worksheet(workbook, NULL);
+ *     lxw_chartsheet *chartsheet1 = workbook_add_chartsheet(workbook, NULL);
+ *     lxw_chartsheet *chartsheet2 = workbook_add_chartsheet(workbook, NULL);
+ *     lxw_chartsheet *chartsheet3 = workbook_add_chartsheet(workbook, NULL);
+ *
+ *     chartsheet_activate(chartsheet3);
+ * @endcode
+ *
+ * @image html chartsheet_activate.png
+ *
+ * More than one chartsheet can be selected via the `chartsheet_select()`
+ * function, see below, however only one chartsheet can be active.
+ *
+ * The default active chartsheet is the first chartsheet.
+ *
+ * See also `worksheet_activate()`.
+ *
+ */
+void chartsheet_activate(lxw_chartsheet *chartsheet);
+
+/**
+ * @brief Set a chartsheet tab as selected.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ *
+ * The `%chartsheet_select()` function is used to indicate that a chartsheet
+ * is selected in a multi-sheet workbook:
+ *
+ * @code
+ *     chartsheet_activate(chartsheet1);
+ *     chartsheet_select(chartsheet2);
+ *     chartsheet_select(chartsheet3);
+ *
+ * @endcode
+ *
+ * A selected chartsheet has its tab highlighted. Selecting chartsheets is a
+ * way of grouping them together so that, for example, several chartsheets
+ * could be printed in one go. A chartsheet that has been activated via the
+ * `chartsheet_activate()` function will also appear as selected.
+ *
+ * See also `worksheet_select()`.
+ *
+ */
+void chartsheet_select(lxw_chartsheet *chartsheet);
+
+/**
+ * @brief Hide the current chartsheet.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ *
+ * The `%chartsheet_hide()` function is used to hide a chartsheet:
+ *
+ * @code
+ *     chartsheet_hide(chartsheet2);
+ * @endcode
+ *
+ * You may wish to hide a chartsheet in order to avoid confusing a user with
+ * intermediate data or calculations.
+ *
+ * @image html hide_sheet.png
+ *
+ * A hidden chartsheet can not be activated or selected so this function is
+ * mutually exclusive with the `chartsheet_activate()` and
+ * `chartsheet_select()` functions. In addition, since the first chartsheet
+ * will default to being the active chartsheet, you cannot hide the first
+ * chartsheet without activating another sheet:
+ *
+ * @code
+ *     chartsheet_activate(chartsheet2);
+ *     chartsheet_hide(chartsheet1);
+ * @endcode
+ *
+ * See also `worksheet_hide()`.
+ *
+ */
+void chartsheet_hide(lxw_chartsheet *chartsheet);
+
+/**
+ * @brief Set current chartsheet as the first visible sheet tab.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ *
+ * The `chartsheet_activate()` function determines which chartsheet is
+ * initially selected.  However, if there are a large number of chartsheets the
+ * selected chartsheet may not appear on the screen. To avoid this you can
+ * select the leftmost visible chartsheet tab using
+ * `%chartsheet_set_first_sheet()`:
+ *
+ * @code
+ *     chartsheet_set_first_sheet(chartsheet19); // First visible chartsheet tab.
+ *     chartsheet_activate(chartsheet20);        // First visible chartsheet.
+ * @endcode
+ *
+ * This function is not required very often. The default value is the first
+ * chartsheet.
+ *
+ * See also `worksheet_set_first_sheet()`.
+ *
+ */
+void chartsheet_set_first_sheet(lxw_chartsheet *chartsheet);
+
+/**
+ * @brief Set the color of the chartsheet tab.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param color      The tab color.
+ *
+ * The `%chartsheet_set_tab_color()` function is used to change the color of
+ * the chartsheet tab:
+ *
+ * @code
+ *      chartsheet_set_tab_color(chartsheet1, LXW_COLOR_RED);
+ *      chartsheet_set_tab_color(chartsheet2, LXW_COLOR_GREEN);
+ *      chartsheet_set_tab_color(chartsheet3, 0xFF9900); // Orange.
+ * @endcode
+ *
+ * The color should be an RGB integer value, see @ref working_with_colors.
+ *
+ * See also `worksheet_set_tab_color()`.
+ */
+void chartsheet_set_tab_color(lxw_chartsheet *chartsheet, lxw_color_t color);
+
+/**
+ * @brief Protect elements of a chartsheet from modification.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param password   A chartsheet password.
+ * @param options    Chartsheet elements to protect.
+ *
+ * The `%chartsheet_protect()` function protects chartsheet elements from
+ * modification:
+ *
+ * @code
+ *     chartsheet_protect(chartsheet, "Some Password", options);
+ * @endcode
+ *
+ * The `password` and lxw_protection pointer are both optional:
+ *
+ * @code
+ *     chartsheet_protect(chartsheet2, NULL,       my_options);
+ *     chartsheet_protect(chartsheet3, "password", NULL);
+ *     chartsheet_protect(chartsheet4, "password", my_options);
+ * @endcode
+ *
+ * Passing a `NULL` password is the same as turning on protection without a
+ * password. Passing a `NULL` password and `NULL` options had no effect on
+ * chartsheets.
+ *
+ * You can specify which chartsheet elements you wish to protect by passing a
+ * lxw_protection pointer in the `options` argument. In Excel chartsheets only
+ * have two protection options:
+ *
+ *     no_content
+ *     no_objects
+ *
+ * All parameters are off by default. Individual elements can be protected as
+ * follows:
+ *
+ * @code
+ *     lxw_protection options = {
+ *         .no_content  = 1,
+ *         .no_objects  = 1,
+ *     };
+ *
+ *     chartsheet_protect(chartsheet, NULL, &options);
+ *
+ * @endcode
+ *
+ * See also worksheet_protect().
+ *
+ * **Note:** Sheet level passwords in Excel offer **very** weak
+ * protection. They don't encrypt your data and are very easy to
+ * deactivate. Full workbook encryption is not supported by `libxlsxwriter`
+ * since it requires a completely different file format.
+ */
+void chartsheet_protect(lxw_chartsheet *chartsheet, const char *password,
+                        lxw_protection *options);
+
+/**
+ * @brief Set the chartsheet zoom factor.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param scale      Chartsheet zoom factor.
+ *
+ * Set the chartsheet zoom factor in the range `10 <= zoom <= 400`:
+ *
+ * @code
+ *     chartsheet_set_zoom(chartsheet, 75);
+ * @endcode
+ *
+ * The default zoom factor is 100. It isn't possible to set the zoom to
+ * "Selection" because it is calculated by Excel at run-time.
+ *
+ * See also `worksheet_set_zoom()`.
+ */
+void chartsheet_set_zoom(lxw_chartsheet *chartsheet, uint16_t scale);
+
+/**
+ * @brief Set the page orientation as landscape.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ *
+ * This function is used to set the orientation of a chartsheet's printed page
+ * to landscape. The default chartsheet orientation is landscape, so this
+ * function isn't generally required:
+ *
+ * @code
+ *     chartsheet_set_landscape(chartsheet);
+ * @endcode
+ */
+void chartsheet_set_landscape(lxw_chartsheet *chartsheet);
+
+/**
+ * @brief Set the page orientation as portrait.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ *
+ * This function is used to set the orientation of a chartsheet's printed page
+ * to portrait:
+ *
+ * @code
+ *     chartsheet_set_portrait(chartsheet);
+ * @endcode
+ */
+void chartsheet_set_portrait(lxw_chartsheet *chartsheet);
+
+/**
+ * @brief Set the paper type for printing.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param paper_type The Excel paper format type.
+ *
+ * This function is used to set the paper format for the printed output of a
+ * chartsheet:
+ *
+ * @code
+ *     chartsheet_set_paper(chartsheet1, 1);  // US Letter
+ *     chartsheet_set_paper(chartsheet2, 9);  // A4
+ * @endcode
+ *
+ * If you do not specify a paper type the chartsheet will print using the
+ * printer's default paper style.
+ *
+ * See `worksheet_set_paper()` for a full list of available paper sizes.
+ */
+void chartsheet_set_paper(lxw_chartsheet *chartsheet, uint8_t paper_type);
+
+/**
+ * @brief Set the chartsheet margins for the printed page.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param left       Left margin in inches.   Excel default is 0.7.
+ * @param right      Right margin in inches.  Excel default is 0.7.
+ * @param top        Top margin in inches.    Excel default is 0.75.
+ * @param bottom     Bottom margin in inches. Excel default is 0.75.
+ *
+ * The `%chartsheet_set_margins()` function is used to set the margins of the
+ * chartsheet when it is printed. The units are in inches. Specifying `-1` for
+ * any parameter will give the default Excel value as shown above.
+ *
+ * @code
+ *    chartsheet_set_margins(chartsheet, 1.3, 1.2, -1, -1);
+ * @endcode
+ *
+ */
+void chartsheet_set_margins(lxw_chartsheet *chartsheet, double left,
+                            double right, double top, double bottom);
+
+/**
+ * @brief Set the printed page header caption.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param string     The header string.
+ *
+ * @return A #lxw_error code.
+ *
+ * Headers and footers are generated using a string which is a combination of
+ * plain text and control characters
+ *
+ * @code
+ *     chartsheet_set_header(chartsheet, "&LHello");
+ *
+ *     //     ---------------------------------------------------------------
+ *     //    |                                                               |
+ *     //    | Hello                                                         |
+ *     //    |                                                               |
+ *
+ *
+ *     chartsheet_set_header(chartsheet, "&CHello");
+ *
+ *     //     ---------------------------------------------------------------
+ *     //    |                                                               |
+ *     //    |                          Hello                                |
+ *     //    |                                                               |
+ *
+ *
+ *     chartsheet_set_header(chartsheet, "&RHello");
+ *
+ *     //     ---------------------------------------------------------------
+ *     //    |                                                               |
+ *     //    |                                                         Hello |
+ *     //    |                                                               |
+ *
+ *
+ * @endcode
+ *
+ * See `worksheet_set_header()` for a full explanation of the syntax of
+ * Excel's header formatting and control characters.
+ *
+ */
+lxw_error chartsheet_set_header(lxw_chartsheet *chartsheet,
+                                const char *string);
+
+/**
+ * @brief Set the printed page footer caption.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param string     The footer string.
+ *
+ * @return A #lxw_error code.
+ *
+ * The syntax of this function is the same as chartsheet_set_header().
+ *
+ */
+lxw_error chartsheet_set_footer(lxw_chartsheet *chartsheet,
+                                const char *string);
+
+/**
+ * @brief Set the printed page header caption with additional options.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param string     The header string.
+ * @param options    Header options.
+ *
+ * @return A #lxw_error code.
+ *
+ * The syntax of this function is the same as chartsheet_set_header() with an
+ * additional parameter to specify options for the header.
+ *
+ * Currently, the only available option is the header margin:
+ *
+ * @code
+ *
+ *    lxw_header_footer_options header_options = { 0.2 };
+ *
+ *    chartsheet_set_header_opt(chartsheet, "Some text", &header_options);
+ *
+ * @endcode
+ *
+ */
+lxw_error chartsheet_set_header_opt(lxw_chartsheet *chartsheet,
+                                    const char *string,
+                                    lxw_header_footer_options *options);
+
+/**
+ * @brief Set the printed page footer caption with additional options.
+ *
+ * @param chartsheet Pointer to a lxw_chartsheet instance to be updated.
+ * @param string     The footer string.
+ * @param options    Footer options.
+ *
+ * @return A #lxw_error code.
+ *
+ * The syntax of this function is the same as chartsheet_set_header_opt().
+ *
+ */
+lxw_error chartsheet_set_footer_opt(lxw_chartsheet *chartsheet,
+                                    const char *string,
+                                    lxw_header_footer_options *options);
+
+lxw_chartsheet *lxw_chartsheet_new(lxw_worksheet_init_data *init_data);
+void lxw_chartsheet_free(lxw_chartsheet *chartsheet);
+void lxw_chartsheet_assemble_xml_file(lxw_chartsheet *chartsheet);
+
+/* Declarations required for unit testing. */
+#ifdef TESTING
+
+STATIC void _chartsheet_xml_declaration(lxw_chartsheet *chartsheet);
+STATIC void _chartsheet_write_sheet_protection(lxw_chartsheet *chartsheet);
+#endif /* TESTING */
+
+/* *INDENT-OFF* */
+#ifdef __cplusplus
+}
+#endif
+/* *INDENT-ON* */
+
+#endif /* __LXW_CHARTSHEET_H__ */

+ 77 - 0
src/3rdparty/libxlsxwriter/include/xlsxwriter/comment.h

@@ -0,0 +1,77 @@
+/*
+ * libxlsxwriter
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ * Copyright 2014-2026, John McNamara, jmcnamara@cpan.org.
+ *
+ * comment - A libxlsxwriter library for creating Excel XLSX comment files.
+ *
+ */
+#ifndef __LXW_COMMENT_H__
+#define __LXW_COMMENT_H__
+
+#include <stdint.h>
+
+#include "common.h"
+#include "worksheet.h"
+
+/* Define the tree.h RB structs for the red-black head types. */
+RB_HEAD(lxw_author_ids, lxw_author_id);
+
+/*
+ * Struct to represent a comment object.
+ */
+typedef struct lxw_comment {
+
+    FILE *file;
+    struct lxw_comment_objs *comment_objs;
+    struct lxw_author_ids *author_ids;
+    char *comment_author;
+    uint32_t author_id;
+
+} lxw_comment;
+
+/* Struct to an author id */
+typedef struct lxw_author_id {
+    uint32_t id;
+    char *author;
+
+    RB_ENTRY (lxw_author_id) tree_pointers;
+} lxw_author_id;
+
+#define LXW_RB_GENERATE_AUTHOR_IDS(name, type, field, cmp) \
+    RB_GENERATE_INSERT_COLOR(name, type, field, static)    \
+    RB_GENERATE_REMOVE_COLOR(name, type, field, static)    \
+    RB_GENERATE_INSERT(name, type, field, cmp, static)     \
+    RB_GENERATE_REMOVE(name, type, field, static)          \
+    RB_GENERATE_FIND(name, type, field, cmp, static)       \
+    RB_GENERATE_NEXT(name, type, field, static)            \
+    RB_GENERATE_MINMAX(name, type, field, static)          \
+    /* Add unused struct to allow adding a semicolon */    \
+    struct lxw_rb_generate_author_ids{int unused;}
+
+
+/* *INDENT-OFF* */
+#ifdef __cplusplus
+extern "C" {
+#endif
+/* *INDENT-ON* */
+
+lxw_comment *lxw_comment_new(void);
+void lxw_comment_free(lxw_comment *comment);
+void lxw_comment_assemble_xml_file(lxw_comment *self);
+
+/* Declarations required for unit testing. */
+#ifdef TESTING
+
+STATIC void _comment_xml_declaration(lxw_comment *self);
+
+#endif /* TESTING */
+
+/* *INDENT-OFF* */
+#ifdef __cplusplus
+}
+#endif
+/* *INDENT-ON* */
+
+#endif /* __LXW_COMMENT_H__ */

+ 0 - 0
src/3rdparty/libxlsxwriter/include/xlsxwriter/common.h


Некоторые файлы не были показаны из-за большого количества измененных файлов