File size: 75,748 Bytes
85097f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
"""批次统计:题目的输入分布、版内多样性,以及两批之间的对照。

  python3 -B -m np.batch_stats OUT VOUT [--json 路径]
      OUT/段/script.json、facts.npz 是生成结果,VOUT/段/questions.jsonl 是出题结果(与 apps/console/server/batch_summary 同布局)。
      按剧本来源 generator.config.pool(anti_shortcut | natural,没标记“未标”)分开,报输入分布和每版多样性。
  python3 -B -m np.batch_stats --compare VOUT_A VOUT_B [--noise VOUT_C]
      B 对 A 逐(段, 版)比四项多样性,报合计、降和升的版数,以及符号检验 z =(降−升)÷√(降+升)。
      判退步:合计降、且 z > 2(降的版显著多于升的版)。只看一臂换种子的降幅作底太粗:need-noise 里片段桶门槛 20 降 0.32%、
      换种子降 0.13%,但降升 525/505(z 0.6)、604/571(z 1.0)都不显著。--noise C(与 A 同设置只换种子)照样报,它的 z 应在 2 以内,
      超过说明换种子本身就会显著变,判据要重定。

  python3 np/batch_stats.py --chain NAME --segs DIR --logs DIR --vout DIR --arm ARM [--cfg DIR] [--json OUT]
  python3 np/batch_stats.py --chain-compare FRONT.json NEW.json [--noise NOISE.json]
      整链统计需要 --cfg、固定 --versions(或 --catalog)、两臂 logs/segs/vout 与完整 SHA;共同支持集上比较。
      chain-gate/2 退出码:0 有优势,1 退步,2 无优势,3 无效,75 没测成;优先级 3→75→1→2→0。
      prover_code 记录所声明提交的出题代码指纹;仅剧本与已知代码均相同时豁免用时变化,缺指纹照常判。
      prover.post_reject_count 是候选后拒合计(不含 prefiltered:、sampling:),比 FRONT 增加判退步、减少算优势、相等持平;
      validity.<规则>.<版本>.violations 由同一份代码独立重查题包;两臂检查完整且分母相等时,减少算有效性优势、增加退步。
      缺字段或不支持的规则记不可检,不补零;checked/unchecked 只报检查覆盖。
      gen.sec_median、gen.sec_max 只展示;生成性能由门的逐配置配对用时比判定。
      逐版合计跌到 FRONT 的 0.2 倍以下(未到 0)列“大跌报警”,不改退出码。
      prover.leak_drop_count、prover.leak_drop_ratio、leak_drop.<因> 是抽包后泄露检查剔掉的包(summary 的 leak_check),
      reject_reasons 里没有、post_reject_count 数不到;先只报不判退步。
      arr.prover_agree 是安排与证明一致率(段摘要 arrangements 里两边结论相同的占比),NEW 里 <1 或
      arr.agree_error_segments >0 即判退步,保证安排与证明的判定一致。
      可发布数退步用逐版合计的符号检验(降的版显著多于升的版、且合计降);各段合计的中位、均值只展示。
      不足 20 的版按户型列拒因前三(预筛、候选后分开);给了 --cfg,组头下印安排层概况。

多样性四项:写出数、不同题面、不同作答取值(replay.value)、不同片段起点 10 s 桶(binding.local_span_s 首项)。"""
import argparse
import collections
import contextlib
import hashlib
import json
import math
import re
from pathlib import Path

from embodied_pipeline.domain import storage
import statistics
import subprocess
import sys
import zipfile

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from embodied_pipeline.domain.spec_motion import (CRUISE_SPREAD_MIN, SLOW_FRAC_MAX, SPEED_SLOW, SPEED_STILL,
                                                  VISUAL_ACCEL_S as ACCEL_S, VISUAL_ACCEL_MPS2 as ACCEL_MPS2)

ITEMS = ('写出', '题面', '作答取值', '片段桶')
Z = 2.0          # 符号检验门槛,约双侧 5%


def rows(vout):
    """{(段, 版): [题]}。"""
    out = collections.defaultdict(list)
    for f in sorted(Path(vout).glob('*/questions.jsonl')):
        for line in f.read_text().splitlines():
            if line.strip():
                r = json.loads(line)
                out[(f.parent.name, r['public']['version_id'])].append(r)
    return out


def _start(r):
    x = (r.get('binding') or {}).get('local_span_s')
    return x[0] if isinstance(x, (list, tuple)) and x else (x or 0)


def _value(r):
    return json.dumps((r.get('replay') or {}).get('value'), ensure_ascii=False, sort_keys=True)


