Переглянути джерело

chore(git): develop 合并三条支线(数据集门禁 / edge-v2-wide / 稳定性复核)

kwass 3 днів тому
батько
коміт
66685d50b8

+ 3 - 2
README.md

@@ -195,8 +195,9 @@ cmake -S cpp -B build -DCMAKE_BUILD_TYPE=Release
 cmake --build build -j
 ctest --test-dir build --output-on-failure     # 八个自检全绿(200 / 269 / 110 / 231 / 112 / 54 / 56 / 104)
 
-# 一条命令跑完"冻结点"回归(ctest + Python 357 单测 + v1/v2 现场回放),失败即非 0 退出
-python scripts/regression_freeze.py --build-dir build
+# 一条命令跑完"冻结点"回归(ctest + Python 单测 + v1/v2 现场回放 + 数据集安全门禁),失败即非 0 退出
+python scripts/regression_freeze.py --build-dir build --dataset-dir <语料目录>
+#    数据集门禁用 docs/evidence/test_2026-11-20/baseline_violations.json,**只卡新增违例**(禁止变差)
 
 # 跑起来(PLC 用 MB_CLIENT 轮询 1502 端口读 12 个字结果区)
 # 现场参数都在配置文件里:**改参数不重编译**

+ 1 - 0
configs/README.md

@@ -12,6 +12,7 @@
 | `edge-cpp.json` | **C++ 版(`portcv_run`)专用**:`run.backend=edge`(二维边缘几何证据,不需要 NPU/OpenCV/模型)+ `edge.*` 参数模板。键名与 Python 同名同义,但 `backend=edge` 只有 C++ 版认识 —— Python 侧请继续用上面的模板 |
 | `edge-v2-front.json` | **C++/Python 通用 v2 前视模板(A/B 回放)**:`run.backend=evidence-v2` + `evidence_v2.enabled=true` + `require_commit=true` + `allow_state2=true` + `allow_state3=true`;`source.type=images`(PGM 序列,零依赖)。动态 ROI + 门板立柱/车面边梁 + commit 落位门,判据见 `docs/route_v2.md` |
 | `edge-v2-rtsp.json` | **C++ 真机 v2 模板**:与 `edge-v2-front.json` **判据完全相同**,只把 `source` 换成 `type=rtsp` + `uri`(占位 `192.168.1.64`,上线前改现场相机)。`plc.enabled=true`,`portcv-cpp.service` 直接指这份即可从 v1 切到 v2 |
+| `edge-v2-wide.json` | **广角 / 远景 / 高点机位(域外)专用**:`view=high` + `allow_state2=false` + `allow_state3=false` + 关掉空车/空平车判据 ⇒ **只发 `1` 与 `0`**。为什么:几何判据按部署机位(近距前视)整定,广角侧视下"集装箱侧壁 vs 敞车侧墙"在 `posts/opacity/span` 上完全重叠(`docs/route_v2.md` §9.3 2026-11-20),强行判 `2/3` 只会产生危险误报;宁可弃权。**验收口径只有安全方向**(载车不得判 3、空车不得判 1/2、作业帧不得判车型),召回率要等 `docs/field_capture_spec.md` 的现场素材 |
 | `demo-yolov8n.json` | **RKNN 数值冒烟专用**(不是现场模板):COCO YOLOv8n 的 80 类权重 + `input_format=rgb_uint8` + `quantized=false`,配 `scripts/verify_rknn.py` 做 ONNX↔NPU 数值比对(bus.jpg 应出 person×3 + bus)。`demo-*.json` 由 `scripts/check_configs.py` 自动跳过 4 类契约 |
 
 现场事实(2026-10-10 确认,直接影响配置):

+ 211 - 0
configs/edge-v2-wide.json

@@ -0,0 +1,211 @@
+{
+  "_note": [
+    "广角 / 远景 / 高点机位(域外)专用参数组:只发 1(敞车)与 0(不判),不发 2 / 3。",
+    "为什么:几何判据(车面边梁、门板立柱、箱底暗带)是在部署机位(近距前视、箱底与车面在画面中部)整定的;",
+    "  广角/远景侧视下,集装箱侧壁与敞车侧墙在 posts/opacity/span 上完全重叠",
+    "  (docs/route_v2.md §9.3 2026-11-20、docs/evidence/test_2026-11-20/测试报告.md §六),强行判 2/3 只会产生危险误报。",
+    "取舍:宁可弃权(PLC 保持上一稳定值),也不把 2/3 发给 PLC;1(门板阵列横跨整车)在广角下仍相对稳,保留。",
+    "验收口径(与近距模板不同):只看安全方向——载车不得判 3、空车不得判 1/2、作业帧不得判车型;",
+    "  召回率必须在按 docs/field_capture_spec.md 补拍的现场素材上另议。",
+    "用法:portcv_run -c configs/edge-v2-wide.json --backend edge-v2 --source-type images --source-uri <PGM 目录> --no-plc",
+    "回放/门禁:python scripts/dataset_harness.py --images <语料目录> --config configs/edge-v2-wide.json --labels docs/evidence/test_2026-11-20/labels.json",
+    "view=high 是语义标记(本模板声明“这是高位/广角机位”),不是自动视角识别;P1d 视角头仍未实现。"
+  ],
+  "run": {
+    "mode": "composed",
+    "backend": "evidence-v2",
+    "max_fps": 15.0,
+    "warmup_frames": 3,
+    "log_level": "INFO",
+    "log_json": false,
+    "save_on_change": true,
+    "output_dir": "runs/edge_v2_wide",
+    "preview": false
+  },
+  "health": {
+    "enabled": true,
+    "work_width": 320,
+    "blur_var_min": 18.0,
+    "dark_clip_ratio_max": 0.97,
+    "bright_clip_ratio_max": 0.55,
+    "low_texture_ratio_max": 0.88,
+    "degrade_persist_s": 0.8,
+    "recover_persist_s": 1.5
+  },
+  "source": {
+    "type": "images",
+    "uri": "runs/frames_wide",
+    "width": 0,
+    "height": 0,
+    "buffer_size": 2,
+    "use_gst": false,
+    "reconnect_s": 2.0,
+    "stale_frame_s": 0.6
+  },
+  "calibration": {
+    "_comment": "P0-5 标定记录:填 configs/calib/<站点>-<机位>.json;留空则不做判定(只受 stale 开关控制)。hold_on_stale=true 时标定不可信会清 RESULT_VALID/STABLE。",
+    "stale": false,
+    "record": "",
+    "max_age_days": 180,
+    "px_per_m_tolerance": 0.1,
+    "box_height_tolerance_m": 0.02,
+    "hold_on_stale": true
+  },
+  "scene": {
+    "mode": "composed",
+    "roi": [
+      [
+        0.03,
+        0.1
+      ],
+      [
+        0.97,
+        0.1
+      ],
+      [
+        0.97,
+        0.99
+      ],
+      [
+        0.03,
+        0.99
+      ]
+    ]
+  },
+  "evidence_v2": {
+    "enabled": true,
+    "view": "high",
+    "work_width": 960,
+    "window": [
+      0.24,
+      0.02,
+      0.78,
+      0.95
+    ],
+    "band_min_h": 3,
+    "band_max_h_ratio": 0.15,
+    "bed_search_ratio": 0.4,
+    "box_bottom_max_ratio": 0.78,
+    "below_start_ratio": 0.07,
+    "below_height_ratio": 0.55,
+    "below_min_height_px": 24,
+    "min_door_posts": 5,
+    "max_door_posts": 16,
+    "max_bed_gap_px": 40.0,
+    "flat_max_door_posts": 4,
+    "max_post_spacing_cv": 6.0,
+    "min_post_len_ratio": 0.3,
+    "min_post_spacing_px": 24.0,
+    "min_diagonal_braces": 1,
+    "min_post_span_ratio": 0.23,
+    "texture_top_enable": true,
+    "texture_grad_th": 50.0,
+    "texture_block_px": 16,
+    "texture_block_hit_ratio": 0.03,
+    "texture_coverage_min": 0.5,
+    "texture_run_rows": 3,
+    "texture_smooth_rows": 7,
+    "texture_top_margin_ratio": 0.02,
+    "body_fallback_enable": true,
+    "body_bottom_ratio": 0.75,
+    "body_min_opacity": 0.5,
+    "body_min_roi_px": 90,
+    "body_canny_lo_pct": 0.55,
+    "body_canny_hi_pct": 0.75,
+    "body_min_points": 4,
+    "body_grad_pct": 0.6,
+    "body_min_inlier_ratio": 0.5,
+    "body_run_min_len_ratio": 0.2,
+    "body_min_post_len_ratio": 0.15,
+    "body_x_margin_ratio": 0.03,
+    "body_min_posts": 3,
+    "vehicle_min_span_ratio": 0.5,
+    "vehicle_max_posts": 60,
+    "empty_vehicle_enable": false,
+    "empty_min_posts": 3,
+    "empty_min_span_ratio": 0.6,
+    "empty_min_opacity": 0.55,
+    "empty_min_wall_h_ratio": 0.25,
+    "empty_min_post_len_ratio": 0.3,
+    "empty_fallback_max_posts": 4,
+    "empty_min_diagonal_braces": 1,
+    "empty_flatbed_enable": false,
+    "empty_flatbed_min_gap_px": 16.0,
+    "empty_flatbed_max_plane_edge": 0.12,
+    "empty_flatbed_max_gray_drop": 80.0,
+    "empty_top_margin_ratio": 0.0,
+    "allow_state3": false,
+    "min_wall_opacity": 0.35,
+    "wall_edge_density_ref": 0.14,
+    "wall_edge_density_span": 0.04,
+    "ground_block_px": 32,
+    "ground_density_lo": 0.02,
+    "ground_density_hi": 0.35,
+    "min_zero_ground_ratio": 0.65,
+    "deck_min_len_ratio": 0.3,
+    "contact_max_h_ratio": 0.12,
+    "under_deck_dark_delta": 12.0,
+    "under_deck_min_h_ratio": 0.01,
+    "under_deck_search_h_ratio": 0.1,
+    "max_flat_gap_px": 40.0,
+    "box_height_m": 2.591,
+    "px_per_m": 0.0,
+    "min_scale_px": 60.0,
+    "motion_diff_max": 12.0,
+    "motion_grad_ratio_min": 0.72,
+    "require_commit": true,
+    "allow_state2": false,
+    "structure_hits_min": 0.6,
+    "min_bed_roi_px": 90,
+    "reject_hoist_high": true,
+    "hoist_dark_max": 75,
+    "hoist_band_frac": 0.035,
+    "hoist_line_ratio": 0.2,
+    "hoist_dark_ratio": 0.55,
+    "hoist_bright_delta": 12.0,
+    "reject_spreader_contact": true,
+    "spreader_dark_max": 110,
+    "spreader_dark_ratio": 0.55,
+    "commit": {
+      "gap_m_max": 0.1,
+      "gap_px_hard_max": 8.0,
+      "stable_frames": 5,
+      "structure_frames": 5,
+      "min_structure_hits": 0.6,
+      "max_gap_rise_m": 0.01,
+      "allow_state1": true,
+      "allow_state2": false,
+      "allow_state3": false,
+      "require_motion_ok": true,
+      "require_view_known": true,
+      "use_plc_arrival": true
+    }
+  },
+  "decision": {
+    "window": 9,
+    "window_s": 1.0,
+    "min_votes": 4,
+    "min_confidence": 0.45,
+    "min_dwell_s": 0.2,
+    "hold_s": 0.6,
+    "lost_timeout_s": 1.5,
+    "low_fps_threshold": 3.0
+  },
+  "plc": {
+    "enabled": true,
+    "push": "modbus_server",
+    "modbus": {
+      "host": "0.0.0.0",
+      "port": 1502,
+      "unit_id": 1,
+      "input_addr": 0,
+      "holding_addr": 0,
+      "allow_unit_any": true
+    },
+    "gating": false,
+    "gating_timeout_ms": 800,
+    "heartbeat_ms": 500,
+    "confidence_scale": 1000,
+    "min_publish_interval_ms": 50
+  }
+}