def diversity(rs):
    return [len(rs), len({json.dumps(r['public'].get('text'), ensure_ascii=False) for r in rs}),
            len({_value(r) for r in rs}), len({int(_start(r) // 10) for r in rs})]


def segment_inputs(seg):
    """一段的输入:来源、住宅、主体种类、安排、观察者,和事实包里的事件数。"""
    script = json.loads((seg / 'script.json').read_text())
    g = script.get('generator') or {}
    c = g.get('config') or {}
    kinds = collections.Counter(a.get('kind') for a in c.get('cast') or [])
    events = {}
    if (seg / 'facts.npz').exists():
        z = np.load(seg / 'facts.npz')
        if 'room_event_kind' in z:
            k = z['room_event_kind']
            events = dict(进房=int((k > 0).sum()), 出房=int((k < 0).sum()))
        if 'door_event_t' in z:
            events['穿门'] = int(len(z['door_event_t']))
    return dict(pool=c.get('pool') or '未标', house=Path(g.get('house') or script.get('world_id') or '?').name,
                subjects=sum(kinds.values()), kinds=dict(kinds), arranged=bool(c.get('arrangements')),
                arrangements=sorted({a.get('type') for a in c.get('arrangements') or []}),
                observers=sorted(f"{o.get('kind')}/{o.get('body') or '-'}/{o.get('motion_mode') or '-'}" for o in c.get('observers') or []),
                events=events)


def summarize(out, vout):
    segs = {p.name: segment_inputs(p) for p in sorted(Path(out).iterdir()) if (p / 'script.json').exists()}
    R = rows(vout)
    by_pool = collections.defaultdict(lambda: dict(segments=0, inputs=collections.defaultdict(collections.Counter),
                                                   versions=collections.defaultdict(list), answers=collections.defaultdict(list)))
    for pool in ('anti_shortcut', 'natural', '未标'):
        by_pool[pool]
    for name, x in segs.items():
        P = by_pool[x['pool']]
        P['segments'] += 1
        P['inputs']['住宅'][x['house']] += 1
        P['inputs']['主体数'][x['subjects']] += 1
        P['inputs']['有无安排']['有' if x['arranged'] else '无'] += 1
        for k, n in x['kinds'].items():
            P['inputs']['主体种类'][k] += n
        for a in x['arrangements']:
            P['inputs']['安排类型'][a] += 1
        for o in x['observers']:
            P['inputs']['观察者'][o] += 1
        for k, n in x['events'].items():
            P['inputs']['事件'][k] += n
    for (seg, v), rs in R.items():
        P = by_pool[segs.get(seg, dict(pool='未标'))['pool']]
        P['versions'][v].append(diversity(rs))
        P['answers'][v] += [(r.get('replay') or {}).get('value') for r in rs]
        for r in rs:
            P['inputs']['所问时刻 10 s 桶'][int(_start(r) // 10) * 10] += 1
    result = {}
    for pool, P in by_pool.items():
        vers = {}
        for v, ds in sorted(P['versions'].items()):
            vals = P['answers'][v]
            nums = [x for x in vals if isinstance(x, (int, float)) and not isinstance(x, bool)]
            ans = (dict(数值=len(nums), 最小=min(nums), 中位=statistics.median(nums), 最大=max(nums)) if nums and len(nums) == len(vals)
                   else dict(collections.Counter(json.dumps(x, ensure_ascii=False, sort_keys=True) for x in vals).most_common(8)))
            counts = collections.Counter(json.dumps(x, ensure_ascii=False, sort_keys=True) for x in vals)
            vers[v] = dict(段=len(ds), 分母=len(vals), 答案计数=dict(sorted(counts.items())),
                           **{f'{n}中位': statistics.median(d[i] for d in ds) for i, n in enumerate(ITEMS)}, 作答分布=ans)
        result[pool] = dict(段数=P['segments'], 输入分布={k: dict(c.most_common()) for k, c in P['inputs'].items()},
                            分母=sum(len(vals) for vals in P['answers'].values()),
                            各版载体配方='NOT_CHECKED', 一般稀有性判据='NOT_CHECKED',
                            零产出版=sorted(v for v, x in vers.items() if x['写出中位'] == 0), 每版=vers)
    return result


def shortfall(out, vout, cfg):
    """配置声明住宅全集;每栋每档目标三段,两能力组共享载体,供给按组重复、总段数去重。"""
    from embodied_pipeline.gen.config import DURATION

    tiers = dict(zip(('short', 'medium', 'long'), DURATION['of']))
    groups = ('1-4', '5')
    configs = [json.loads(p.read_text()) | {'_name': p.stem} for p in sorted(Path(cfg).glob('*.json'))]
    if not configs:
        raise ValueError('三维缺口需要非空 --cfg 单段配置目录')
    identities = {}
    for c in configs:
        name, house = c.get('id', c['_name']), Path(c['scene']).name
        tier = [k for k, band in tiers.items() if band['lo'] <= c['duration_s'] <= band['hi']]
        if len(tier) != 1 or name in identities:
            raise ValueError(f'{name}: 段长档不明或段名重复')
        identities[name] = (tier[0], house)
    houses = sorted({h for _, h in identities.values()})
    cells = {(t, g, h): dict(时段档=t, 能力组=g, 房子=h, 目标段数=3, 成段数=0,
                            出题段数=0, 出题数=0, 题包数=0, 缺口=0, 出题缺口=0)
             for t in tiers for g in groups for h in houses}
    generated = {p.parent.name for p in Path(out).glob('*/script.json')}
    if generated - identities.keys():
        raise ValueError(f'成段缺配置: {sorted(generated - identities.keys())}')
    for name in generated:
        tier, house = identities[name]
        for g in groups:
            cells[tier, g, house]['成段数'] += 1
    contract = json.loads((Path(__file__).resolve().parents[1] / 'embodied_pipeline/prover/wp_target.json').read_text())
    units = {vid: u for v in contract['versions'] if (u := v.get('unit'))
             for vid in [v['id'], *v.get('impl', [])]}
    supplied, packages = set(), set()
    for filename in ('questions.jsonl', 'groups.jsonl'):
        for path in sorted(storage.stored_glob(vout, f'*/{filename}')):
            name = path.parent.name
            if name not in generated:
                raise ValueError(f'{path}: 出题目录缺成段')
            tier, house = identities[name]
            for line in storage.iter_lines(path):
                if not line.strip():
                    continue
                row = json.loads(line)
                group = (row.get('scope') or {}).get('group') or {}
                unit = group.get('unit') or units.get(row['public']['version_id'])
                roots = {str(u).split('.')[0] for u in (unit if isinstance(unit, list) else [unit])}
                if not roots or not roots <= {'1', '2', '3', '4', '5'} or ('5' in roots and len(roots) > 1):
                    raise ValueError(f'{path}: 未知能力单元 {unit!r}')
                g = '5' if roots == {'5'} else '1-4'
                cell = cells[tier, g, house]
                cell['出题数'] += 1
                supplied.add((name, g))
                if group:
                    if 'id' not in group or 'unit' not in group:
                        raise ValueError(f'{path}: 题包缺 id/unit')
                    packages.add((name, g, group['unit'], group['id']))
    for name, g in supplied:
        tier, house = identities[name]
        cells[tier, g, house]['出题段数'] += 1
    for name, g, _, _ in packages:
        tier, house = identities[name]
        cells[tier, g, house]['题包数'] += 1
    target_segments, cumulative = sum(c['目标段数'] for c in cells.values()), 0
    for cell in cells.values():
        previous, cumulative = cumulative, cumulative + cell['目标段数']
        cell['目标题数'] = 4000*cumulative//target_segments - 4000*previous//target_segments
        cell['缺口'] = max(0, cell['目标段数'] - cell['成段数'])
        cell['出题缺口'] = max(0, cell['目标段数'] - cell['出题段数'])
    totals = {k: sum(c[k] for c in cells.values()) for k in ('目标段数', '成段数', '出题段数', '出题数', '题包数', '缺口', '出题缺口', '目标题数')}
    unique = dict(目标段数=9*len(houses), 成段数=len(generated), 出题数=totals['出题数'], 缺口=totals['缺口']//2)
    return dict(口径='两能力组共享成段供给;格合计重复计段,去重总数不重复;出题缺口按有题段数计算',
                题量口径='约4000题按格目标段数占比分摊,以累计整除差额取整,合计4000;仅作规划参考,不作硬门',
                格子=list(cells.values()), 合计=totals, 去重总数=unique,
                缺口前十=sorted(cells.values(), key=lambda c: (-c['缺口'], -c['出题缺口']))[:10])


def segdist(run):
    """只读 cfg/state/logs;面积按本批去重值的秩四分位,p90 用最近秩(ceil(.9*n)),另列线性插值。"""
    run = Path(run)
    areas = json.loads((Path(__file__).parent / 'batches/release40-areas.json').read_text())['pass_m2']
    records, missing_logs = [], []
    for path in sorted((run / 'cfg').glob('*.json')):
        cfg = json.loads(path.read_text())
        name = cfg['id']
        state = json.loads((run / 'state/seg' / (name + '.json')).read_text())
        rc = state['rc']
        if not isinstance(rc, int):
            raise ValueError(f'{name}: missing completed rc')
        duration = float(cfg['duration_s'])
        band = 'short' if duration <= 60 else 'mid' if duration <= 125 else 'long'
        scene = cfg['scene']
        area = areas.get(scene, areas.get(scene.split('_')[0]))
        if area is None or not math.isfinite(area):
            raise ValueError(f'{name}: missing pass_m2 for {scene}')
        wall = float(state['wall_s'])
        if not math.isfinite(wall) or wall < 0 or not math.isfinite(duration) or duration <= 0:
            raise ValueError(f'{name}: invalid duration/wall_s')
        log = run / 'logs' / (name + '.log')
        if not log.exists():
            missing_logs.append(name)
        text = log.read_text(errors='replace') if log.exists() else ''
        records.append(dict(name=name, duration=band, people=len(cfg['cast']), area=area,
                            kind=name.rsplit('_', 1)[-1].split('-')[0], rc=rc, wall=wall, log=text))
    if not records:
        raise ValueError(f'{run}: no cfg/*.json')
    xs = sorted({r['area'] for r in records})
    cuts = [xs[len(xs)*i//4] for i in (1, 2, 3)]
    for r in records:
        r['quartile'] = 'Q' + str(1 + sum(r['area'] >= q for q in cuts))

    def failures(selected):
        n = len(selected); failed = sum(r['rc'] != 0 for r in selected)
        return dict(segments=n, failed=failed, failure_rate=failed/n if n else None)

    def timing(selected):
        walls = [r['wall'] for r in selected if r['rc'] == 0]
        return dict(succeeded=len(walls), wall_s_median=statistics.median(walls) if walls else None,
                    wall_s_p90=sorted(walls)[math.ceil(.9*len(walls))-1] if walls else None,
                    wall_s_p90_linear=float(np.percentile(walls, 90)) if walls else None,
                    le10_s=sum(w <= 10 for w in walls), le60_s=sum(w <= 60 for w in walls))

    people = sorted({r['people'] for r in records})
    times = [dict(duration=d, people=p, **timing([r for r in records if (r['duration'], r['people']) == (d, p)]))
             for d in ('short', 'mid', 'long') for p in people]
    tables = {}
    for axis, values, by_people in (('duration', ('short', 'mid', 'long'), True),
                                     ('quartile', ('Q1', 'Q2', 'Q3', 'Q4'), True),
                                     ('kind', sorted({r['kind'] for r in records}), False)):
        tables[axis] = [dict(bucket=v, **({'people': p} if by_people else {}),
                            **failures([r for r in records if r[axis] == v and (not by_people or r['people'] == p)]))
                        for v in values for p in (people if by_people else [None])]
    tails = collections.Counter()
    hard = collections.defaultdict(list)
    patterns = ('gave way too long', 'no speed')
    for r in records:
        if r['rc'] != 0:
            tail = next((s.strip() for s in reversed(r['log'].splitlines()) if s.strip()), '<missing/empty log>')
            tail = re.sub(r'[-+]?\d+(?:\.\d+)?', '#', tail)
            tails[r['rc'], tail] += 1
        for pattern in patterns:
            if re.search(pattern, r['log'], re.IGNORECASE):
                hard[pattern].append(r)
    return dict(schema='segdist/1', total=failures(records), timing_total=timing(records), timing=times,
                failures=tables, area_cuts_m2=cuts, missing_logs=missing_logs,
                failure_tails=[dict(rc=rc, tail=tail, segments=n) for (rc, tail), n in sorted(tails.items())],
                hard_reasons=[dict(pattern=k, segments=len(rs), failed=sum(r['rc'] != 0 for r in rs),
                                   duration_people=[dict(duration=d, people=p, segments=sum((r['duration'], r['people']) == (d, p) for r in rs))
                                                    for d in ('short', 'mid', 'long') for p in people])
                              for k, rs in sorted(hard.items())])


def compare(a, b, noise=None):
    A, B = ({k: diversity(v) for k, v in rows(x).items()} for x in (a, b))
    C = {k: diversity(v) for k, v in rows(noise).items()} if noise else None

    def delta(X):
        both = [k for k in A if k in X]
        out = {}
        for i, n in enumerate(ITEMS):
            sa, sx = sum(A[k][i] for k in both), sum(X[k][i] for k in both)
            out[n] = dict(合计=[sa, sx], 变化=round((sx-sa)/sa*100, 2) if sa else None,
                         降=sum(X[k][i] < A[k][i] for k in both), 升=sum(X[k][i] > A[k][i] for k in both))
            d, u = out[n]['降'], out[n]['升']
            out[n]['z'] = round((d-u)/math.sqrt(d+u), 2) if d+u else 0.0
        return dict(只在对照=len([k for k in A if k not in X]), 只在本批=len([k for k in X if k not in A]), 各项=out)
    res = dict(B=delta(B))
    res['退步'] = [n for n, x in res['B']['各项'].items() if (x['变化'] or 0) < 0 and x['z'] > Z]
    if C is not None:
        res['噪声底'] = delta(C)
        res['噪声底显著'] = [n for n, x in res['噪声底']['各项'].items() if abs(x['z']) > Z]
    return res



# Chain metrics are flattened within each configuration-prefix group; ratios use 0..1.
# 预筛拒、抽样预算截断不算候选后拒。
# 整版阻断(剧本只有一路、没有可求值查询)不是抽出候选后的拒,也不算。
NOT_POST = ('prefiltered:', 'sampling:', 'blocked:single_view_script', 'blocked:no_evaluable_query')
# 逐版合计跌到 FRONT 的这个倍数以下报警,不进退步:少了可以靠加量补,变 0 归零损失闸。
DROP = 0.2
LEAK_KEYS = ('prover.leak_drop_', 'leak_drop.')
GROUP_NAMES = dict(c10='N10', c5='N5', c5w='N5W', vw='A10')
# 证明器 CPU 随机器负载起伏:同剧本同代码两臂(四组剧本逐字相同、出题同一份代码)差 -7.2%…+4.6%,12 项里 9 项判了
# 退步。门里没有噪声臂时按 FRONT 的 10% 定底;有噪声臂用两次前沿之差
LOAD_REL = dict.fromkeys(('prover.cpu_sec_median', 'prover.cpu_sec_max', 'prover.cpu_sec_total'), .1)
# 生成秒数只展示:各臂独立中位/最大值不参与方向裁决。
DIRECTIONS = {
    **{k: -1 for k in ('gen.rejected_attempt_count', 'check.conflict_segments',
       'check.off_walkable_segments', 'check.speed_over_segments',
       'prover.missing_summary_segments', 'prover.missing_questions_segments',
       'hum.seen_longest_sec_median', 'hum.still_ratio_median',
       'hum.still_seen_ratio_median', 'obs.longest_sec_median', 'obs.longest_sec_max',
       'obs.still_ratio_median', 'hum.pause_rate_band_gap', 'obs.pause_rate_band_gap', 'prover.cpu_sec_median', 'prover.cpu_sec_max', 'prover.cpu_sec_total',
       'prover.post_reject_count', 'arr.agree_error_segments', 'hum.cruise_spread_gap', 'hum.speed_slow_gap', 'hum.speed_accel_over_ratio')},
    # hum.longest_sec_* 量全部站立(含不在画面里的让路),只报数不定方向;方向看被看见时的 hum.seen_longest_sec_median;
    # 它的 max 是一个人的极值、门里没有噪声臂定底,只走 LIMITS 的 SEEN_STAND_S 绝对线
    # 速度中位本身不定方向(快不一定好);定方向的是慢走占时(SPEED_SLOW)、巡航速度的差别(CRUISE_SPREAD_MIN)和在动帧速度变化超过 ACCEL_MPS2 的占比(中位从 .85 降到 .55 时
    # 历次对比都判“无方向”、没报退步);hum.speed_mps_median 只展示
    # pauses_ge3_count_* 只展示:停顿不是越少越好,方向看每分钟停顿次数离 PAUSE_RATE_BAND 的距离
    # written_count 中、均只展示不定方向:段合计的中位、均值和逐版方向会相反(同 publishable,8512e330)
    **{k: 1 for k in ('gen.success_ratio', 'check.moving_ratio_median',
       'prover.written_full_versions', 'prover.publishable_full_versions', 'arr.prover_agree')},
    **{f'diversity.{k}_{suffix}': 1 for k in ('written', 'text', 'answer', 'start_bin10s')
       for suffix in ('median', 'full_versions')},
}


# 人形走速看两条:低速不能多,被任一观察者看见的时间(含站,量法同 _speed10)里 SPEED_SLOW 档的占时不超过真人(THÖR)的两倍;
# 速度要有差别,每段巡航速度(_cruise)按时长的 p90−p10 不比真人窄(THÖR .86–1.18)。
# SPEED_FAST 档的占时和巡航分位只报数:walker 配置三档速度里只有一档落在这个区间,无停无弯也到不了真人的比例
# 速度变化按视觉看(0.1 s 里 1.5→1.0 不行,零点几秒内平滑地变可以):在动帧上 ACCEL_S 窗内 |Δv|/Δt 超过
# 真人刹车平均减速度 p90 的占比(THÖR .72 m/s²)
SPEED_FAST = (.9, 1.3)
CRUISE_MIN_S, CRUISE_TRIM_S = 3., 1.5
# 停顿(量法同 thor_pause.py:1 s 滑动平均后 v < .25 连续 ≥3 s、两头都在录像里;可见 ≥20 s 的人才算次数/分钟)的真人带:THÖR
# 每人每分钟 p10/中位/p90 0/1.67/2.92 次,停顿时长 p90 16.4 s(53 人段、74 次停顿);带下沿取 .5
PAUSE_RATE_BAND, PAUSE_P90_S = (.5, 3.), 17.


def _accel_over(xy, hz):
    """一个人的位置 → (在动帧数, 其中 |Δv|/Δt > ACCEL_MPS2 的帧数):10 Hz 块平均、ACCEL_S 滑动平均后中心差分得速度,
    相隔 ACCEL_S 的两帧都 ≥.25 m/s 才算在动。"""
    k = max(int(round(hz/10)), 1); n = len(xy)//k*k; w = int(ACCEL_S*10)
    p = xy[:n].reshape(-1, k, 2).mean(1)
    if len(p) < 3*w:
        return 0, 0
    p = np.stack([np.convolve(p[:, i], np.ones(w)/w, 'valid') for i in (0, 1)], 1); v = np.linalg.norm(p[2:]-p[:-2], axis=1)*5
    mv = (v[w:] >= .25) & (v[:-w] >= .25)
    return int(mv.sum()), int((mv & (np.abs(v[w:]-v[:-w])/ACCEL_S > ACCEL_MPS2)).sum())


def _speed10(xy, hz):
    """一个人的位置 → 逐帧速度(10 Hz 块平均、.5 s 滑动平均后中心差分,同真人那边的量法);太短返回空。"""
    k = max(int(round(hz/10)), 1); n = len(xy)//k*k; p = xy[:n].reshape(-1, k, 2).mean(1)
    if len(p) < 12:
        return np.zeros(0)
    p = np.stack([np.convolve(p[:, i], np.ones(5)/5, 'valid') for i in (0, 1)], 1)
    return np.linalg.norm(p[2:]-p[:-2], axis=1)*5


def _cruise(xy, hz):
    """一个人的位置 → [(巡航速度, 段长 s)],量法同 thor_acc.py:10 Hz 块平均、ACCEL_S 滑动平均后逐帧速度;v ≥ .25 连续
    ≥ CRUISE_MIN_S 为一个走着段,巡航速度是段内去掉两头各 CRUISE_TRIM_S 后的中位(起步、刹车不算进来)。"""
    k = max(int(round(hz/10)), 1); n = len(xy)//k*k; w = int(ACCEL_S*10)
    p = xy[:n].reshape(-1, k, 2).mean(1)
    if len(p) < 5*w:
        return []
    p = np.stack([np.convolve(p[:, i], np.ones(w)/w, 'valid') for i in (0, 1)], 1); v = np.linalg.norm(np.gradient(p, axis=0), axis=1)*10
    mv = v >= .25; cut = np.flatnonzero(np.diff(mv.astype(int)))+1; e = int(CRUISE_TRIM_S*10); out = []
    for lo, hi in zip(np.r_[0, cut], np.r_[cut, len(v)]):
        if mv[lo] and hi-lo >= CRUISE_MIN_S*10:
            out.append((float(np.median(v[lo+e:hi-e] if hi-lo > 2*e+2 else v[lo:hi])), (hi-lo)/10))
    return out


def _pauses(xy, hz):
    """一个人的位置 → (录像秒数, [停顿秒]),量法同 thor_pause.py:10 Hz 块平均、1 s 滑动平均后逐帧速度,v < .25 连续 ≥3 s、
    两头都在录像里的算一次停顿。"""
    k = max(int(round(hz/10)), 1); n = len(xy)//k*k
    p = xy[:n].reshape(-1, k, 2).mean(1)
    if len(p) < 20:
        return len(p)/10, []
    p = np.stack([np.convolve(p[:, i], np.ones(10)/10, 'valid') for i in (0, 1)], 1); v = np.linalg.norm(np.gradient(p, axis=0), axis=1)*10
    st = v < .25; cut = np.flatnonzero(np.diff(st.astype(int)))+1
    return len(v)/10, [(hi-lo)/10 for lo, hi in zip(np.r_[0, cut], np.r_[cut, len(v)]) if st[lo] and hi-lo >= 30 and lo > 0 and hi < len(v)]


def _wmed(vd, q=.5):
    """[(值, 权)] → 按权的 q 分位(缺省中位,同 thor_acc.py 的 wq)。"""
    x, w = np.array(vd, float).T; o = np.argsort(x); c = np.cumsum(w[o])/w.sum()
    return float(x[o][min(int(np.searchsorted(c, q)), len(x)-1)])


def _med(xs):
    return float(statistics.median(xs))


def _logs(logs, arm, only=None):
    for f in sorted(Path(logs).glob(f'{arm}_*.log')) if logs else []:
        if only is not None and f.stem[len(arm)+1:] not in only:
            continue
        text = f.read_text()
        js = []
        for line in text.splitlines():
            if line.startswith('{'):
                try:
                    js.append(json.loads(line))
                except ValueError:
                    pass
        rc = int((re.findall(r'^rc=(\d+)', text, re.M) or ['-1'])[-1])
        sec = int((re.findall(r'^sec=(\d+)', text, re.M) or ['0'])[-1])/1000
        r = ([j for j in js if 'script_id' in j or 'error' in j] or [{}])[-1]
        yield f.stem[len(arm)+1:].split('_')[0], rc, sec, r, js


def gen_stats(logs, arm, only=None):
    """Per configuration prefix, all completed configurations (including refusals)."""
    grouped = collections.defaultdict(list)
    for g, rc, sec, r, _ in _logs(logs, arm, only):
        ok = rc == 0 and bool(r) and 'rejected' not in r and 'error' not in r
        grouped[g].append((ok, sec, len(r.get('tried', [])) + int(ok), [t.split(':')[0] for t in r.get('tried', [])]))
    return {g: {'gen.config_count': len(xs), 'gen.attempt_count': sum(x[2] for x in xs),
                # refused attempts, each a whole pipeline run thrown away; by reason too
                'gen.rejected_attempt_count': sum(len(x[3]) for x in xs),
                **{f'gen.rejected.{k}': v for k, v in collections.Counter(t for x in xs for t in x[3]).items()},
                'gen.success_count': sum(x[0] for x in xs), 'gen.success_ratio': sum(x[0] for x in xs)/len(xs),
                'gen.sec_median': _med([x[1] for x in xs]), 'gen.sec_max': max(x[1] for x in xs)}
            for g, xs in grouped.items()}


def check_stats(logs, arm, only=None):
    """Generator self-checks as recorded, without upgrading them to rendered QA."""
    grouped = collections.defaultdict(list)
    for g, _, _, _, js in _logs(logs, arm, only):
        cs = [j['check'] for j in js if 'check' in j]
        if cs:
            grouped[g].append(cs[-1])
    return {g: {'check.segment_count': len(cs),
                **{f'check.{out}_segments': sum(c[key] > 0 for c in cs) for out, key in
                   (('conflict', 'conflict_frames'), ('off_walkable', 'off_walkable'), ('speed_over', 'speed_over'))},
                # a segment with one body has no pair: min_sep_m is None
                'check.min_sep_m': min((c['min_sep_m'] for c in cs if c.get('min_sep_m') is not None), default=None),
                'check.accel_ratio_max': max((c['accel_ratio'] for c in cs if c.get('accel_ratio') is not None), default=None),
                'check.moving_ratio_median': _med([c['moving_share'] for c in cs])}
            for g, cs in grouped.items()}


def _runs(mask):
    return [len(x) for x in np.split(mask, np.flatnonzero(np.diff(mask)) + 1) if len(x) and x[0]]


def _seen(meta, facts, aid, tt):
    from embodied_pipeline.domain import visibility
    from embodied_pipeline.prover import methods
    params = methods.params()
    ents = [e['id'] for e in meta['entities']]
    out = np.zeros(len(tt), bool)
    if aid not in ents:
        return out
    x = ents.index(aid)
    for vi, v in enumerate(meta['views']):
        n = int(v['frame_count'])
        ft = facts['frame_time_s'][vi][:n]
        ok = visibility.seen_code(facts['obs_projected_height'][vi][x, :n], facts['obs_occlusion'][vi][x, :n],
                                  visibility.frame_valid(facts['obs_front_clear_m'][vi][:n]), params['min_ph'], params['max_occ']) == 0
        j = np.clip(np.searchsorted(ft, tt), 1, n-1)
        j = np.where(np.abs(tt-ft[j-1]) <= np.abs(ft[j]-tt), j-1, j)
        out |= (tt >= float(v['first_frame_s'])) & (tt <= float(v['last_frame_s'])) & ok[j]
    return out


def motion_stats(segs, only=None):
    grouped = collections.defaultdict(lambda: collections.defaultdict(list))
    traj = collections.defaultdict(set)   # 组 → 人形轨迹指纹:c10、c5、c5w 几组的人形轨迹可以逐字节相同,段多样本不多
    for f in sorted(Path(segs).glob('*/script.json')) if segs else []:
        if only is not None and f.parent.name not in only:
            continue
        s = json.loads(f.read_text())
        R = grouped[f.parent.name.split('_')[0]]
        with np.load(f.parent / 'curves.npz') as c:
            t = c['t']; hz = 1/np.median(np.diff(t)); i0 = int(np.searchsorted(t, 0.))
            visible = {}
            if (f.parent / 'facts.npz').exists():
                meta = json.loads(storage.read_text(f.parent / 'facts.json'))
                with np.load(f.parent / 'facts.npz') as facts:
                    visible = {a['id']: _seen(meta, facts, a['id'], t[i0:-1]) for a in s['actors']
                               if not a['kind'].startswith('observer')}
            for a in s['actors']:
                k = 'obs' if a['kind'].startswith('observer') else 'hum'; aid = a['id']
                xy = np.stack([c[aid+'__u'], c[aid+'__v']], -1)[i0:]
                sp = np.linalg.norm(np.diff(xy, axis=0), axis=-1)*hz
                still = sp < SPEED_STILL; rs = np.array(_runs(still))/hz
                R[k, 'longest_sec'].append(float(rs.max()) if len(rs) else 0.)
                R[k, 'still_ratio'].append(float(still.mean()))
                R[k, 'pauses_ge3_count'].append(int((rs >= 3).sum())); R[k, 'pause'].append(_pauses(xy, hz))
                if k == 'hum':
                    traj[f.parent.name.split('_')[0]].add(np.round(xy, 3).tobytes())
                    seen = visible.get(aid, np.zeros(len(sp), bool))
                    cuts = np.flatnonzero(np.diff(seen.astype(int)))+1
                    spans = [(lo, hi) for lo, hi in zip(np.r_[0, cuts], np.r_[cuts, len(seen)]) if seen[lo]]
                    # 保持时间连续:遮挡两侧不能拼成相邻位置;全帧旧值只报数。
                    for suffix, chunks, speeds in (('_all', [xy], sp),
                                                    ('', [xy[lo:hi+1] for lo, hi in spans], sp[seen])):
                        if len(speeds):
                            moving = speeds[speeds >= SPEED_STILL]
                            R[k, 'speed_mps'+suffix].append(float(np.median(moving)) if len(moving) else 0.)
                        for chunk in chunks:
                            R[k, 'accel'+suffix].append(_accel_over(chunk, hz))
                            R[k, 'cruise'+suffix].append(_cruise(chunk, hz))
                            if a['kind'] == 'humanoid':             # 速度分布对的是真人,只算人形
                                R[k, 'speed10'+suffix].append(_speed10(chunk, hz))
                    if aid in visible:
                        seen = visible[aid]
                        R[k, 'still_seen_ratio'].append(float((still & seen).sum()/max(seen.sum(), 1)))
                        ss = np.array(_runs(still & seen))/hz
                        R[k, 'seen_longest_sec'].append(float(ss.max()) if len(ss) else 0.)
    out = {}
    for g, R in grouped.items():
        speed_stats = {}
        for suffix in ('', '_all'):
            A = R.pop(('hum', 'accel'+suffix), None); C = [x for xs in R.pop(('hum', 'cruise'+suffix), ()) for x in xs]
            V = np.concatenate(R.pop(('hum', 'speed10'+suffix), []) or [np.zeros(0)])
            values = {}
            if A and sum(a for a, _ in A):
                values['speed_accel_over_ratio'] = sum(b for _, b in A)/sum(a for a, _ in A)
            if C:
                p10, p90 = _wmed(C, .1), _wmed(C, .9)
                values.update({'cruise_mps_median': _wmed(C), 'cruise_mps_p10': p10, 'cruise_mps_p90': p90,
                               'cruise_spread_mps': p90-p10})
                if not suffix:
                    values['cruise_spread_gap'] = max(CRUISE_SPREAD_MIN-(p90-p10), 0.)
            if len(V):
                fast = float(((V >= SPEED_FAST[0]) & (V < SPEED_FAST[1])).mean()); slow = float(((V >= SPEED_SLOW[0]) & (V < SPEED_SLOW[1])).mean())
                values.update({'speed_fast_frac': fast, 'speed_slow_frac': slow})
                if not suffix:
                    values['speed_slow_gap'] = max(slow-SLOW_FRAC_MAX, 0.)
            M = R.pop(('hum', 'speed_mps'+suffix), [])
            if M:
                values['speed_mps_median'] = _med(M)
            speed_stats.update({f'hum.{key}{suffix}': value for key, value in values.items()})
        P = {k: R.pop((k, 'pause'), []) for k in ('hum', 'obs')}
        out[g] = {f'{k}.{metric}_median': _med(xs) for (k, metric), xs in R.items()}
        out[g].update(speed_stats)
        for k in ('hum', 'obs'):
            if (k, 'longest_sec') in R:
                out[g][f'{k}.actor_count'] = len(R[k, 'longest_sec'])
                out[g][f'{k}.longest_sec_max'] = max(R[k, 'longest_sec'])
                for suffix, fn in (('min', min), ('max', max)):
                    out[g][f'{k}.pauses_ge3_count_{suffix}'] = fn(R[k, 'pauses_ge3_count'])
        for k, ps in P.items():
            rate = [len(d)/T*60 for T, d in ps if T >= 20]
            if rate:
                r = out[g][f'{k}.pause_rate_per_min_median'] = _med(rate)
                out[g][f'{k}.pause_rate_band_gap'] = max(PAUSE_RATE_BAND[0]-r, r-PAUSE_RATE_BAND[1], 0.)
        D = [x for _, d in P['hum'] for x in d]
        if D:
            out[g]['hum.pause_sec_p90'] = float(np.percentile(D, 90))
        if ('hum', 'seen_longest_sec') in R:
            out[g]['hum.seen_longest_sec_max'] = max(R['hum', 'seen_longest_sec'])
        if traj[g]:
            other = set().union(*(v for h, v in traj.items() if h != g))
            out[g]['hum.distinct_traj_count'] = len(traj[g])
            out[g]['hum.traj_shared_ratio'] = len(traj[g] & other)/len(traj[g])
    return out


def _group_summaries(vout, segs=None, only=None):
    """(组 → 段名, 组 → 段 → summary):段取 segs(没给就取 vout)下全部子目录,组名是段名第一个 _ 之前;
    给了 only(段名集合)只取其中的段。"""
    grouped = collections.defaultdict(dict)
    source = segs if segs is not None else vout
    members = collections.defaultdict(list)
    for d in sorted(Path(source).iterdir()) if source and Path(source).is_dir() else []:
        if d.is_dir() and (only is None or d.name in only):
            members[d.name.split('_')[0]].append(d.name)
    included = {s for names in members.values() for s in names}
    for f in sorted(Path(vout).glob('**/summary.json')) if vout else []:
        seg = f.relative_to(vout).parts[0]
        if seg not in included:
            continue
        if seg in grouped[seg.split('_')[0]]:
            raise ValueError(f'multiple summaries for {seg}')
        grouped[seg.split('_')[0]][seg] = json.loads(f.read_text())
    return members, grouped


HOUSE = re.compile(r'gen-(\d+(?:_\d+)?)')


def under20_reasons(vout, segs=None, top=3, only=None):
    """不足 20 的版按户型列拒因前 top 个,预筛(prefiltered: 前缀)和候选后分开。

    整链调用传入共同支持集 only;独立诊断按 segs 下全部段取组内可发布中位 < 20 的版
    (只看摘要里出现过的版)。户型取段名里的 gen-<户型>,没有就记“未知”。同次数按拒因名排。only 同 prover_stats。
    """
    members, grouped = _group_summaries(vout, segs, only)
    out = {}
    for g, names in members.items():
        S = {s: grouped[g].get(s, {}) for s in names}
        vers = lambda s, v: (S[s].get('versions') or {}).get(v) or {}
        houses = collections.defaultdict(list)
        for s in names:
            m = HOUSE.search(s)
            houses[m.group(1) if m else '未知'].append(s)
        for v in sorted({v for x in S.values() for v in x.get('versions') or {}}):
            if _med([vers(s, v).get('publishable') or 0 for s in names]) >= 20:
                continue
            rows = out.setdefault(g, {})[v] = {}
            for h, ss in sorted(houses.items()):
                pre, post = collections.Counter(), collections.Counter()
                for s in ss:
                    for k, n in (vers(s, v).get('reject_reasons') or {}).items():
                        (pre if k.startswith('prefiltered:') else post)[k] += n
                pub = [vers(s, v).get('publishable') or 0 for s in ss]
                rows[h] = dict(segments=len(ss), zero_segments=sum(x == 0 for x in pub), publishable_median=_med(pub),
                               prefilter=[[k, n] for k, n in sorted(pre.items(), key=lambda x: (-x[1], x[0]))[:top]],
                               post=[[k, n] for k, n in sorted(post.items(), key=lambda x: (-x[1], x[0]))[:top]])
    return out


def arrangement_summary(cfg):
    """各组配置的安排层概况:安排按 type/strength 计条数,观察者按 motion_mode 计人数(CFG/*.json,组名同段名)。"""
    out = {}
    for f in sorted(Path(cfg).glob('*.json')):
        d = json.loads(f.read_text())
        a = out.setdefault(f.stem.split('_')[0], dict(configs=0, arrangements=collections.Counter(),
                                                      observer_modes=collections.Counter()))
        a['configs'] += 1
        a['arrangements'].update(f"{x.get('type')}/{x.get('strength')}" for x in d.get('arrangements') or [])
        a['observer_modes'].update(str(o.get('motion_mode')) for o in d.get('observers') or [])
    return {g: dict(configs=a['configs'], arrangements=dict(sorted(a['arrangements'].items())),
                    observer_modes=dict(sorted(a['observer_modes'].items()))) for g, a in sorted(out.items())}


VALIDITY_RULES = ('doorway_seen', 'fraction_answer')


def validity_checks(row, script, meta, facts, curves):
    """Independent checks on published evidence; None means missing/unsupported input, never zero violations."""
    from embodied_pipeline.domain.visibility import frame_valid, seen_code
    from embodied_pipeline.prover.methods import position_at
    from embodied_pipeline.semantics.shared_quantities import first_fraction
    results = {}
    from np.proof_storage import expand
    nodes = (expand(row).get('proof') or {}).get('nodes')
    if nodes is None:
        results['doorway_seen'] = None
    else:
        links = [n for n in nodes if n.get('op') == 'cross_view_link:space']
        for node in links:
            try:
                sources = node['inputs']
                if not sources:
                    raise KeyError('space inputs')
                for src in sources:
                    if src['kind'] != 'doorway':
                        continue
                    doors = script['scene']['doorways']
                    col = next(i for i, d in enumerate(doors) if d.get('id', i) == src['door'])
                    videos = row['presentation']['videos']
                    if set(src['views']) != set(videos) or not videos:
                        raise KeyError('anchor views')
                    ok = True
                    for letter, observer in videos.items():
                        vi, view = next((i, v) for i, v in enumerate(meta['views']) if v['observer'] == observer)
                        n = view['frame_count']; times = facts['frame_time_s'][vi][:n]
                        valid = frame_valid(facts['obs_front_clear_m'][vi][:n])
                        # Same strict visibility as door_src; defaults are the experiment's thresholds.
                        mask = seen_code(facts['obs_door_projected_height'][vi, col, :n],
                                         facts['obs_door_occlusion'][vi, col, :n], valid) == 0
                        ends = src['views'][letter]
                        if len(ends) != 2 or ends[0] > ends[1]:
                            raise ValueError('anchor window')
                        ok &= all(bool(np.any(mask & np.isclose(times, t, atol=1e-9, rtol=0))) for t in ends)
                    results['doorway_seen'] = results.get('doorway_seen', True) and ok
            except (KeyError, TypeError, ValueError, IndexError, StopIteration):
                results['doorway_seen'] = None
                break
    version = row['public']['version_id']
    if version.startswith('moment.clock_time.at_fraction/'):
        try:
            slots = row['public']['slots']; instant = slots['1']; value = instant['value']
            if instant['method'] != 'instant.fraction' or value['quantity'] not in ('path_length', 'displacement'):
                raise ValueError('unsupported fraction')
            within = instant['fill']['within']; span = within['value']
            if 'members' in span:
                raise ValueError('discontinuous fraction interval')
            videos = row['presentation']['videos']
            view = next(v for v in meta['views'] if v['observer'] == videos[span['video']])
            if within['method'] == 'period.clock_span':
                lo, hi = (view['first_frame_s']+span[k] for k in ('start', 'end'))
            else:
                lo, hi = span['t0'], span['t1']
            # instant_at emits no top-level truth actor; roles_of preserves the process ref here.
            truth, = [role['actor'] for role in row['presentation']['roles'] if role['path'] == '1.who']
            actor = next(a for a in script['actors'] if a['id'] == truth)
            times = curves['t']; points = position_at(actor, curves, times)
            expected = first_fraction(dict(source='curves.npz', times=times.tolist(), points=points.tolist()),
                                      [[lo, hi]], value['quantity'], value['fraction'])
            reply, = [x for x in slots.values() if x.get('method') == 'reply.clock_time']
            clock = next(v for v in meta['views'] if v['observer'] == videos[reply['value']['clock']])
            answer = row['replay']['value']
            results['fraction_answer'] = bool(np.isfinite(answer) and
                np.isclose(answer, expected-clock['first_frame_s'], atol=1e-9, rtol=0))
        except (KeyError, TypeError, ValueError, IndexError, StopIteration):
            results['fraction_answer'] = None
    return results


def prover_stats(vout, segs=None, only=None, versions=None):
    """Measure complete segments on an explicit fixed version list (catalog by default)."""
    versions = versions if versions is not None else expected_versions(Path(__file__).resolve().parents[1]/'spec/questions/catalog.json')
    members, grouped = _group_summaries(vout, segs, only)
    for g in list(members):
        members[g] = [n for n in members[g] if n in grouped[g]
                      and set(grouped[g][n].get('versions', {})) == set(versions)
                      and not grouped[g][n].get('execution_error') and not grouped[g][n].get('version_errors')
                      and (Path(vout)/n/'questions.jsonl').is_file()]
        if not members[g]:
            del members[g]
    included = {s for names in members.values() for s in names}
    # Retain counts/sets only, as status_div does; full proof rows can be large.
    R = {}; validity = collections.defaultdict(collections.Counter)
    for f in sorted(Path(vout).glob('*/questions.jsonl')) if vout else []:
        if f.parent.name not in included:
            continue
        with contextlib.ExitStack() as stack:
            script, meta, facts, curves = {}, {}, {}, {}
            try:
                root = Path(segs)/f.parent.name
                script = json.loads((root/'script.json').read_text())
                meta = json.loads(storage.read_text(root/'facts.json'))
                archive = stack.enter_context(np.load(root/'facts.npz', allow_pickle=False))
                facts = {k: archive[k] for k in ('frame_time_s', 'obs_front_clear_m',
                         'obs_door_projected_height', 'obs_door_occlusion') if k in archive}
                archive = stack.enter_context(np.load(root/'curves.npz', allow_pickle=False))
                curves = {k: archive[k] for k in archive.files if k == 't' or k.endswith(('__u', '__v', '__yaw'))}
            except (OSError, TypeError, ValueError):
                pass  # Rule-specific missing fields are reported as unchecked below.
            stream = stack.enter_context(f.open())
            for line in stream:
                if not line.strip():
                    continue
                r = json.loads(line); v = r['public']['version_id']
                for rule, ok in validity_checks(r, script, meta, facts, curves).items():
                    count = validity[f.parent.name.split('_')[0], rule, v]
                    count['unchecked' if ok is None else 'checked'] += 1
                    count['violations'] += int(ok is False)
                d = R.setdefault((f.parent.name, v), [0, set(), set(), set()])
                d[0] += 1
                d[1].add(json.dumps(r['public'].get('text'), ensure_ascii=False))
                d[2].add(_value(r)); d[3].add(int(_start(r)//10))
    R = {k: [d[0], *(len(x) for x in d[1:])] for k, d in R.items()}
    out = {}
    for g, names in members.items():
        summaries = {s: grouped[g].get(s, {}) for s in names}
        m = out[g] = {'prover.segment_count': len(names),
                      'prover.missing_summary_segments': sum(s not in grouped[g] for s in names),
                      'prover.missing_questions_segments': sum(not vout or not (Path(vout)/s/'questions.jsonl').is_file() for s in names)}
        secs = [s['seconds'] for s in summaries.values() if s.get('seconds') is not None]
        if secs:
            m.update({'prover.sec_median': _med(secs), 'prover.sec_max': max(secs)})
        # 时间优劣按 CPU 秒判:同一代码两次跑墙钟差到 10%(pf1、pf2 c5 中位 40.0、44.2),墙钟只列不判方向。
        cpus = [sum((x or {}).get('cpu_seconds') or 0 for x in s['versions'].values()) for s in summaries.values() if s.get('versions')]
        if cpus:
            m.update({'prover.cpu_sec_median': _med(cpus), 'prover.cpu_sec_max': max(cpus), 'prover.cpu_sec_total': sum(cpus)})
        pub = {v: _med([(summaries[s].get('versions', {}).get(v) or {}).get('publishable') or 0 for s in names]) for v in versions}
        totals = [sum((x or {}).get('publishable') or 0 for x in s.get('versions', {}).values()) for s in summaries.values()]
        m['prover.publishable_count_mean'] = float(statistics.mean(totals))
        m['prover.publishable_count_median'] = _med(totals)
        m['prover.publishable_full_versions'] = sum(x >= 20 for x in pub.values())
        # 候选抽出后才拒的次数,目标 0:全部检查都在抽题前。
        m['prover.post_reject_count'] = sum(n for s in summaries.values() for x in (s.get('versions') or {}).values()
                                            for k, n in ((x or {}).get('reject_reasons') or {}).items()
                                            if not k.startswith(NOT_POST))
        # 抽包之后剔掉的包(Tally.packages 的 leak_check:revealed:*、unwritable、capped:*):不进 reject_reasons,上面数不到
        # (曾有一次对比剔掉 17911 个,post_reject 只记到 1)。比例的分母是抽出造好的包(checked)
        leak = collections.Counter()
        for s in summaries.values():
            for x in (s.get('versions') or {}).values():
                leak.update((x or {}).get('leak_check') or {})
        checked = leak.pop('checked', 0)
        m['prover.leak_drop_count'] = sum(leak.values())
        if checked:
            m['prover.leak_drop_ratio'] = sum(leak.values())/checked
        m.update({f'leak_drop.{k}': n for k, n in sorted(leak.items())})
        # 安排与证明一致:证明器按剧本安排用同一 coverage() 重判(prover/arr_agree.py),目标 1
        rows = [r for s in summaries.values() for r in s.get('arrangements') or []]
        errs = sum('arrangements_error' in s for s in summaries.values())
        if rows or errs:
            m['arr.prover_agree_rows'] = len(rows)
            m['arr.agree_error_segments'] = errs
            if rows:
                m['arr.prover_agree'] = round(sum(r['generator'] == r['prover'] for r in rows)/len(rows), 4)
        # 零损失闸:逐版合计,上线版 >0、新版 0 一律硬退步;中位会把少数段有题的版抹成 0。
        m.update({f'version_total.publishable.{v}': sum((summaries[s].get('versions', {}).get(v) or {}).get('publishable') or 0
                                                         for s in names) for v in versions})
        for v, n in pub.items():
            if n < 20:
                m[f'under20.publishable.{v}'] = n
        # Zero rows for a completed version are measured zero output.
        written_segs = names
        written_vers = versions
        totals = [sum(ds[0] for (seg, _), ds in R.items() if seg == s) for s in written_segs]
        m['prover.written_count_mean'] = float(statistics.mean(totals))
        m['prover.written_count_median'] = _med(totals)
        for i, label in enumerate(('written', 'text', 'answer', 'start_bin10s')):
            vals = {v: _med([R.get((s, v), [0]*4)[i] for s in written_segs]) for v in written_vers}
            if vals:
                m[f'diversity.{label}_median'] = _med(list(vals.values()))
                m[f'diversity.{label}_full_versions'] = sum(x >= 20 for x in vals.values())
        for rule in VALIDITY_RULES:
            for version in versions:
                count = validity[g, rule, version]
                key = f'validity.{rule}.{version}'
                m[key+'.violations'] = count['violations'] if count['checked'] and not count['unchecked'] else None
                m[key+'.checked'], m[key+'.unchecked'] = count['checked'], count['unchecked']
        m['prover.written_full_versions'] = m.get('diversity.written_full_versions', 0)
        for v in versions:
            n = _med([R.get((s, v), [0]*4)[0] for s in written_segs])
            if n < 20:
                m[f'under20.written.{v}'] = n
        for mode, counts in (('publishable', pub), ('written', {
                v: _med([R.get((s, v), [0]*4)[0] for s in written_segs]) for v in versions})):
            families = collections.Counter(v.split('/')[0] for v, n in counts.items() if n < 20)
            m.update({f'under20.{mode}_family.{family}_versions': n for family, n in families.items()})
    return out


def script_digest(segs, only=None):
    """每组指定支持集内剧本(段名、script.json 原字节)的 sha1。"""
    h = collections.defaultdict(hashlib.sha1)
    for f in sorted(Path(segs).glob('*/script.json')) if segs else []:
        if only is not None and f.parent.name not in only:
            continue
        h[f.parent.name.split('_')[0]].update(f.parent.name.encode()+b'\0'+f.read_bytes())
    return {g: x.hexdigest() for g, x in h.items()}


def prover_digest(sha, root=None):
    """报告所声明提交的出题代码指纹;对象缺失时未知,不豁免用时变化。

    保守覆盖领域库、批次适配和问法规格,包含证明器的传递依赖。
    不取当前工作树:统计可以在两臂跑完后由另一份代码执行。
    """
    if not isinstance(sha, str) or not re.fullmatch(r'[0-9a-f]{40}', sha):
        return None
    try:
        run = subprocess.run(['git', '-C', str(root or Path(__file__).resolve().parents[1]),
                              'ls-tree', sha, '--', 'embodied_pipeline', 'np', 'spec/questions'],
                             capture_output=True, check=False)
    except OSError:
        return None
    if run.returncode or len(run.stdout.splitlines()) != 3:
        return None
    return hashlib.sha256(run.stdout).hexdigest()


DEADLINE = re.compile(r"RuntimeError\('deadline:[1-9]\d*/[1-9]\d* 块没做完((?:计算期限已到|--deadline [0-9.e+\-]+ s))'\)")


def expected_versions(catalog):
    sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'spec/questions'))
    from core.catalog_reader import CatalogReader
    return sorted(CatalogReader(catalog=Path(catalog)).active_ids())


def support(segs, logs, vout, arm, expected, versions):
    """Read completed artifacts; only the producer's exact deadline signature is truncation."""
    generated, questioned, truncated, invalid, missing = set(), set(), [], [], []
    for name in expected:
        try:
            text = (Path(logs)/f'{arm}_{name}.log').read_text()
            rc = re.findall(r'^rc=(\d+)$', text, re.M)
            if not rc:
                missing.append(f'{arm}/{name}: generation rc missing'); continue
            if int(rc[-1]) != 0:
                # A recorded generator refusal is a measured failure, not an execution error.
                records = [json.loads(x) for x in text.splitlines() if x.startswith('{')]
                if int(rc[-1]) != 2 or not any(isinstance(x.get('rejected'), str) for x in records):
                    invalid.append(f'{arm}/{name}: generation rc={rc[-1]}')
                continue
            root = Path(segs)/name
            if not isinstance(json.loads((root/'script.json').read_text()), dict):
                raise ValueError('script must be an object')
            if not isinstance(json.loads(storage.read_text(root/'facts.json')), dict):
                raise ValueError('facts metadata must be an object')
            with np.load(root/'facts.npz', allow_pickle=False) as facts:
                for key in facts.files:
                    facts[key]  # Force CRC/data reads, not just the ZIP directory.
            generated.add(name)
        except FileNotFoundError as exc:
            missing.append(f'{arm}/{name}: {exc.filename} missing')
        except (OSError, ValueError, TypeError, KeyError, AttributeError, zipfile.BadZipFile) as exc:
            invalid.append(f'{arm}/{name}: {type(exc).__name__}: {exc}')
    for name in expected:
        # Q is independent of G. A refused segment need not have question output.
        if name not in generated and not (Path(vout)/name/'summary.json').exists():
            continue
        try:
            summary = json.loads((Path(vout)/name/'summary.json').read_text())
            error = summary.get('execution_error')
            if error and isinstance(error, str) and DEADLINE.fullmatch(error) and not summary.get('version_errors'):
                truncated.append(name); continue
            if error or summary.get('version_errors') or any(x.get('execution_error') for x in summary['versions'].values()):
                invalid.append(f'{arm}/{name}: {error or "version execution errors"}'); continue
            if set(summary['versions']) != set(versions):
                missing.append(f'{arm}/{name}: expected versions differ'); continue
            for line in (Path(vout)/name/'questions.jsonl').read_text().splitlines():
                if line.strip() and json.loads(line)['public']['version_id'] not in versions:
                    raise ValueError('unexpected JSONL version')
            questioned.add(name)
        except FileNotFoundError as exc:
            missing.append(f'{arm}/{name}: {exc.filename} missing')
        except (OSError, ValueError, TypeError, KeyError, AttributeError, zipfile.BadZipFile) as exc:
            invalid.append(f'{arm}/{name}: {type(exc).__name__}: {exc}')
    return dict(G=sorted(generated), Q=sorted(questioned), truncated=truncated, invalid=invalid, missing=missing)


def chain(name, segs=None, logs=None, vout=None, arm='base', cfg=None, common=None,
          common_logs=None, common_vout=None, common_arm='new', versions=None, sha=None, common_sha=None):
    expected = sorted(f.stem for f in Path(cfg).glob('*.json')) if cfg else []
    versions = sorted(versions or [])
    reasons = []
    ready = bool(expected and versions and all((segs, logs, vout, common, common_logs, common_vout)))
    arms = [support(*paths, expected, versions) for paths in
            ((segs, logs, vout, arm), (common, common_logs, common_vout, common_arm))] if ready else []
    only = set.intersection(*(set(x[k]) for x in arms for k in ('G', 'Q'))) if arms else set()
    if not ready:
        reasons.append('expected configs/versions or both arms inputs missing')
    invalid = [reason for x in arms for reason in x['invalid']]
    missing = reasons + [reason for x in arms for reason in x['missing']]
    if not only:
        missing.append('common support is empty')
    if not sha or not common_sha:
        missing.append('both full commit SHAs required')
    elif not all(re.fullmatch(r'[0-9a-f]{40}', x) for x in (sha, common_sha)):
        invalid.append('invalid full commit SHA')
    counts = {}
    for g in sorted({s.split('_')[0] for s in expected}):
        group = {s for s in expected if s.split('_')[0] == g}
        c = sorted(group & only)
        counts[g] = dict(E=len(group), C=len(c), C_hash=hashlib.sha256('\n'.join(c).encode()).hexdigest(),
                         arms=[dict(G=len(group & set(x['G'])), Q=len(group & set(x['Q'])),
                                    truncated=sorted(group & set(x['truncated'])),
                                    truncated_count=len(group & set(x['truncated']))) for x in arms])
        if not c:
            missing.append(f'{g}: common support is empty')
    blocks = [gen_stats(logs, arm, expected), check_stats(logs, arm, expected)] if ready else []
    if only:
        blocks += [motion_stats(segs, only), prover_stats(vout, segs, only, versions)]
    groups = sorted({g for block in blocks for g in block})
    return dict(schema='chain-gate/2', name=name, sha=sha, peer_sha=common_sha,
                expected_segments=expected, expected_versions=versions, C=sorted(only), support=counts,
                arms=arms, reasons=invalid+missing, exit_code=3 if invalid else 75 if missing else 2,
                states=dict(structure='FAIL' if invalid else 'PASS',
                            support='NOT_CHECKED' if missing else 'PASS', comparison='NOT_CHECKED'),
                groups={g: {k: v for block in blocks for k, v in block.get(g, {}).items()} for g in groups},
                inputs=script_digest(segs, only), prover_code=prover_digest(sha),
                under20_reasons=under20_reasons(vout, segs, only=only) if only else {},
                arrangements=arrangement_summary(cfg) if cfg else None)


def gate_result(front, new, noise=None):
    """Validate the comparison contract before assigning the gate exit code."""
    invalid, missing = [], []
    for label, report in (('front', front), ('new', new)):
        if report.get('schema') != 'chain-gate/2':
            invalid.append(f'{label}: expected chain-gate/2; regenerate report')
        elif (report.get('exit_code') not in (0, 1, 2, 3, 75)
              or not isinstance(report.get('groups'), dict)
              or not isinstance(report.get('states'), dict)):
            invalid.append(f'{label}: malformed report')
        elif not all(isinstance(report.get(k), str) and re.fullmatch(r'[0-9a-f]{40}', report[k])
                     for k in ('sha', 'peer_sha')):
            invalid.append(f'{label}: full commit SHAs required')
        elif report.get('exit_code') == 3:
            invalid.extend(report['reasons'])
        elif report.get('exit_code') == 75:
            missing.extend(report['reasons'])
    for key in ('expected_segments', 'expected_versions', 'C'):
        if front.get(key) != new.get(key):
            invalid.append(f'{key}: arms differ')
        if not front.get(key):
            missing.append(f'{key}: empty')
    if front.get('sha') != new.get('peer_sha') or new.get('sha') != front.get('peer_sha'):
        invalid.append('arm SHAs do not match peer SHAs')
    if noise and (noise.get('exit_code') in (3, 75) or
                  any(noise.get(k) != front.get(k) for k in ('schema', 'expected_segments', 'expected_versions', 'C'))):
        invalid.append('noise support differs')
    result = chain_compare(front, new, noise) if not invalid and not missing else dict(
        items={}, regressions=[], advantages={}, over_limit=[], drops=[])
    code = 3 if invalid else 75 if missing else 1 if result['regressions'] else 0 if result['advantages'] else 2
    result.update(schema='chain-gate/2', shas=[front.get('sha'), new.get('sha')],
                  expected_segments=front.get('expected_segments', []), expected_versions=front.get('expected_versions', []),
                  C=front.get('C', []), support=[front.get('support'), new.get('support')],
                  arms=[front.get('arms'), new.get('arms')],
                  states=dict(structure='FAIL' if invalid else 'PASS', support='NOT_CHECKED' if missing else 'PASS',
                              comparison='NOT_CHECKED' if invalid or missing else 'FAIL' if code == 1 else 'PASS'),
                  reasons=invalid+missing+result['regressions']+[x for xs in result['advantages'].values() for x in xs]
                          + (['no advantage'] if code == 2 else []), exit_code=code)
    return result


def _counts(d):
    return '、'.join(f'{k} {v:g}' for k, v in d) or '无'


def _axis(k):
    """优势按几个角度归:时间、多样性、自然、题目有效性。"""
    if k.startswith(('gen.sec', 'gen.rejected', 'prover.sec', 'prover.cpu_sec')):     # hum./obs. 的 longest_sec 是静止时长,归自然
        return '时间'
    if k.startswith('diversity.'):
        return '多样性'
    if k.startswith(('hum.', 'obs.', 'check.')):
        return '自然'
    return '有效性'


# 被看见时站着的上限,同生成器放行判据 gen/block.py SEEN_STAND_S(单测核两处相等)
SEEN_STAND_S = 20
# 绝对值超标:两臂都高就不进退步、优势,需单列;只报,不改退出码。
LIMITS = (('obs.still_ratio_median', lambda x, nv: x > .5, '观察者静止占比 >0.5'),
          ('hum.seen_longest_sec_max', lambda x, nv: x > SEEN_STAND_S, f'人形被看见时最长连续静止 >{SEEN_STAND_S} s'),
          ('hum.pause_sec_p90', lambda x, nv: x > PAUSE_P90_S, f'人形停顿时长 p90 >{PAUSE_P90_S:g} s(真人 16.4 s)'),
          ('diversity.answer_full_versions', lambda x, nv: nv and x < nv/2, '答案写满 20 种的版不到一半'))


def chain_compare(front, new, noise=None):
    result = {}; regressions = []; advantages = collections.defaultdict(list); over = []; drops = []
    for g in sorted(set(front['groups']) | set(new['groups'])):
        a, b = front['groups'].get(g, {}), new['groups'].get(g, {})
        c = (noise or {}).get('groups', {}).get(g, {})
        # 只有剧本和已知出题代码都相同才豁免负载噪声;未知身份照常判方向。
        same = (bool(front.get('inputs', {}).get(g))
                and front['inputs'][g] == new.get('inputs', {}).get(g)
                and bool(front.get('prover_code')) and front['prover_code'] == new.get('prover_code'))
        # Known directed metrics also expose blocks absent from both reports.
        for k in sorted(set(a) | set(b) | set(DIRECTIONS)):
            direction = DIRECTIONS.get(k)
            av, bv = a.get(k), b.get(k)
            if k.startswith('validity.'):
                status = '只报(检查分母)'
                if k.endswith('.violations'):
                    prefix = k.removesuffix('.violations')
                    checked = prefix+'.checked'
                    if (av is None or bv is None or not a.get(checked) or a.get(checked) != b.get(checked)
                            or a.get(prefix+'.unchecked', 1) or b.get(prefix+'.unchecked', 1)):
                        status = '不可检(缺字段或检查分母不同)'
                    elif bv > av:
                        status = 'FRONT 好(退步)'; regressions.append(f'{g}.{k}')
                    elif bv < av:
                        status = 'NEW 好'; advantages[_axis(k)].append(f'{g}.{k}')
                    else:
                        status = '持平'
                result[f'{g}.{k}'] = [av, bv, status]
                continue
            if k.startswith('version_total.'):    # only the hard zero-loss gate; other changes show in the aggregate rows
                if (av or 0) > 0 and not bv:
                    regressions.append(f'{g}.{k}')
                    result[f'{g}.{k}'] = [av, bv or 0, '零损失(硬退步)']
                elif (av or 0) > 0 and bv < DROP * av:
                    drops.append(f'{g}.{k.split(".", 2)[2]} {av:g}→{bv:g}')
                continue
            if k.startswith(LEAK_KEYS):           # 抽包后剔包先只报:某因一边没有按 0,不当测量消失
                result[f'{g}.{k}'] = [av or 0, bv or 0, '只报(不判退步)']
                continue
            if k.startswith('gen.rejected.'):     # a refusal reason absent from a report counted none (vs2: 2 -> absent read as lost)
                av, bv = av or 0, bv or 0
                a, b = {**a, k: av}, {**b, k: bv}
            status = '两边都没量'
            if av is not None and bv is None:
                if k.startswith('under20.'):
                    # Conditional diagnostics disappear when a version fills up.
                    status = '条件诊断退出(无方向)'
                else:
                    status = '测量消失(退步)'
                    regressions.append(f'{g}.{k}')
            elif av is None and bv is not None:
                status = '新增'
            elif av is not None and bv is not None:
                status = '持平' if a[k] == b[k] else '无方向'
                if direction and a[k] != b[k] and same and k.startswith(('prover.cpu_sec', 'prover.sec')):
                    status = '输入相同(负载噪声)'
                elif direction and a[k] != b[k]:
                    delta = (b[k]-a[k])*direction
                    floor = abs(a[k]-c[k]) if c.get(k) is not None else LOAD_REL.get(k, 0)*abs(a[k])
                    status = 'NEW 好' if delta > 0 else ('噪声内' if -delta <= floor else 'FRONT 好(退步)')
                    if delta < -floor:
                        regressions.append(f'{g}.{k}')
                    elif delta > floor:
                        advantages[_axis(k)].append(f'{g}.{k}')
            hard = (k == 'arr.agree_error_segments' and (bv or 0) > 0 and f'一致率出错 {bv:g} 段,应为 0(退步)' or
                    k == 'arr.prover_agree' and bv is not None and bv < 1 and f'安排与证明一致率 {bv:g},应为 1(退步)')
            if hard:                                                # 硬闸:不看对上线版的增减
                status = hard
                if f'{g}.{k}' not in regressions:
                    regressions.append(f'{g}.{k}')
            result[f'{g}.{k}'] = [a.get(k), b.get(k), status]
        # 符号检验:可发布数的退步看逐版合计降的版是否显著多于升的版(合计降且 z > Z);
        # 各段合计的中位、均值只展示不定方向——中位会把少数段有题的版抹平。
        vs = [k for k in set(a) | set(b) if k.startswith('version_total.publishable.')]
        dn, up = sum((b.get(k) or 0) < (a.get(k) or 0) for k in vs), sum((b.get(k) or 0) > (a.get(k) or 0) for k in vs)
        z = round((dn-up)/math.sqrt(dn+up), 2) if dn+up else 0.0
        sa, sb = sum(a.get(k) or 0 for k in vs), sum(b.get(k) or 0 for k in vs)
        if vs:
            worse = sb < sa and z > Z
            result[f'{g}.version_total.sign'] = [sa, sb, f'降 {dn} 版、升 {up} 版,z={z:g}' + ('(退步)' if worse else '')]
            if worse:
                regressions.append(f'{g}.version_total.sign')
        nv = sum(k.startswith('version_total.publishable.') for k in b)
        over.extend(f'{g}.{k}={b[k]:g}({text})' for k, bad, text in LIMITS
                    if b.get(k) is not None and bad(b[k], nv))
    return dict(items=result, regressions=regressions, advantages=dict(advantages), over_limit=over, drops=drops)


def _chain_table(data):
    lines = [f'[{g}] 支持集 '+json.dumps(counts, ensure_ascii=False)
             for g, counts in data.get('support', {}).items()]
    for g, metrics in data['groups'].items():
        header = f"[{GROUP_NAMES.get(g, g)}]"
        if 'prover.segment_count' in metrics:
            header += (f" 共 {metrics['prover.segment_count']} 段,"
                       f"缺摘要 {metrics['prover.missing_summary_segments']} 段、"
                       f"缺 questions.jsonl {metrics['prover.missing_questions_segments']} 段")
        lines.append(header)
        if data.get('arrangements') is not None:
            a = data['arrangements'].get(g)
            lines.append(f"安排层:配置 {a['configs']} 份;{_counts(a['arrangements'].items())};"
                         f"观察者 {_counts(a['observer_modes'].items())}" if a else '安排层:--cfg 里没有这组')
        for prefix in ('gen.', 'check.', 'hum.', 'obs.', 'prover.', 'diversity.', 'validity.'):
            xs = [(k, v) for k, v in metrics.items() if k.startswith(prefix)]
            lines.extend(f'{k}: '+('不可检' if v is None else f'{v:g}') for k, v in xs)
            if not xs:
                lines.append(f'{prefix} 没量')
        lines.extend(f'{k}: {v:g}' for k, v in metrics.items() if k.startswith('under20.'))
        reasons = (data.get('under20_reasons') or {}).get(g)
        if reasons:
            lines.append('不足 20 的版,按户型:段数、0 道段数、可发布中位;预筛前三|候选后前三')
            lines.extend(f"  {v} {h}:段 {r['segments']}、0 道 {r['zero_segments']}、可发布中位 {r['publishable_median']:g};"
                         f"预筛 {_counts(r['prefilter'])}|候选后 {_counts(r['post'])}"
                         for v, houses in reasons.items() for h, r in houses.items())
    return '\n'.join(lines) or '没量'


def main(argv=None):
    p = argparse.ArgumentParser(prog='np.batch_stats')
    p.add_argument('dirs', nargs='*')
    p.add_argument('--compare', nargs=2, metavar=('VOUT_A', 'VOUT_B'))
    p.add_argument('--noise')
    p.add_argument('--json')
    p.add_argument('--chain')
    p.add_argument('--chain-compare', nargs=2)
    p.add_argument('--segs')
    p.add_argument('--logs')
    p.add_argument('--vout')
    p.add_argument('--arm', default='base')
    p.add_argument('--cfg')
    p.add_argument('--segdist', action='store_true', help='只读成段耗时与失败分布;需 --run')
    p.add_argument('--run')
    p.add_argument('--shortfall', action='store_true', help='附加时段档×能力组×住宅缺口;需 --cfg 单段配置目录')
    p.add_argument('--common-segs', help='另一臂的段目录')
    p.add_argument('--common-logs')
    p.add_argument('--common-vout')
    p.add_argument('--common-arm', default='new')
    p.add_argument('--sha')
    p.add_argument('--common-sha')
    p.add_argument('--versions', help='本轮固定版本,逗号分隔;缺省取 catalog 现行版本')
    p.add_argument('--catalog', default=str(Path(__file__).resolve().parents[1]/'spec/questions/catalog.json'))
    args = p.parse_args(argv)
    if args.chain or args.chain_compare:
        try:
            if args.chain_compare:
                data = gate_result(*(json.loads(Path(f).read_text()) for f in args.chain_compare),
                                     noise=json.loads(Path(args.noise).read_text()) if args.noise else None)
                text = '\n'.join(f'{k}: {a} | {b} | {status}' for k, (a, b, status) in data['items'].items())
                text += '\n退步:' + ', '.join(data['regressions'])
                text += ''.join(f'\n优势({axis}):' + ', '.join(ks) for axis, ks in data['advantages'].items())
                text += '\n超标(新臂绝对值):' + (', '.join(data['over_limit']) or '无')
                text += f'\n大跌报警(逐版合计 < FRONT×{DROP}):' + (', '.join(data['drops']) or '无')
                if data['exit_code'] == 2:
                    text += '\n无优势:没有一项超出噪声地好过上线版,回头查设计和规划'
            else:
                data = chain(args.chain, args.segs, args.logs, args.vout, args.arm, args.cfg, args.common_segs,
                             args.common_logs, args.common_vout, args.common_arm,
                             args.versions.split(',') if args.versions else expected_versions(args.catalog), args.sha, args.common_sha)
                text = _chain_table(data)
        except (OSError, ValueError, TypeError, KeyError, AttributeError, IndexError, zipfile.BadZipFile) as exc:
            data = dict(schema='chain-gate/2', shas=[args.sha, args.common_sha], expected_segments=[],
                        expected_versions=[], C=[], support={}, exit_code=3,
                        states=dict(structure='FAIL', support='NOT_CHECKED', comparison='NOT_CHECKED'),
                        reasons=[f'{type(exc).__name__}: {exc}'])
            text = '运行无效'
        text += '\n结论:' + json.dumps(data['states'], ensure_ascii=False)
        text += '\n原因:' + '; '.join(data['reasons'])
        if args.json:
            Path(args.json).write_text(json.dumps(data, ensure_ascii=False, indent=1))
        print(text)
        return data['exit_code']

    if args.segdist:
        if not args.run:
            p.error('--segdist 需要 --run')
        data = segdist(args.run)
    elif args.compare:
        data = compare(*args.compare, noise=args.noise)
    elif len(args.dirs) == 2:
        data = summarize(*args.dirs)
        if args.shortfall:
            if not args.cfg:
                p.error('--shortfall 需要 --cfg 单段配置目录')
            data['三维缺口'] = shortfall(*args.dirs, args.cfg)
    else:
        p.error('要么给 OUT VOUT,要么给 --compare VOUT_A VOUT_B')
    text = json.dumps(data, ensure_ascii=False, indent=1, default=str)
    if args.json:
        Path(args.json).write_text(text)
    print(text)
    return 0


if __name__ == '__main__':
    sys.exit(main())