+ 5 - 2
cpp/README.md

@@ -80,8 +80,11 @@ ctest --test-dir build --output-on-failure
 | `portcv_v2_selftest` | **54 通过 / 0 失败** | V2 PublishGate 的 12 个契约向量、状态保持/复位、half-up 千分比 |
 | `portcv_edge_v2_selftest` | **75 通过 / 0 失败** | edge-v2 证据链:零间隙接触、侧视 flatbed、`allow_state2` 回退、空帧/无图 abstain;**P0-0 吊具高悬 / 夹箱门**(合成高悬帧 6 帧 0 commit、注入路径、远距 ROI 弃权、门关闭对照);**P0-Q3 地面/堆料/堆叠箱负样本**(不得判 1/2) |
 
-> 一条命令跑完全部四层(ctest + Python 单测 + v1 `edge` 现场回放 + v2 `edge-v2` 现场回放):
-> `python scripts/regression_freeze.py --build-dir build-cmake/windows-zig-release`。
+> 一条命令跑完全部五层(ctest + Python 单测 + v1 `edge` 现场回放 + v2 `edge-v2` 现场回放
+> + **数据集安全门禁**):
+> `python scripts/regression_freeze.py --build-dir build-cmake/windows-zig-release --dataset-dir <语料目录>`。
+> 数据集门禁用的是 `docs/evidence/test_2026-11-20/baseline_violations.json`(**只卡新增违例**,
+> 见 `docs/route_v2.md` §9.3);不指 `--dataset-dir` 时这一组明确 SKIP 而不是假装通过。
 > 已知失败(`runs/ab_A_s2.jsonl` 那 1 条"投票器把 1/2 混了")写在脚本白名单里,**要求恰好 1 条
 > 且必须匹配该原因**;多一条、换原因、缺产物都算 FAIL —— 不会把失败偷偷标成跳过。
 

+ 5 - 0
docs/README.md

@@ -10,6 +10,7 @@
 | [deployment.md](deployment.md) | 实施/运维 | 各平台环境、模型转换、现场联调、systemd、标定与验收清单、FAQ |
 | [data_retention.md](data_retention.md) | 实施/运维/验收 | **P0-4 数据证据链**:逐帧 JSONL、50 MB 切分、事件视频环缓、90 天保留、断电恢复演练与容量估算 |
 | [calibration.md](calibration.md) | **实施/运维/验收** | **P0-5 标定记录**:字段/哈希/复核、过期与比例尺/箱高漂移判定、`CALIB_STALE`、现场重标流程 |
+| [field_capture_spec.md](field_capture_spec.md) | **实施/客户/算法** | **现场素材采集规范**:机位/俯角/取景/距离、四态必拍、目录与命名、`labels.json` 标注契约、**网上图库素材的使用边界**(只能当域外负样本池) |
 | [test_plan_gbt45163_5.md](test_plan_gbt45163_5.md) | **客户/测试/验收** | **P0-7 试验计划**:安全/契约/证据/标定/时延用例、现场 ODD 矩阵与 300 事件样本量、通过准则与工装 |
 | [stability_soak.md](stability_soak.md) | 开发/测试/实施 | C++ 边端稳定性 / 鲁棒性 / 浸泡实测报告:配置与命令行 fuzz、Modbus/TCP 折磨、30 min 资源曲线、发现的缺口与补丁建议、板卡执行清单 |
 | [soak_7x24.md](soak_7x24.md) | **开发/测试/实施/验收** | **168 h 工业落地前门禁**:内存/句柄/线程/帧进度/Modbus 探活/温度/磁盘判据、systemd 常驻、断点续跑、故障注入矩阵、ASan 补充与证据归档 |
@@ -22,6 +23,10 @@
 * `evidence/p0_v2/report.md` —— P0 A/B 结构可分性自动测量(`scripts/p0_v2_measure.py` 生成,
   含逐帧 JSONL 与关键帧标注图);`evidence/p0_v2/p0_conclusion.md` 是**评审结论页**
   (自动测量 + 既有 C++ dump + 人工关键帧读数 + P0 gate);
+* `evidence/test_2026-11-20/` —— **数据集回归**:`测试报告.md`(39 张 web_cc + 4 段视频逐条结果)
+  + `labels.json`(人工判读的机器可读版),配合 `scripts/dataset_harness.py` 一键复现
+  「本帧候选 / 发布值」并卡「载车不得判 3、空车不得判 1/2、作业帧不得判车型」三条安全断言
+  (违例退出码 1,可进 CI);
 * `configs/README.md` —— 配置模板与"如何新建现场配置";
 * `cpp/README.md` —— C++17 生产实现的构建、自检与一致性校验;
 * `../tests/test_publish_gate.py` / `../cpp/tests/selftest_v2.cpp` —— P1a PublishGate 的

+ 2 - 2
docs/deployment.md

@@ -38,8 +38,8 @@ ctest --test-dir build --output-on-failure
 #        portcv_edge_selftest 112 通过 / 0 失败
 #        portcv_edge_v2_selftest 75 通过 / 0 失败(含 P0-0 吊具高悬 / 夹箱门、P0-Q3 地面/堆料负样本)
 #
-#   不想逐条敲?一条命令跑完四层(ctest + Python 单测 + v1/v2 现场回放):
-#        python scripts/regression_freeze.py --build-dir build
+#   不想逐条敲?一条命令跑完五层(ctest + Python 单测 + v1/v2 现场回放 + 数据集安全门禁):
+#        python scripts/regression_freeze.py --build-dir build --dataset-dir <语料目录>
 #   缺产物 / 多一条失败都会非 0 退出;只有在纯算法机上才用 --allow-missing 降级为 SKIP。
 #        (2026-10-27 起全绿;历史上的 12 项失败是 C1/F2/F3/G2 证据路径,修法见 docs/edge_evidence.md §7.1)
 

+ 27 - 0
docs/evidence/test_2026-11-20/baseline_violations.json

@@ -0,0 +1,27 @@
+{
+  "_note": [
+    "已知安全违例基线(2026-11-20,`configs/edge-v2-front.json` + dataset_package_20251120)。",
+    "键 = 文件名:发布值。语义是**禁止变差**:登录在案的违例允许存在,新增一条即 FAIL。",
+    "来源:docs/evidence/test_2026-11-20/测试报告.md §九(43 张,9 条)。",
+    "★ 这 9 条**全部落在域外素材**(web 8 + field 1);近距对照集 4/4 命中。",
+    "  修好一条 → scripts/dataset_harness.py 会提示“已修复,请同步基线”;",
+    "  但**不要**为了让门禁变绿而把新违例加进来 —— 加条目必须写明理由与整改项。",
+    "用法:python scripts/dataset_harness.py --images <语料目录> \\",
+    "      --labels docs/evidence/test_2026-11-20/labels.json \\",
+    "      --baseline-violations docs/evidence/test_2026-11-20/baseline_violations.json"
+  ],
+  "generated": "2026-11-20",
+  "config": "configs/edge-v2-front.json",
+  "dataset": "dataset_package_20251120(39 张 web_cc + 4 张近距对照 + test1/test2)",
+  "violations": [
+    "test1.png:3",
+    "NX70_003.jpg:3",
+    "X160_001.jpg:1",
+    "X70_004.jpg:3",
+    "X70_007.jpg:3",
+    "X70_008.jpg:3",
+    "X70_010.jpg:3",
+    "C64K_001.jpg:2",
+    "C70E_001.jpg:1"
+  ]
+}

+ 199 - 0
docs/evidence/test_2026-11-20/labels.json

@@ -0,0 +1,199 @@
+{
+  "_note": [
+    "2026-11-20 数据集 Package(dataset_package_20251120.zip)的人工判读表 —— 逐条抄自本目录《测试报告.md》第三/五节。",
+    "★ 数据域(domain)务必按实际来源填:field = 现场实拍(部署机位/司机视角)、near = 近距前视素材、web = 网上图库。",
+    "  本批 web_cc 的 39 张来自网上图库(广角/远景),拍摄角度与距离和部署机位不同 → domain=web,",
+    "  数字只能用于「会不会危险误报」的安全方向回归,**不得**当作现场精度(召回/准确率)。",
+    "  只有 domain=field 的样本才能支撑现场精度结论;本机目前只有 test1/test2 两帧司机视角实拍。",
+    "用途:python scripts/dataset_harness.py --images <目录...> --labels 本文件 [--domain field|near|web]",
+    "label 取值(与 scripts/dataset_harness.py 的 LABEL_EXPECT 对应):",
+    "  boxed_flatbed 平车坐箱 → 2;boxed_gondola 敞车坐箱 → 1;empty_gondola 空敞车 → 3;",
+    "  empty_flatbed 空平车 → 3;working 作业中(吊具吊箱悬于平车上方)→ 0(不判)。",
+    "安全断言(GATE_FORBID):载车不得发 3;空车不得发 1/2;作业帧不得发 1/2/3。"
+  ],
+  "_source": {
+    "report": "docs/evidence/test_2026-11-20/测试报告.md",
+    "images_web_cc": "39 张(domain=web,网上图库):平车 21(NX70 ×3 / X160 ×7 / X70 ×11)+ 敞车 16(C64K ×6 / C64 ×1 / C70E ×4 / C70H ×1 / C70 ×3 / C80 ×1)+ 作业中 2(test1/test2.png,司机视角实拍 → domain=field)",
+    "images_ctl": "4 张(domain=near,近距前视素材):ctl_05/06/07 不在本机,未列入",
+    "videos": "video1..4 未列入本表:先用 scripts/extract_frames.py 抽帧,再按其人工判读另建 labels(同样要标 domain)",
+    "gap": "现场 A/B 片段(runs/frames_A1、runs/frames_B)本机缺失 → 现场精度回归基线待回填"
+  },
+  "NX70_001.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed",
+    "note": "空平车:报告判 2(弃权),属已记录的 deck_edge 漏报"
+  },
+  "NX70_002.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "NX70_003.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X160_001.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed"
+  },
+  "X160_002.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed"
+  },
+  "X160_003.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed"
+  },
+  "X160_004.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed"
+  },
+  "X160_005.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed"
+  },
+  "X160_006.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed"
+  },
+  "X160_007.jpg": {
+    "domain": "web",
+    "label": "empty_flatbed"
+  },
+  "X70_001.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_002.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_003.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_004.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_005.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_006.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_007.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_008.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_009.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_010.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "X70_011.jpg": {
+    "domain": "web",
+    "label": "boxed_flatbed"
+  },
+  "C64K_001.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C64K_002.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C64K_003.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C64K_004.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C64K_005.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C64K_006.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C64_001.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70E_001.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70E_002.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70E_003.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70E_004.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70H_001.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70_001.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70_002.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C70_003.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "C80_001.jpg": {
+    "domain": "web",
+    "label": "empty_gondola"
+  },
+  "test1.png": {
+    "domain": "field",
+    "label": "working",
+    "note": "司机视角、吊具吊箱悬在平车上方;报告里仍被空车判据判 3(风险项,image 侧 hoist 未触发)"
+  },
+  "test2.png": {
+    "domain": "field",
+    "label": "working"
+  },
+  "01_flatcar_0022.jpg": {
+    "domain": "near",
+    "label": "boxed_flatbed",
+    "note": "对照集:近距前视,真值 2"
+  },
+  "02_C70E_shigure03.jpg": {
+    "domain": "near",
+    "label": "empty_gondola",
+    "note": "对照集:空 C70E,真值 3"
+  },
+  "03_C70EA_DF10.jpg": {
+    "domain": "near",
+    "label": "empty_gondola",
+    "note": "对照集:空 C70EA,真值 3"
+  },
+  "04_container_on_gondola.png": {
+    "domain": "near",
+    "label": "boxed_gondola",
+    "note": "对照集:罐箱在敞车内,真值 1(箱底被车帮挡住)"
+  }
+}

+ 99 - 0
docs/evidence/test_2026-11-20/测试报告.md

@@ -142,3 +142,102 @@
 4. **本 zip 的 web_cc 39 张不能作为现场精度依据**;验收仍以现场机位片段(A/B + 对照集)为准,
    但这些图正好暴露了 `3` 与 `2` 的边界问题,建议纳入回归负样本池(断言「载车不得 3」)。
 
+
+## 九、复现与门禁(2026-11-20 收口)
+
+上面几张表原先只有一套临时 harness(`%TEMP%` 里的 PGM chunk + 逐个 `portcv_run`)能跑出来,
+harness 本身没进仓 —— 报告无法复现,改判据也没有门禁。现已收口成两件仓内资产:
+
+| 资产 | 作用 |
+|---|---|
+| `scripts/dataset_harness.py` | 用 **C++ `edge-v2`(生产路径)**跑「本帧候选 + 发布值」两遍口径,出 Markdown 表 + JSON 小结 + 安全断言 |
+| `docs/evidence/test_2026-11-20/labels.json` | 本报告第三/五节的人工判读,转成机器可读标签(`boxed_flatbed` / `boxed_gondola` / `empty_gondola` / `empty_flatbed` / `working`) |
+
+```bash
+python scripts/dataset_harness.py \
+    --images <web_cc/平车> <web_cc/敞车> <test1.png> <test2.png> <ctl_original> \
+    --labels docs/evidence/test_2026-11-20/labels.json --out runs/harness
+# 退出码 1 = 安全断言违例(载车判 3 / 空车判 1 或 2 / 作业帧判 1、2、3)
+
+# 只跑某一数据域(★ 现场精度只能看 field;web 只作域外负样本池)
+python scripts/dataset_harness.py --images <目录...> --labels <labels.json> --domain field
+```
+
+**复现结果(43 张 = 39 张 + 对照集 4 张,`configs/edge-v2-front.json`)**
+
+| 人工判读 | 张数 | 命中 | 弃权 | 误判 | 第二节(39 张) |
+|---|---|---|---|---|---|
+| 平车坐箱 `boxed_flatbed` | 14(含对照集 1) | 1 | 8 | 5 | 13 张:0 / 8 / 5 |
+| 空敞车 `empty_gondola` | 18(含对照集 2) | 9 | 7 | 2 | 16 张:7 / 7 / 2 |
+| 空平车 `empty_flatbed` | 8 | 4 | 3 | 1 | 8 张:4 / 3 / 1 |
+| 敞车坐箱 `boxed_gondola` | 1(对照集) | 1 | 0 | 0 | 对照集:命中 |
+| 作业中 `working` | 2 | 1 | 0 | 1 | 2 张:1 / 0 / 1 |
+| **合计** | **43** | **16** | **18** | **9** | 39 张:12 / 18 / 9 |
+
+> 差额全部来自对照集 4 张(命中 4);去掉后与第二节**逐格一致**:弃权 18 / 误判 9。
+
+**按数据域拆分(同一批 43 张)**
+
+| 数据域 | 张数 | 命中 | 弃权 | 误判 | 读法 |
+|---|---|---|---|---|---|
+| `near` 近距前视对照集 | 4 | 4 | 0 | 0 | 仅作回归参照(不是现场工况片段) |
+| `field` 现场实拍(司机视角) | 2 | 1 | 0 | 1 | 可作现场证据,但只有 2 帧,**不足以谈精度** |
+| `web` 网上图库(广角 / 远景) | 37 | 11 | 18 | 8 | **只看安全方向**,命中率不作数 |
+
+> ★ 这批 `web_cc` 的 39 张是**网上找的图库照片**,拍摄角度与距离跟部署机位
+> (相机固定在车身左前方、近距、箱底与车面落在画面中部)不是一回事 —— 属**域外**。
+> 9 条安全违例**全部落在域外**(`web` 8 + `field` 1),唯一近距对照集 **4/4 命中**,
+> 与 §六 的判断一致:几何判据在近距机位成立、在广角/远景失效。
+> 现场精度(召回 / 准确率)必须等按 `docs/field_capture_spec.md` 补拍的 `field` 素材。
+
+**门禁当前 9 条(与 §三 完全对应,判据本身未改)**
+
+| 文件 | 人工判读 | 发布 | 判据 |
+|---|---|---|---|
+| `test1.png` | 作业中 | 3 | `empty_vehicle`(吊具未触发 `hoist_high`) |
+| `NX70_003` / `X70_004` / `X70_007` / `X70_008` / `X70_010` | 平车坐箱 | 3 | `empty_vehicle`(箱体瓦楞被当成门板立柱) |
+| `X160_001` | 空平车 | 1 | `wall_posts`(车帮/端墙竖棱被数成门板) |
+| `C70E_001` | 空敞车 | 1 | `wall_posts` |
+| `C64K_001` | 空敞车 | 2 | `deck_edge`(车帮顶面亮边被当成车面边梁) |
+
+**两个口径坑(已写进脚本注释)**
+
+1. **必须走 C++**:`video2` 这类广角素材在 Python 参考实现上多为 `255 weak_evidence`
+   (本机 6 个抽样帧只有 1 帧判 `2`),用 Python 量会得出"没有问题"的错结论;
+2. **不要调快 fps**:`decision.min_dwell_s=0.2 s` 要求落位驻留,20 帧同图若被 `--fps 240`
+   跑到 83 ms,投票永远不发布,表里会整片变成"弃权"(本 harness 首版就踩过,
+   对照集 3 张本该发 `3`/`1` 却发 `0`)。
+
+**结论**:本报告 §六 的结论(几何判据在域外机位上无法分辨"集装箱侧壁 vs 敞车侧墙"、
+需要车型小分类器)被这次复现再次证实 —— `posts` / `opacity` 在载车与空车之间
+仍然完全重叠,且 9 条违例**全部落在域外**(近距对照集 4/4 命中)。因此**本轮不再调阈值**,
+`labels.json` + 门禁作为后续分类器的 A/B 量测台;现场精度以
+`docs/field_capture_spec.md` 口径补拍的 `field` 素材为准。
+
+## 十、域外安全模式:`configs/edge-v2-wide.json`(2026-11-20)
+
+既然"域外机位判不了 2/3",就给它一个**显式参数组**,而不是继续硬套近距模板
+(`docs/route_v2.md` §8 建议 3 的最小实现)。同一批 43 张,只换配置:
+
+| 配置 | 安全违例 | 域外(web 37 张)分布 | 近距对照(near 4 张) |
+|---|---|---|---|
+| `edge-v2-front.json`(近距前视模板) | **9**(web 8 + field 1) | 命中 11 / 弃权 18 / 误判 8 | **4/4 命中** |
+| `edge-v2-wide.json`(`view=high` + 不发 2/3 + 关空车判据) | **2**(全部 web) | 命中 0 / 弃权 35 / 误判 2 | 命中 1 / 弃权 3 |
+
+* **清零的方向**:载车判 `3`(5 条)、空车判 `2`(1 条)、作业帧判 `3`(1 条)—— 即所有
+  "会触发错误装卸动作"的 `2/3` 误发,在广角机位上一律消失;
+* **剩余 2 条**:`X160_001`、`C70E_001` 的"空车判 `1`"(反方向:把空敞车侧墙当成载车侧墙),
+  关掉 2/3 修不了它,需要车型证据/分类器,等 `field` 素材;
+* **代价(必须写明)**:域外不再谈召回(命中 0),近距对照从 4/4 掉到 1/4 ——
+  所以这份模板**只给广角/远景/高点机位用**,部署机位继续用 `edge-v2-front.json` /
+  `edge-v2-rtsp.json`。
+
+复现:
+
+```bash
+python scripts/dataset_harness.py --images <语料目录> \
+    --labels docs/evidence/test_2026-11-20/labels.json \
+    --config configs/edge-v2-wide.json --out runs/harness_wide
+```
+
+

+ 111 - 0
docs/field_capture_spec.md

@@ -0,0 +1,111 @@
+# 现场素材采集规范(P1 语料 / 回归基线)
+
+> **为什么要有这份文件**:2026-11-20 那批 39 张 `web_cc` 图是**网上图库**(广角/远景侧视),
+> 拍摄角度与距离和部署机位(相机固定在车身左前方、近距、箱底与车面在画面中部)不是一回事。
+> 拿它们整定阈值或算召回率,得到的是"图库外观"而不是"现场工况"。**现场素材是唯一能支撑
+> 精度结论的数据**;网上素材只能当**域外负样本池**(见 §7)。
+
+## 1. 机位与光学(先固定,再谈精度)
+
+| 项 | 要求 | 归档 |
+| --- | --- | --- |
+| 安装位置 | 相机**固定在车身左前方**,不在吊臂上、不随臂俯仰(`docs/edge_evidence.md` §12.8 Q1) | 装机照片 + 视野全图 |
+| 几何 | 记录安装高度(m)、到车体中心线水平距离(m)、**俯角**、**偏角**、焦距/视场角 | 随标定记录(`configs/calib/`)一起存,见 `docs/calibration.md` |
+| 相机参数 | 分辨率、帧率、曝光/增益(是否自动)、镜头型号 | 同上 |
+| 取景 | **箱底与车面(或车帮上沿)必须同框**;车体不要贴画面边缘;整箱**不要占满**画幅 | 与 `configs/edge-v2-front.json` 的 `evidence_v2.window=[0.24,0.02,0.78,0.95]` 对齐 |
+
+> 越界带 / 车帮上缘的证据要**余量**:整箱贴满画幅时亮带断续、越界宽度不可靠
+> (`docs/edge_evidence.md` §12.7 第 7 条的答复口径)。
+
+## 2. 拍摄规则(决定能不能判)
+
+1. **不许改工作距离**:按部署实际距离拍;不要为了"看清楚"拉近、上长焦或换机位 ——
+   换了就不是同一 ODD,量出来的数字也不能用。
+2. 每节车至少覆盖「车体上缘 → 车体下缘(**车轮/转向架可见**)」的完整竖向范围;
+   `2`(平车)判据要看到**薄车面边梁 + 边梁下方暗带**,`3`(空车)要看到**整段侧墙**。
+3. 同一机位必须分别拍到三类状态:
+   * **载车**:集装箱**已落位**(箱底贴车面 / 落入敞车车斗);
+   * **空车**:无箱(空敞车、空平车各一组);
+   * **作业中**:箱未落、吊具仍夹箱 / 吊具高悬(这一类**必须**有,`docs/route_v2.md` §4.2 P0-Q11 的硬门就靠它验收)。
+4. 夜间/逆光/雨雾各至少一组(`255` 降级路径需要样本)。
+
+## 3. 采样矩阵(每桶 ≥ 300 个有效落位事件)
+
+与 `docs/test_plan_gbt45163_5.md` §4 同一张表,这里只强调**时间轴**:
+
+| 维度 | 取值 |
+| --- | --- |
+| 车型 × 箱型 | 敞车 20ft / 敞车 40ft / 平车 20ft / 平车 40ft(现场只有这两种箱长) |
+| 状态 | 载车落位、空敞车、空平车、作业中(吊具未松 / 高悬) |
+| 时段 | 白天、夜间(补光开 / 关) |
+| 天气 | 晴、阴、雨 / 雾、逆光 |
+| 姿态偏差 | 车位偏斜、部分遮挡(人员 / 立柱) |
+| 负样本 `0` 类 | 地面、堆场、卡车、堆叠箱、棚车 / 罐车(≥ 20 min) |
+
+## 4. 目录与命名(与抽帧、harness 直接对接)
+
+```
+runs/frames_<站点>_<机位>_<场景>_<光源>/
+    frame_000000.pgm ...
+    manifest.json
+# 例:runs/frames_yard1_front_boxed40_day/
+#     runs/frames_yard1_front_empty_c70_day/
+#     runs/frames_yard1_front_working_spreader_night/
+```
+
+```bash
+# 抽帧(整定语料必须 step 1;只看命中率可用 --step 5)
+python scripts/extract_frames.py --clip 现场.mp4 --out runs/frames_yard1_front_boxed40_day --step 1
+```
+
+原始视频**另存归档**(`docs/data_retention.md`),禁止只留压缩截图。
+
+## 5. 标注契约(与 `scripts/dataset_harness.py` 同一份 `labels.json`)
+
+```json
+{
+  "frame_000123.pgm": {"domain": "field", "label": "boxed_flatbed", "expect": 2,
+                       "note": "40ft 箱已落位,箱底贴车面"}
+}
+```
+
+| 字段 | 取值 | 说明 |
+| --- | --- | --- |
+| `domain` | `field` / `near` / `web` | **现场素材必须写 `field`**;写错会让它进不了精度统计(harness 会打警告) |
+| `label` | `boxed_flatbed` `boxed_gondola` `empty_gondola` `empty_flatbed` `working` | 见 `scripts/dataset_harness.py::LABEL_EXPECT` |
+| `expect` | `0/1/2/3` | 缺省按 label 推(载车平车=2、载车敞车=1、空车=3、作业中=0) |
+| `note` | 自由文本 | 写清判读依据(箱底/车帮/轮对是否可见) |
+
+真值必须**人工**判读并留依据;同一条争议样本至少两人复核。
+
+## 6. 怎么跑
+
+```bash
+# ① 现场精度(唯一可引用):只跑 field 域
+python scripts/dataset_harness.py --images runs/frames_* \
+    --labels labels_field.json --domain field --out runs/harness_field
+
+# ② 安全方向回归(域外负样本池):允许弃权,不允许危险误报
+python scripts/dataset_harness.py --images <web_cc 目录> \
+    --labels docs/evidence/test_2026-11-20/labels.json --domain web --out runs/harness_web
+```
+
+退出码 1 = 安全断言违例(载车判 `3`、空车判 `1`/`2`、作业帧判车型)。
+
+## 7. 网上图库素材的使用边界(★ 2026-11-20 明确)
+
+| 可以 | 不可以 |
+| --- | --- |
+| 作**域外负样本池**:断言"不得出现危险误报" | 作阈值整定的**正样本**(角度/距离都不同,整定出来的阈值到现场必偏) |
+| 作可视化调参参考(`scripts/vis_evidence_v2_steps.py`) | 算召回率 / 准确率、写进验收报告 |
+| 作模型预训练的补充数据(**必须**标注 `domain=web` 并单独报告) | 当现场素材唯一来源去训练车型分类器(学到的是图库外观) |
+
+引用这类数字时一律写明"`domain=web`,非现场素材,仅作安全方向回归"。
+
+## 8. 与验收的关系
+
+* 本规范产出的 `field` 素材是 `docs/test_plan_gbt45163_5.md` §4/§5 的输入(每桶 300 事件);
+* 现场 A/B 片段(`runs/frames_A1`、`runs/frames_B`)是**回归基线**:任何判据改动都要先在这两段上
+  回放(`docs/route_v2.md` §7.1,A 发布 `1×40`、B 发布 `2×40`);
+* 域内素材到位前,`docs/route_v2.md` §9.3 P0-Q11 ③ 与 2026-11-20 harness 结论都只能表述为
+  "域外安全回归通过 / 域外误判已量化",**不得**写成现场精度。

+ 3 - 0
docs/route_v2.md

@@ -827,6 +827,9 @@ else:
 
 | 日期 | 变更 |
 | --- | --- |
+| 2026-11-20 | **数据集门禁进冻结点回归 + 域外安全模式 `edge-v2-wide.json`**:① `scripts/dataset_harness.py` 新增 `--baseline-violations`:**只卡"新增违例"**(基线里的 9 条历史违例允许存在,修好会提示同步基线),把"禁止变差"变成可执行门禁;② `scripts/regression_freeze.py` 新增第 5 组 `gate`(`--dataset-dir` / `PORTCV_DATASET_DIR`,缺语料时明确 FAIL/SKIP 而不是静默跳过),实测 `[PASS] 43 张;违例 9(基线 9)/ 新增 0 / 已修复 0`;③ 新增 `docs/evidence/test_2026-11-20/baseline_violations.json`(9 条,含来源与"不许为变绿而加条目"的约定);④ 新增 `configs/edge-v2-wide.json`:广角/远景/高点机位专用(`view=high` + `allow_state2/3=false` + 关空车判据 ⇒ 只发 `1`/`0`)。实测同一批 43 张:违例 **9 → 2**,载车判 3、空车判 2、作业帧判 3 **全部清零**,剩 2 条"空车判 1"(反方向,需分类器);代价是域外召回归零、近距对照 4/4 → 1/4,故只用于广角机位 |
+| 2026-11-20 | **数据域进回归(把"网上图库"与"现场实拍"分开统计)+ 现场素材采集规范**:① `labels.json` 每条加 `domain`(`field` 现场实拍 / `near` 近距前视 / `web` 网上图库),`scripts/dataset_harness.py` 支持 `--domain` 过滤与按域分表,并在**没有 `field` 样本时打醒目警告**(命中率不得当现场精度)。② 实测拆分(43 张,`edge-v2-front`):`near` **4/4 命中**、`field` 2 张(`test1` 判 `3` 风险项 / `test2` 弃权)、`web` 37 张 **命中 11 / 弃权 18 / 误判 8** —— 9 条安全违例**全部落在域外**(web 8 + field 1),与"广角/远景 + 近距 4:1 不同域"的判断一致。③ 新增 `docs/field_capture_spec.md`:机位/俯角/取景/距离不许改、四态必拍(载车落位 / 空敞车 / 空平车 / 作业中)、`runs/frames_<站点>_<机位>_<场景>_<光源>` 命名、`labels.json` 标注契约,以及**网上图库素材的使用边界**(只能作域外负样本池,不得用于整定/算召回/写验收/单独训练)。④ 缺口写清:现场 A/B(`runs/frames_A1`/`frames_B`)本机缺失,域内精度与回归基线待回填 |
+| 2026-11-20 | **数据集 harness 入仓(把"报告里的数字"变成可复现的门禁)**:① 新增 `scripts/dataset_harness.py`:走 **C++ `edge-v2` 生产路径**,每张图跑两遍口径(本帧候选 = `require_commit=false` 单帧;发布值 = `require_commit=true` + 同图 20 帧),出 Markdown 表 + JSON 小结;中间产物(配置 / PGM / dump)一律落 `%TEMP%`,因为 Windows 下 `main()` 的 `argv` 是 ANSI、仓库路径含中文会被传坏。② 新增 `docs/evidence/test_2026-11-20/labels.json`:把该报告的 39 张 `web_cc` + 4 张对照集人工判读转成机器可读标签(`boxed_flatbed` / `boxed_gondola` / `empty_gondola` / `empty_flatbed` / `working`),并内置三条安全断言(载车不得判 `3`、空车不得判 `1`/`2`、作业帧不得判车型),违例即 **退出码 1**。③ 全量复现(43 张,`configs/edge-v2-front.json`):**弃权 18 / 误判 9**,与《测试报告》第二节逐格一致;门禁当前 9 条 = `test1`、`NX70_003`、`X70_004/007/008/010`(载车判 3)、`X160_001`、`C70E_001`(空车判 1)、`C64K_001`(空车判 2)。④ 两个口径坑写进脚本:**必须走 C++**(`video2` 这类广角素材在 Python 参考实现上多为 `255 weak_evidence`,用 Python 量会得出"没问题"的错结论);**不要调快 fps**(`decision.min_dwell_s=0.2 s` 要求落位驻留,20 帧若被跑到 83 ms,投票永不发布,表里会全变成"弃权")。**判据本身未改**——几何阈值可分性否定的结论(见下一行 ③)被本次复现再次证实,下一步仍是车型小分类器,本 harness 即其 A/B 量测台 |
 | 2026-11-20 | **P0-Q11 作业帧硬门(吊具高悬/夹箱时绝不判车型)+ 记录一条"做不到"的边界**:① 空车/空平车判据的覆写一律先过 `hoist_flag`:命中即 `state=255 / class_reason=hoist_high`(旧口径"分类仍给 1、只拦 commit"会把 `root_test1` 的"吊具横梁+箱体侧壁"当成空车 3 发给 PLC)。C++/Python 同构,`selftest_edge_v2` 75/0(新增 3 项)、Python `HoistBlocksTypeTests` 3 项。② 顺带补诊断:`BodyEvidence.spcv`(立柱间距变异系数)与 `boxh/bedh`(箱底暗带/边梁亮带高度)进 C++ summary,Python `_measure_body` 返回 `spcv`。③ 量化后**未采纳**:39 张 `web_cc` 广角侧视图上,`posts/span/opacity` 与 `ground` 均无法区分"集装箱侧壁 vs 敞车侧墙"(载车 `body=(3~12,0.64~0.93,0.68~0.85)` vs 空车 `(3~14,0.61~0.96,0.59~0.85)`,完全重叠;`ground` 门实测会误伤 5 项合成单测,已回退),`px_per_m` 全为 0 亦无尺度信号 → 域外机位需车型分类器,暂保持 `allow_state2/3=false`。A/B 回归不变(A 发布 `1×40`、B 发布 `2×40`) |
 | 2026-11-20 | **P0-Q10 空平车也输出 `state=3`(并修掉一个危险误判)**:① 先删掉"严格竖棱门数不够就回退宽松"的兜底——实测 `img01`(NX70A 平车+蓝箱,真值 2)在宽松门下会被聚成 7 根"立柱"→ 越过空车门变成 **3**(载车被判空车);空 C70/C70EA 在严格门下本来就够数(9/5 根),回退无收益。② 新增空平车判据 `evidence_v2.empty_flatbed_*`:`under_deck` + 薄边梁 + **箱底不贴边梁**(`gap_px ≥ 16 px`;载车三样本实测 gap≈0)+ 边梁上方是光滑亮车面(`vcov/hcov ≤ 0.12`,灰度降 ≤80)→ `state=3`、`class_reason=empty_flatbed`。与空敞车互斥(先判侧墙)。③ 实测:合成空平车 → 3(6 帧 commit);`flat_scene` → 2;`ground/thick_contact/stacked` → 不判 3;七张实测图 = `2/3/3/1 + 255/255/1`(img01 由 3 修正为 255);A 发布 `1×43/0×7`、B 发布 `2×18/0×32` 与基线逐帧一致。**空平车真机素材仍缺**,阈值由合成 + 载车 gap≈0 支撑 |
 | 2026-11-20 | **P0-Q9 空车单独输出 `state=3`(取代 P0-Q7 的"空车一律 255")**:把空车逻辑从 255 里摘干净,做成独立判据 `evidence_v2.empty_*`:`texture_top` 以下侧墙 ROI 必须满足 门板立柱∈[3,16] / 跨度≥0.60 / 不透明≥0.55 / 斜撑≥1 / **可见墙高≥0.25 画幅** / **竖棱长度≥0.30×墙高**,命中→`3`(`gap=0`);只"看得见车体结构但不够完整"仍按旧口径 `255 ambiguous_empty_vehicle`。两道安全门:①`empty_wall_below_deck`(平车"薄车面边梁+车面下暗带"出现在候选墙之上 ⇒ 那是车面以下的地面,不判空车);②空车专用竖棱门(0.30 vs 兜底的 0.15,防止平车车面下方的地面碎竖棱被当成门板)。实测:`02_C70E`、`03_C70EA` 两张空车图 **255 → 3**;`01_flatcar`(posts=63)/`04_container_on_gondola`(墙高 13%) 保持 **2 / 1** 不变;`00` 合成地面/堆料仍不判 3。状态码全线放开到 `{0,1,2,3}`(schema/STATE_LABELS/PublishGate/commit/check_contract_v2/replay_check/plc_interface);新增 `allow_state3`(顶层与 `commit` 串联)。Python `test_evidence_v2.EmptyVehicleTests` 5 项 + C++ `selftest_edge_v2` 4 项 |

+ 25 - 0
docs/stability_soak.md

@@ -284,6 +284,31 @@ if (!(cfg->max_fps > 0.0) || cfg->max_fps > 240.0) { return bad("run.max_fps 必
 accept 到已有连接时先拒绝新连接(现在会用新连接把正在服务的连接"挤"在后面);
 ③ 真机验收时用 §6 的清单确认"PLC 扫描周期 + 视觉侧最坏响应"之和仍在预算内。
 
+---
+
+## 8. 2026-11-20 复核(软件侧证据,开发机)
+
+> 这一节是**没有相机 / 没有现场素材**时也能产出的验收证据(对应 `acceptance_report.md`
+> 第 6 项"板端 30 min 浸泡 / fuzz / modbus_torture"里的前两项;**开发机基线不等于板端结论**)。
+
+| 项 | 命令 | 结果 |
+|---|---|---|
+| 配置 / 命令行 fuzz | `python scripts/fuzz_app.py --exe build-cmake/windows-zig-release/portcv_run.exe --config configs/edge-cpp.json --out runs/fuzz_20261120` | **90 用例:PASS 83 / WARN 7 / FAIL 0**(rc=0,报告 `runs/fuzz_20261120/fuzz_20261120_164543.txt`) |
+| Modbus/TCP 折磨 | `python scripts/modbus_torture.py --exe build-cmake/windows-zig-release/portcv_run.exe --config configs/edge-cpp.json --out runs/torture_20261120` | **34 用例:PASS 34 / WARN 0 / FAIL 0**(rc=0;句柄 63→63、线程 4→4、RSS 5.04→5.13 MB) |
+
+7 条 WARN **全是 §3 已记录的老问题**,没有新增缺口:
+
+| WARN | 归属 |
+|---|---|
+| `type_plc_null` / `type_run_array` / `type_min_votes_null` / `unknown_top_key` / `unknown_nested_key` | §3.1 段落级类型错 / 未知键**静默忽略**(与"写错会报错退出"的文档承诺不符,P1 待办) |
+| `many_keys_200k`(解析 24.3 s) | §3.7 配置文件无大小 / 键数上限(P3) |
+| `host_long_1mb` | Windows 一次命令行长度上限(环境限制,不是程序行为) |
+
+**结论**:判据链与 Modbus 服务端在这台开发机上的**崩溃 / 挂死 / 资源泄漏**类问题仍为 0;
+`FAIL 0` 是可作为上线前门禁的基线。未做(本机与时长限制):30 min 资源曲线、168 h 长跑、
+板端(RK3576)实测 —— 这三项仍按 §6 / `docs/soak_7x24.md` 上板执行。
+
+
 ### 3.5 【低】50 个并发客户端时约 2% 连接被拒(10061)
 
 1000 次读里 978 次成功;失败样例是 `[WinError 10061] 由于目标计算机积极拒绝`

+ 633 - 0
scripts/dataset_harness.py

@@ -0,0 +1,633 @@
+"""数据集回归 harness(**C++ 生产路径**):把一个图片/视频测试集跑成“本帧候选 / 发布值”表 + 安全断言。
+
+为什么要这个脚本
+----------------
+`docs/evidence/test_2026-11-20/测试报告.md` 那几张表是用一套**临时 harness**(`%TEMP%` 里的
+PGM chunk + 逐个 `portcv_run`)跑出来的,harness 本身没进仓 —— 于是“报告里的数字”无法复现,
+任何判据改动都没有门禁。这里把它固化成脚本,并且**必须走 C++ `edge-v2`**:
+
+* Python 参考实现(`portcv/logic/evidence_v2.py`)在广角/远景素材上与 C++ 结论不同
+  (实拍 `video2`:Python 抽样帧多为 `255 weak_evidence`,C++ 是 `2 deck_edge`),
+  用 Python 量会得出错误结论;
+* 现场跑的是 C++,验收看的也是 C++ 发给 PLC 的 `state`。
+
+两遍口径(与测试报告一致)
+--------------------------
+* **本帧候选**:`evidence_v2.require_commit=false` + 单帧 → `edge_state`
+  (算法本身把这一帧判成什么,用来评估结构可分性);
+* **发布值**:`evidence_v2.require_commit=true` + 同一张图重复 `--repeats` 帧(默认 20)
+  → 寄存器口径 `state`(含 commit / 投票 / 发布门,PLC 实际采信的就是它)。
+
+安全断言(`--labels` 给了人工判读才生效;违反 → 退出码 1)
+--------------------------------------------------------
+* `boxed`(平车坐箱 / 敞车坐箱):发布值**不得**为 `3`(载车被判空车 = 最危险的误判);
+* `empty`(空敞车 / 空平车):发布值**不得**为 `2` / `1`(空车被判成载车);
+* `working`(吊具高悬 / 夹箱的作业帧):发布值必须是 `0`(不判)。
+
+数据域(`labels.json` 的 `domain`;`--domain field,near,web` 可过滤)
+-------------------------------------------------------------------
+* `field`:现场实拍(部署机位 / 司机视角)——**只有这一域的命中率能当现场精度**;
+* `near`:近距前视素材,非现场工况片段,仅作回归参照;
+* `web`:网上图库(广角 / 远景),与部署机位的拍摄角度、距离都不同 ——
+  它的数字只能回答"会不会出现危险误报",**不能**当召回率/准确率;
+* 报告按域分开统计;一批里没有 `field` 样本时,脚本会打醒目警告。
+
+
+用法
+----
+::
+
+    # 39 张 web_cc + 4 张对照集(人工判读见 labels.json)
+    python scripts/dataset_harness.py --images <图片目录...> \
+        --labels docs/evidence/test_2026-11-20/labels.json --out runs/harness
+
+    # 只跑发布值(快一半)
+    python scripts/dataset_harness.py --images <目录> --no-single
+
+    # 换配置(真机模板 / view=high)
+    python scripts/dataset_harness.py --images <目录> --config configs/edge-v2-rtsp.json
+
+视频请先用 ``scripts/extract_frames.py`` 抽成 PGM 目录(本脚本只吃图片,避免把解码差异
+混进判据口径)。
+
+为什么所有中间产物都落在系统临时目录:C++ `main()` 的 `argv` 在 Windows 上是 ANSI 编码,
+仓库路径含中文(`…\\正面吊\\…`)会被传坏。脚本把配置/PGM/dump 全部写到**纯 ASCII** 的
+`%TEMP%/portcv_harness`,只把结论写回 `--out`(Python 侧自己写文件,无编码问题)。
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+STATE_LABEL = {0: "0 不在车上", 1: "1 敞车", 2: "2 平车", 3: "3 空车", 255: "255 弃权"}
+
+#: 数据域:**现场**实拍 / 近距前视素材(非现场工况) / 网上图库(广角、远景)
+#:
+#: 为什么必须分开统计:`web_cc` 那 39 张是网上找的图库照片,拍摄角度与距离
+#: 和部署机位(相机固定在车身左前方、近距、箱底与车面在画面中部)不是一回事 ——
+#: 它们的数字只能回答"会不会把载车判成空车"这类**安全方向**问题,**不能**当
+#: 现场精度(召回/准确率)。没有 `field` 样本时,报告里的命中率一律不作数。
+DOMAINS = ("field", "near", "web", "unknown")
+
+#: 人工判读标签 → 期望状态(`expect` 在 labels.json 里可逐条覆盖)
+LABEL_EXPECT = {
+    "boxed_flatbed": 2,
+    "boxed_gondola": 1,
+    "empty_gondola": 3,
+    "empty_flatbed": 3,
+    "working": 0,
+}
+
+IMAGE_EXT = (".jpg", ".jpeg", ".png", ".bmp", ".pgm")
+
+#: 断言:标签 → 发布值禁集(None = 无禁集)
+GATE_FORBID = {
+    "boxed_flatbed": {3},
+    "boxed_gondola": {3},
+    "empty_gondola": {1, 2},
+    "empty_flatbed": {1, 2},
+    "working": {1, 2, 3},
+}
+
+
+def find_exe(explicit: str = "") -> str:
+    """找 `portcv_run`:显式参数 > 环境变量 > 本仓构建产物 > PATH。"""
+
+    if explicit:
+        return explicit
+    env = os.environ.get("PORTCV_RUN", "")
+    if env:
+        return env
+    for rel in (
+        os.path.join("build-cmake", "windows-zig-release", "portcv_run.exe"),
+        os.path.join("build-cmake", "windows-zig-release", "portcv_run"),
+        os.path.join("build", "portcv_run"),
+        os.path.join("build", "portcv_run.exe"),
+    ):
+        path = os.path.join(ROOT, rel)
+        if os.path.exists(path):
+            return path
+    found = shutil.which("portcv_run")
+    if found:
+        return found
+    raise SystemExit(
+        "找不到 portcv_run:用 --exe 指定,或先构建(docs/deployment.md §2)。"
+    )
+
+
+def collect_images(dirs: list[str]) -> list[str]:
+    """递归收集图片;按路径排序(同一目录内即文件名序)。"""
+
+    out: list[str] = []
+    for base in dirs:
+        if os.path.isfile(base):
+            out.append(base)
+            continue
+        for cur, _sub, files in os.walk(base):
+            for name in sorted(files):
+                if name.lower().endswith(IMAGE_EXT):
+                    out.append(os.path.join(cur, name))
+    return sorted(out)
+
+
+def image_to_pgm(src: str, dst: str) -> tuple[int, int]:
+    """图片 → PGM(**灰度解码**,与取流口径一致:`IMREAD_GRAYSCALE`)。
+
+    路径可能含中文(仓库在 `…\\正面吊\\…`),OpenCV 的 `imread` 在 Windows 上按 ANSI
+    打开文件会失败 —— 所以统一 `np.fromfile` + `imdecode`(与 `portcv/io/capture.py`
+    同一手法,`docs/route_v2.md` §7.1 记录的「JPEG 经 BGR→gray 差 ±1 灰阶」也在这里避开)。
+    """
+
+    import cv2  # 局部导入:只跑网关/查表时不需要 cv2
+    import numpy as np
+
+    with open(src, "rb") as handle:
+        buf = np.frombuffer(handle.read(), dtype=np.uint8)
+    gray = cv2.imdecode(buf, cv2.IMREAD_GRAYSCALE)
+    if gray is None:
+        raise RuntimeError("解不开这张图(损坏或格式不支持):%s" % src)
+    height, width = gray.shape[:2]
+    with open(dst, "wb") as handle:
+        handle.write(b"P5\n")
+        handle.write(("%d %d\n" % (width, height)).encode("ascii"))
+        handle.write(b"255\n")
+        handle.write(np.ascontiguousarray(gray).tobytes())
+    return width, height
+
+
+def prepare_configs(base_config: str, work: str, chunk: str, repeats: int,
+                    fps: float) -> tuple[str, str]:
+    """把模板配置改写成两份(single / stable),全部指向 ASCII 临时目录。
+
+    * `source.type=images` + `source.uri=<chunk>`:离线回放,零依赖;
+    * `run.max_fps`:默认沿用模板(15 fps)。**不要调太快**:`decision.min_dwell_s`(0.2 s)
+      要求落位驻留,20 帧同图若跑成 83 ms,投票永远不会发布(本 harness 早期就踩过这个坑);
+    * `evidence_v2.require_commit`:single=false(看算法本身怎么判)/ stable=true(看发布值);
+    * `run.output_dir` / `calibration.record` 指到临时目录:仓储路径含中文,C++ 侧打不开。
+    """
+
+    with open(base_config, encoding="utf-8-sig") as handle:
+        cfg = json.load(handle)
+
+    cfg.setdefault("run", {})["max_fps"] = float(fps) if fps > 0.0 else float(
+        cfg.get("run", {}).get("max_fps", 15.0))
+    cfg["run"]["output_dir"] = os.path.join(work, "output")
+    cfg["run"]["preview"] = False
+    cfg["run"]["save_on_change"] = False
+    cfg.setdefault("source", {})["type"] = "images"
+    cfg["source"]["uri"] = chunk
+    cfg["source"]["loop"] = False
+    cfg.pop("_note", None)
+    calib = cfg.setdefault("calibration", {})
+    calib["record"] = ""
+    calib["stale"] = False
+
+    paths = []
+    for name, require_commit in (("single", False), ("stable", True)):
+        one = json.loads(json.dumps(cfg))
+        one.setdefault("evidence_v2", {})["require_commit"] = bool(require_commit)
+        path = os.path.join(work, "cfg_%s.json" % name)
+        with open(path, "w", encoding="utf-8") as handle:
+            json.dump(one, handle, ensure_ascii=False, indent=2)
+            handle.write("\n")
+        paths.append(path)
+    return paths[0], paths[1]
+
+
+def read_dump(path: str) -> list[dict]:
+    rows: list[dict] = []
+    if not os.path.exists(path):
+        return rows
+    with open(path, encoding="utf-8-sig") as handle:
+        for line in handle:
+            line = line.strip()
+            if line:
+                rows.append(json.loads(line))
+    return rows
+
+
+def run_once(exe: str, config: str, chunk: str, frames: int, dump: str,
+             timeout: float) -> tuple[int, str, list[dict]]:
+    """跑一次 `portcv_run`(images 源),返回 (退出码, 日志尾部, dump 行)。"""
+
+    if os.path.exists(dump):
+        os.remove(dump)
+    cmd = [exe, "-c", config, "--source-type", "images", "--source-uri", chunk,
+           "--max-frames", str(frames), "--dump-frames", dump,
+           "--dump-dir", os.path.join(os.path.dirname(dump), "pgm"), "--no-plc"]
+    try:
+        proc = subprocess.run(cmd, cwd=ROOT, timeout=timeout,
+                              stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+        log = proc.stdout.decode("utf-8", "replace")
+        code = proc.returncode
+    except subprocess.TimeoutExpired as exc:
+        log = (exc.stdout or b"").decode("utf-8", "replace") if exc.stdout else ""
+        return 124, log[-400:], read_dump(dump)
+    return code, log[-400:], read_dump(dump)
+
+
+def short_reason(row: dict) -> str:
+    """从 dump 行里抠出“判据一句话”(v2 的 reason 就是现场可读诊断)。"""
+
+    reason = str(row.get("reason") or "").strip()
+    text = reason or str(row.get("summary") or "").strip()
+    text = re.sub(r"^v2:(ok|abstain)\s*", "", text)
+    return text.replace(" ", " ")
+
+
+def load_labels(path: str) -> dict[str, dict]:
+    """读人工判读表:``{"NX70_001.jpg": {"label": "empty_flatbed", "expect": 3}}``。"""
+
+    if not path:
+        return {}
+    with open(path, encoding="utf-8-sig") as handle:
+        raw = json.load(handle)
+    out: dict[str, dict] = {}
+    for name, item in raw.items():
+        if name.startswith("_"):
+            continue  # `_note` / `_source` 这类说明键
+        if isinstance(item, str):
+            item = {"label": item}
+        entry = dict(item)
+        label = str(entry.get("label", "")).strip()
+        if label not in LABEL_EXPECT:
+            raise SystemExit("labels.json 里 %s 的 label 不认识:%r(可选:%s)"
+                             % (name, label, ", ".join(sorted(LABEL_EXPECT))))
+        entry["label"] = label
+        domain = str(entry.get("domain", "unknown")).strip().lower() or "unknown"
+        if domain not in DOMAINS:
+            raise SystemExit("labels.json 里 %s 的 domain 不认识:%r(可选:%s)"
+                             % (name, domain, ", ".join(DOMAINS)))
+        entry["domain"] = domain
+        if "expect" not in entry:
+            entry["expect"] = LABEL_EXPECT[label]
+        out[os.path.basename(name)] = entry
+    return out
+
+
+def parse_args(argv=None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description="数据集回归 harness(C++ edge-v2):本帧候选 / 发布值 + 安全断言")
+    parser.add_argument("--images", nargs="+", required=True,
+                        help="图片目录(递归)或图片文件")
+    parser.add_argument("--config", default=os.path.join("configs", "edge-v2-front.json"),
+                        help="配置模板(相对仓库根或绝对路径)")
+    parser.add_argument("--labels", default="",
+                        help="人工判读 JSON(见 docs/evidence/test_2026-11-20/labels.json)")
+    parser.add_argument("--domain", default="",
+                        help="只跑指定数据域(逗号分隔:field,near,web;空 = 全部)。"
+                             "**没有 field 样本时,命中率不得当现场精度**")
+    parser.add_argument("--exe", default="", help="portcv_run 路径(缺省自动找)")
+    parser.add_argument("--out", default=os.path.join("runs", "harness"),
+                        help="结论输出目录(默认 runs/harness,已 gitignore)")
+    parser.add_argument("--repeats", type=int, default=20,
+                        help="发布值口径:同一张图重复多少帧(现场 harness 约定 20)")
+    parser.add_argument("--fps", type=float, default=0.0,
+                        help="覆盖 run.max_fps(默认 0 = 沿用模板;"
+                             "注意别调太快:decision.min_dwell_s 要求落位驻留,"
+                             "20 帧必须跨够 0.2 s 才会发布)")
+    parser.add_argument("--timeout", type=float, default=300.0, help="单次 portcv_run 超时(秒)")
+    parser.add_argument("--limit", type=int, default=0, help="只跑前 N 张(0 = 全部)")
+    parser.add_argument("--no-single", action="store_true", help="跳过“本帧候选”这一遍(快一半)")
+    parser.add_argument("--no-gate", action="store_true", help="断言失败也返回 0(只出表)")
+    parser.add_argument("--baseline-violations", default="",
+                        help="已知违例基线 JSON:只卡“**不许新增**违例”(改判据的日常门禁);"
+                             "不给则任何违例都返回 1(发版/验收口径)")
+    parser.add_argument("--keep-work", action="store_true", help="保留临时工作目录")
+    return parser.parse_args(argv)
+
+
+def verdict(publish: int, expect: int) -> str:
+    """发布值 vs 人工真值:命中 / 弃权(发 0 = 不判)/ 误判。"""
+
+    if publish == expect:
+        return "命中"
+    if publish == 0:
+        return "弃权"
+    return "误判"
+
+
+def main(argv=None) -> int:
+    args = parse_args(argv)
+
+    exe = find_exe(args.exe)
+    config = args.config if os.path.isabs(args.config) else os.path.join(ROOT, args.config)
+    if not os.path.exists(config):
+        print("找不到配置模板: %s" % config, file=sys.stderr)
+        return 2
+    if args.repeats < 1:
+        print("--repeats 至少 1", file=sys.stderr)
+        return 2
+
+    images = collect_images(args.images)
+    if not images:
+        print("没有找到图片:%s" % " ".join(args.images), file=sys.stderr)
+        return 2
+    if args.limit > 0:
+        images = images[:args.limit]
+    labels = load_labels(args.labels)
+    if args.domain:
+        wanted = {item.strip().lower() for item in args.domain.split(",") if item.strip()}
+        bad = wanted - set(DOMAINS)
+        if bad:
+            print("--domain 里有不认识的值:%s(可选:%s)"
+                  % (sorted(bad), ", ".join(DOMAINS)), file=sys.stderr)
+            return 2
+        total = len(images)
+        images = [path for path in images
+                  if labels.get(os.path.basename(path), {}).get("domain", "unknown") in wanted]
+        print("域过滤    : %s → %d/%d 张" % ("+".join(sorted(wanted)), len(images), total))
+        if not images:
+            print("该数据域下没有样本", file=sys.stderr)
+            return 2
+
+    work = os.path.join(tempfile.gettempdir(), "portcv_harness")
+    chunk = os.path.join(work, "chunk")
+    if os.path.isdir(work):
+        shutil.rmtree(work, ignore_errors=True)
+    os.makedirs(chunk, exist_ok=True)
+    cfg_single, cfg_stable = prepare_configs(config, work, chunk, args.repeats, args.fps)
+    out_dir = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
+    os.makedirs(out_dir, exist_ok=True)
+
+    print("可执行    : %s" % exe)
+    print("配置模板  : %s" % os.path.relpath(config, ROOT))
+    print("图片      : %d 张(人工判读 %d 条)" % (len(images), len(labels)))
+    print("口径      : 本帧候选 = require_commit=false 单帧 / 发布值 = require_commit=true"
+          " + 同图 %d 帧" % args.repeats)
+    print("")
+
+    rows: list[dict] = []
+    started = time.time()
+    for index, src in enumerate(images, 1):
+        name = os.path.basename(src)
+        label = labels.get(name, {})
+        for old in os.listdir(chunk):
+            os.remove(os.path.join(chunk, old))
+        try:
+            width, height = image_to_pgm(src, os.path.join(chunk, "frame_000000.pgm"))
+        except RuntimeError as exc:
+            print("[%d/%d] %s 跳过:%s" % (index, len(images), name, exc), file=sys.stderr)
+            continue
+        for copy in range(1, args.repeats):
+            shutil.copyfile(os.path.join(chunk, "frame_000000.pgm"),
+                            os.path.join(chunk, "frame_%06d.pgm" % copy))
+        row: dict = {
+            "index": index,
+            "file": name,
+            "size": [width, height],
+            "domain": label.get("domain", "unknown"),
+            "label": label.get("label", ""),
+            "expect": label.get("expect"),
+            "note": label.get("note", ""),
+        }
+        if not args.no_single:
+            code, log, dump = run_once(
+                exe, cfg_single, chunk, 1,
+                os.path.join(work, "dump_single.jsonl"), args.timeout)
+            if code != 0 or not dump:
+                row["candidate"] = None
+                row["candidate_reason"] = ""
+                row["candidate_error"] = "rc=%d %s" % (code, log.strip()[-120:])
+            else:
+                row["candidate"] = int(dump[-1].get("edge_state", -1))
+                row["candidate_reason"] = short_reason(dump[-1])
+        code, log, dump = run_once(
+            exe, cfg_stable, chunk, args.repeats,
+            os.path.join(work, "dump_stable.jsonl"), args.timeout)
+        if code != 0 or not dump:
+            row["publish"] = None
+            row["publish_reason"] = ""
+            row["publish_error"] = "rc=%d %s" % (code, log.strip()[-120:])
+        else:
+            last = dump[-1]
+            row["publish"] = int(last.get("state", -1))
+            row["publish_edge"] = int(last.get("edge_state", -1))
+            row["publish_reason"] = short_reason(last)
+            row["stable_flag"] = bool(int(last.get("flags", 0)) & 0x0001)
+            row["frames"] = len(dump)
+        if row.get("expect") is not None and row.get("publish") is not None:
+            row["verdict"] = verdict(int(row["publish"]), int(row["expect"]))
+        rows.append(row)
+        print("[%d/%d] %-20s 人工=%-11s 候选=%-9s 发布=%-9s %s"
+              % (index, len(images), name,
+                 row.get("label") or "-",
+                 "-" if row.get("candidate") is None
+                 else STATE_LABEL.get(int(row["candidate"]), str(row["candidate"])),
+                 "-" if row.get("publish") is None
+                 else STATE_LABEL.get(int(row["publish"]), str(row["publish"])),
+                 row.get("verdict", "")), file=sys.stderr)
+
+    elapsed = time.time() - started
+    report = render_report(rows, exe, config, args)
+    md_path = os.path.join(out_dir, "dataset_harness.md")
+    json_path = os.path.join(out_dir, "dataset_harness.json")
+    with open(md_path, "w", encoding="utf-8") as handle:
+        handle.write(report["markdown"])
+    with open(json_path, "w", encoding="utf-8") as handle:
+        json.dump(report["summary"], handle, ensure_ascii=False, indent=2)
+        handle.write("\n")
+
+    print("")
+    print(report["markdown"])
+    print("耗时      : %.1f s / %d 张(%.2f s 每张)"
+          % (elapsed, len(rows), elapsed / max(1, len(rows))))
+    print("结论      : %s" % md_path)
+    print("小结 JSON : %s" % json_path)
+
+    if not args.keep_work:
+        shutil.rmtree(work, ignore_errors=True)
+    if args.baseline_violations and report["fixed_violations"]:
+        print("提示:%d 条违例已修复(%s)—— 请把它们从基线里删掉"
+              % (len(report["fixed_violations"]), "、".join(report["fixed_violations"])))
+    gate_items = report["new_violations"] if args.baseline_violations else report["violations"]
+    if gate_items and not args.no_gate:
+        print("", file=sys.stderr)
+        print("安全断言失败 %d 条%s:" % (
+            len(gate_items), "(基线对比口径:只卡新增)" if args.baseline_violations else ""),
+            file=sys.stderr)
+        for item in gate_items:
+            print("  - %s" % item, file=sys.stderr)
+        return 1
+    return 0
+
+
+def load_baseline(path: str) -> set[str]:
+    """读「已知违例基线」:``{"violations": ["test1.png:3", ...]}``(键 = 文件名:发布值)。
+
+    语义是**禁止变差**:基线里的违例允许存在(它们已被记录、有整改项),
+    **新增**一条就 FAIL;某条被修好了会提示更新基线(不算失败)。
+    """
+
+    if not path:
+        return set()
+    with open(path, encoding="utf-8-sig") as handle:
+        data = json.load(handle)
+    items = data.get("violations", data if isinstance(data, list) else [])
+    return {str(item).strip() for item in items if str(item).strip()}
+
+
+def render_report(rows: list[dict], exe: str, config: str,
+                  args: argparse.Namespace) -> dict:
+    """出 Markdown 表 + 小结 JSON + 断言清单。"""
+
+    lines: list[str] = []
+    lines.append("# 数据集回归 harness(C++ `edge-v2`)")
+    lines.append("")
+    lines.append("- 可执行:`%s`" % os.path.basename(exe))
+    lines.append("- 配置模板:`%s`" % os.path.relpath(config, ROOT))
+    lines.append("- 口径:本帧候选 = `require_commit=false` 单帧;发布值 = `require_commit=true`"
+                 " + 同图 %d 帧" % args.repeats)
+    lines.append("- 状态码:`0` 不在车上/其他;`1` 敞车;`2` 平车;`3` 空车;`255` 内部弃权")
+    domains = sorted({row.get("domain", "unknown") for row in rows})
+    lines.append("- 数据域:%s(`field` 现场实拍 / `near` 近距前视素材 / `web` 网上图库"
+                 "——**只有 `field` 的命中率能当现场精度**)" % "/".join(domains))
+    lines.append("")
+    lines.append("| # | 文件 | 域 | 人工判读 | 期望 | 本帧候选 | 发布值 | 结论 | 判据 |")
+    lines.append("|---|---|---|---|---|---|---|---|---|")
+    for row in rows:
+        candidate = row.get("candidate")
+        publish = row.get("publish")
+        lines.append("| %d | `%s` | %s | %s | %s | %s | %s | %s | %s |" % (
+            row["index"], row["file"], row.get("domain", "unknown"),
+            row.get("label") or "-",
+            "-" if row.get("expect") is None else row["expect"],
+            "-" if candidate is None else candidate,
+            "-" if publish is None else STATE_LABEL.get(publish, publish),
+            row.get("verdict", "-"), (row.get("publish_reason") or "-"),
+        ))
+    lines.append("")
+
+    by_label: dict[str, dict[str, int]] = {}
+    for row in rows:
+        label = row.get("label") or "unlabeled"
+        bucket = by_label.setdefault(
+            label, {"total": 0, "命中": 0, "弃权": 0, "误判": 0, "未判定": 0})
+        bucket["total"] += 1
+        bucket[row.get("verdict", "未判定")] += 1
+
+    lines.append("| 人工判读 | 张数 | 命中 | 弃权 | 误判 |")
+    lines.append("|---|---|---|---|---|")
+    for label in sorted(by_label):
+        bucket = by_label[label]
+        lines.append("| %s | %d | %d | %d | %d |" % (
+            label, bucket["total"], bucket["命中"], bucket["弃权"], bucket["误判"]))
+    if by_label:
+        lines.append("| **合计** | **%d** | **%d** | **%d** | **%d** |" % (
+            sum(b["total"] for b in by_label.values()),
+            sum(b["命中"] for b in by_label.values()),
+            sum(b["弃权"] for b in by_label.values()),
+            sum(b["误判"] for b in by_label.values())))
+    lines.append("")
+
+    by_domain: dict[str, dict[str, int]] = {}
+    for row in rows:
+        domain = row.get("domain", "unknown")
+        bucket = by_domain.setdefault(
+            domain, {"total": 0, "命中": 0, "弃权": 0, "误判": 0, "未判定": 0})
+        bucket["total"] += 1
+        bucket[row.get("verdict", "未判定")] += 1
+
+    lines.append("| 数据域 | 张数 | 命中 | 弃权 | 误判 | 读法 |")
+    lines.append("|---|---|---|---|---|---|")
+    reading = {
+        "field": "**唯一可作现场精度**(张数太少时仍不足以下结论)",
+        "near": "近距前视,仅作回归参照",
+        "web": "网上图库(广角/远景),**只看安全方向,不当精度**",
+        "unknown": "未标域,不作数",
+    }
+    for domain in sorted(by_domain):
+        bucket = by_domain[domain]
+        lines.append("| %s | %d | %d | %d | %d | %s |" % (
+            domain, bucket["total"], bucket["命中"], bucket["弃权"], bucket["误判"],
+            reading.get(domain, "—")))
+    lines.append("")
+    if not by_domain.get("field", {}).get("total"):
+        lines.append("> ⚠ **本批没有 `field`(现场实拍)样本**:命中/召回率**不得**作为现场精度引用;"
+                     "这批数据只能用于「会不会把载车判成空车」这类安全方向的回归。")
+        lines.append("")
+
+    violations: list[str] = []
+    keys: list[str] = []
+    for row in rows:
+        label = row.get("label") or ""
+        publish = row.get("publish")
+        if publish is None:
+            continue
+        forbid = GATE_FORBID.get(label)
+        if forbid and publish in forbid:
+            keys.append("%s:%d" % (row["file"], int(publish)))
+            violations.append(
+                "`%s`(%s)发布 %s,禁止出现 %s —— %s"
+                % (row["file"], label, STATE_LABEL.get(publish, publish),
+                   "/".join(str(v) for v in sorted(forbid)),
+                   row.get("publish_reason") or "-"))
+
+    baseline_path = str(getattr(args, "baseline_violations", "") or "")
+    new_violations: list[str] = []
+    fixed_violations: list[str] = []
+    if baseline_path:
+        baseline = load_baseline(baseline_path)
+        current = set(keys)
+        new_violations = sorted(current - baseline)
+        fixed_violations = sorted(baseline - current)
+        lines.append("## 安全断言(与基线对比:禁止变差)")
+        lines.append("")
+        lines.append("| 项 | 数量 |")
+        lines.append("|---|---|")
+        lines.append("| 基线(%s) | %d |" % (os.path.basename(baseline_path), len(baseline)))
+        lines.append("| 本次 | %d |" % len(current))
+        lines.append("| **新增(门禁)** | **%d** |" % len(new_violations))
+        lines.append("| 已修复(请同步基线) | %d |" % len(fixed_violations))
+        lines.append("")
+        if new_violations:
+            lines.append("**新增违例(必须修掉或写进基线并说明理由)**")
+            lines.append("")
+            for key in new_violations:
+                lines.append("* `%s`" % key)
+            lines.append("")
+        if fixed_violations:
+            lines.append("**已修复(把这几条从基线里删掉)**:" +
+                         "、".join("`%s`" % key for key in fixed_violations))
+            lines.append("")
+    if violations:
+        lines.append("## 安全断言失败明细(%d)" % len(violations))
+        lines.append("")
+        for item in violations:
+            lines.append("* %s" % item)
+    else:
+        lines.append("## 安全断言")
+        lines.append("")
+        lines.append("全部通过:载车未判 `3`、空车未判 `1/2`、作业帧未判车型。")
+    lines.append("")
+
+    summary = {
+        "config": os.path.relpath(config, ROOT),
+        "exe": os.path.basename(exe),
+        "repeats": args.repeats,
+        "samples": len(rows),
+        "by_label": by_label,
+        "by_domain": by_domain,
+        "violations": violations,
+        "violation_keys": sorted(keys),
+        "baseline": os.path.basename(baseline_path) if baseline_path else "",
+        "new_violations": new_violations,
+        "fixed_violations": fixed_violations,
+        "rows": rows,
+    }
+    return {"markdown": "\n".join(lines), "summary": summary, "violations": violations,
+            "new_violations": new_violations, "fixed_violations": fixed_violations}
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 90 - 8
scripts/regression_freeze.py

@@ -1,14 +1,19 @@
 """一套命令跑完"冻结点"回归(发版 / 交付 / 改判据之后必跑)。
 
-为什么要一个总脚本:判据链现在有四层(C++ 契约自检 8 个、Python 330 单测、
-v1 `edge` 现场回放 4 份、v2 `edge-v2` 现场回放 2 份),分散在四五个命令里,
-现场/验收时**很容易漏跑一组**,而漏跑的那一组往往正是"刚刚被改动"的那一组。
+为什么要一个总脚本:判据链现在有五层(C++ 契约自检、Python 单测、v1 `edge` 现场回放、
+v2 `edge-v2` 现场回放、**数据集安全门禁**),分散在四五个命令里,现场/验收时**很容易漏跑
+一组**,而漏跑的那一组往往正是"刚刚被改动"的那一组。
 
 用法::
 
     # 全部跑(默认路径就是本仓库的布局)
     python scripts/regression_freeze.py
 
+    # 数据集门禁要指语料目录(没有现场素材时它会明确 FAIL/SKIP,而不是静默跳过)
+    python scripts/regression_freeze.py --dataset-dir "D:/语料/dataset_20251120"
+    # 也可以走环境变量
+    set PORTCV_DATASET_DIR=D:/语料/dataset_20251120
+
     # 产物不在默认位置 / 只想跑其中几组(调试用;正式验收请跑全量)
     python scripts/regression_freeze.py --build-dir build --only ctest,py
 
@@ -19,7 +24,10 @@ v1 `edge` 现场回放 4 份、v2 `edge-v2` 现场回放 2 份),分散在四
   (见 `docs/edge_evidence.md` §7.1 ⑤-2),白名单里写清"允许 1 条且必须匹配该模式",
   多一条、或换了原因,都算 FAIL —— 绝不因为"有一条已知失败"就把整组标记成跳过;
 * **缺产物不静默跳过**:直接给出**生成命令**并记 FAIL;只有显式 `--allow-missing`
-  才降级为 SKIP(报告里照样逐条列出),用于"没有现场素材的纯算法机"。
+  才降级为 SKIP(报告里照样逐条列出),用于"没有现场素材的纯算法机";
+* **数据集门禁只卡“变差”**:`--baseline-violations` 允许基线里已有的违例存在
+  (它们已记录在 `docs/evidence/test_2026-11-20/`),**新增一条就 FAIL**;
+  修好一条会提示同步基线 —— 既不因为"有 9 条历史违例"就永远红,也不许悄悄变差。
 
 退出码:``0`` 全绿;``1`` 有 FAIL;``2`` 用法 / 环境问题。
 """
@@ -27,6 +35,7 @@ v1 `edge` 现场回放 4 份、v2 `edge-v2` 现场回放 2 份),分散在四
 from __future__ import annotations
 
 import argparse
+import json
 import os
 import re
 import subprocess
@@ -125,23 +134,89 @@ def check_replay(jsonl: str, images: str, allow_missing: bool) -> tuple:
     return True, note
 
 
+def check_dataset_gate(dataset_dir: str, repeats: int, allow_missing: bool) -> tuple:
+    """数据集回归门禁:跑 `dataset_harness.py`,**只卡“新增违例”**(基线见 labels 同目录)。
+
+    为什么放进冻结点回归:2026-11-20 的 9 条危险误判(载车判 3 / 空车判 1、2)原先只写在
+    报告里,改判据时没有任何东西会拦住“变差”。这里用 `--baseline-violations` 把“禁止变差”
+    变成一条可执行的门禁;域内精度仍要等现场素材(`docs/field_capture_spec.md`)。
+    """
+
+    dpath = dataset_dir if os.path.isabs(dataset_dir) else os.path.join(REPO, dataset_dir)
+    if not os.path.isdir(dpath):
+        if allow_missing:
+            return True, "SKIP(--allow-missing):缺语料目录 %s" % dataset_dir
+        return False, ("缺语料目录 %s\n  采集规范:docs/field_capture_spec.md §4;"
+                       "或用 --dataset-dir / 环境变量 PORTCV_DATASET_DIR 指定" % dataset_dir)
+    labels = os.path.join("docs", "evidence", "test_2026-11-20", "labels.json")
+    baseline = os.path.join("docs", "evidence", "test_2026-11-20", "baseline_violations.json")
+    for name in (labels, baseline):
+        if not os.path.exists(os.path.join(REPO, name)):
+            return False, "缺判读/基线文件 %s" % name
+    out_json = os.path.join("runs", "harness_gate", "dataset_harness.json")
+    code, out = run([sys.executable, os.path.join("scripts", "dataset_harness.py"),
+                     "--images", _rel(dpath), "--labels", labels,
+                     "--baseline-violations", baseline,
+                     "--repeats", str(repeats), "--no-single",
+                     "--out", os.path.join("runs", "harness_gate")])
+    if code not in (0, 1):
+        return False, "harness 跑不起来(rc=%d)\n%s" % (code, out[-1500:])
+    summary = {}
+    path = os.path.join(REPO, out_json)
+    if os.path.exists(path):
+        try:
+            with open(path, encoding="utf-8-sig") as fh:
+                summary = json.load(fh)
+        except (OSError, ValueError):
+            summary = {}
+    new = summary.get("new_violations") or []
+    fixed = summary.get("fixed_violations") or []
+    by_domain = summary.get("by_domain") or {}
+    total_v = len(summary.get("violations") or [])
+    note = ("%d 张;当前违例 %d 条(基线 %d)/ 新增 %d / 已修复 %d;域:%s"
+            % (summary.get("samples", -1), total_v,
+               len(load_baseline_keys(baseline)), len(new), len(fixed),
+               ", ".join("%s %d 张" % (d, b.get("total", 0))
+                         for d, b in sorted(by_domain.items())) or "-"))
+    if code == 1 or new:
+        return False, note + "\n  新增违例:" + "、".join(new)
+    return True, note
+
+
+def load_baseline_keys(baseline_rel: str) -> list:
+    path = os.path.join(REPO, baseline_rel)
+    try:
+        with open(path, encoding="utf-8-sig") as fh:
+            data = json.load(fh)
+    except (OSError, ValueError):
+        return []
+    items = data.get("violations", data if isinstance(data, list) else [])
+    return [str(item) for item in items]
+
+
 def main(argv: list | None = None) -> int:
     _use_utf8_stdout()
     parser = argparse.ArgumentParser(description="冻结点回归:ctest + unittest + v1/v2 现场回放")
     parser.add_argument("--build-dir", default=os.path.join("build-cmake", "windows-zig-release"),
                         help="CMake 构建目录(ctest 用)")
     parser.add_argument("--tests-dir", default="tests", help="unittest discover 目录")
-    parser.add_argument("--only", default="ctest,py,v1,v2",
-                        help="只跑其中几组:ctest,py,v1,v2(默认全跑)")
+    parser.add_argument("--only", default="ctest,py,v1,v2,gate",
+                        help="只跑其中几组:ctest,py,v1,v2,gate(默认全跑)")
     parser.add_argument("--allow-missing", action="store_true",
                         help="缺现场素材时把该组降级为 SKIP(纯算法机用;正式验收不要带)")
+    parser.add_argument("--dataset-dir",
+                        default=os.environ.get("PORTCV_DATASET_DIR", ""),
+                        help="数据集回归语料目录(缺省取环境变量 PORTCV_DATASET_DIR;"
+                             "采集规范见 docs/field_capture_spec.md)")
+    parser.add_argument("--gate-repeats", type=int, default=20,
+                        help="数据集门禁里“同图重复帧数”(默认 20,与测试报告同口径)")
     parser.add_argument("--report", default=None, help="把汇总另存一份(UTF-8)")
     args = parser.parse_args(argv)
 
     groups = [g.strip() for g in args.only.split(",") if g.strip()]
-    unknown = [g for g in groups if g not in ("ctest", "py", "v1", "v2")]
+    unknown = [g for g in groups if g not in ("ctest", "py", "v1", "v2", "gate")]
     if unknown:
-        print("不认识的组: %s(只用 ctest,py,v1,v2)" % ",".join(unknown), file=sys.stderr)
+        print("不认识的组: %s(只用 ctest,py,v1,v2,gate)" % ",".join(unknown), file=sys.stderr)
         return 2
 
     results: list = []
@@ -163,6 +238,13 @@ def main(argv: list | None = None) -> int:
                              ("runs/v2gate_B4.jsonl", "runs/_v2gate_B4")):
             ok, note = check_replay(name, images, args.allow_missing)
             results.append(("v2 回放 %s" % name, ok, note))
+    if "gate" in groups:
+        if not args.dataset_dir:
+            ok, note = True, "SKIP:未指定 --dataset-dir / PORTCV_DATASET_DIR(数据集门禁不跑)"
+        else:
+            ok, note = check_dataset_gate(args.dataset_dir, args.gate_repeats,
+                                          args.allow_missing)
+        results.append(("数据集安全门禁(禁止新增违例)", ok, note))
 
     lines: list = ["", "=" * 78, "冻结点回归", "=" * 78]
     bad = 0