File size: 142,588 Bytes
02039a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""score_tables.py -- reproduce the AndroidFlux paper tables from evaluation outputs.

This is the scoring entry point for the public release
``Gyubeum/AndroidFlux_Evaluation_Output``.  It takes ONE input -- the root of the
Evaluation_Output tree -- and emits the four paper tables in Markdown and LaTeX:

    tab:hvlvcomparison   Human-verified vs. LLM-verified, 6 models
    tab:modelclass       Failure recovery across agent architectures, 11 models
    tab:instreason       Instruct vs. explicit-CoT reasoning at t
    tab:aw-vs-recovery   AndroidWorld(116) vs. Scratch(80) vs. t_all(80), 26 models

--------------------------------------------------------------------------------
Expected layout of the Evaluation_Output root (``--root``)
--------------------------------------------------------------------------------

    Evaluation_Output/
      androidworld/<model>/              sr_summary.json  per_task.json
      human_verified/
        replay_65/<cond>/<model>/        validation.json  per_episode.json  episodes/<task>/
        snapshot_15/<cond>/<model>/      "
      llm_verified/
        replay_312/<cond>/<model>/       "
      scripts/score_tables.py
      README.md

    <cond> in: clean t_minus_5 t_minus_3 t_minus_1 t t_plus_1_pos t_plus_1_neg

Sharding is a run-time detail and is NOT part of the published layout: the
producer flattens ``shards/shard_0N/<task>/`` into ``episodes/<task>/``.
``app_data_cache/`` is emulator scratch, not a result, and is not published.

--------------------------------------------------------------------------------
Adapter mode (``--adapter hf`` / ``--adapter legacy``) -- retired
--------------------------------------------------------------------------------

Before this repository existed, the same table code read the two pre-release
repositories the cells were later migrated from:

    Gyubeum/AndroidFlux_Failure_Recovery_Eval   HV replay/snapshot/t+1, LV subset
    Gyubeum/AndroidFlux_results                 LV error_t, t-3/t-5, human_verified_80

Those layouts are no longer published: ``AndroidFlux_Failure_Recovery_Eval`` is now
``AndroidFlux_Failure_Recovery_Eval_Agent`` and carries only the inputs, and
``AndroidFlux_results`` was removed.  ``--adapter hf`` / ``--adapter legacy`` and
``LEGACY_PATHS`` are kept only as a record of where each cell came from (see
``MANIFEST.json:provenance``); the default mode, which reads this repository, is
the one to use.

AndroidWorld(116) runs live on the evaluation boxes, not on the Hub, so the
adapter cannot see them.  Point ``--aw-root`` at a directory holding
``**/sr_summary.json`` to fill the AndroidWorld table; without it every
AndroidWorld cell is reported as missing rather than silently dropped.

Usage
-----
    # every paper table, Markdown + LaTeX
    python3 score_tables.py --root /path/to/Evaluation_Output --all

    # one table, by paper label
    python3 score_tables.py --root ... --table tab:hvlvcomparison
    python3 score_tables.py --root ... --table tab:aw-vs-recovery

    # one cell, with the full derivation printed
    python3 score_tables.py --root ... \
        --cell human_verified/replay_65/t_plus_1_pos/ma3_32b --explain

    # machine-readable
    python3 score_tables.py --root ... --all --format json > tables.json
    python3 score_tables.py --root ... --all --format latex

    # gate before publishing: recompute every cell, fail on any disagreement
    python3 score_tables.py --root ... --verify

    # read the current repositories instead of the released tree
    python3 score_tables.py --adapter hf --all --aw-root ~/results
    python3 score_tables.py --adapter hf --compare-paper main.md
    python3 score_tables.py --adapter hf --audit

The Hugging Face token is read from the environment (HF_TOKEN /
HUGGINGFACE_HUB_TOKEN) or from a token FILE (``--token-file``, default
``~/.hf_token``).  The token itself is never accepted on argv.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import sys
import glob as globmod

# ==============================================================================
# 1.  SCORING RULES -- the two rules are different, and both are correct.
# ==============================================================================
#
# A recovery episode can score 0.0, 0.5 or 1.0.  The two artifact families in
# this project disagree about what a 0.5 means, and the paper reports whatever
# each artifact itself reported.  Encoding the disagreement here (instead of
# "fixing" one side) is what makes the numbers reproducible.
#
#   validation.json  (human-verified + LLM-verified replay/snapshot evaluations)
#       success  <=>  score > 0        -- a 0.5 counts as a SUCCESS.
#       The recovery harness treats a partially-credited task as recovered:
#       the agent got out of the injected failure state even if the AndroidWorld
#       checker only awarded partial credit.  ``success_count`` in the file is
#       produced with this rule.
#
#   sr_summary.json  (AndroidWorld 116-task clean-start runs)
#       success  <=>  score >= 1       -- a 0.5 counts as a FAILURE.
#       This is upstream AndroidWorld semantics, reproduced by
#       summarize_eval_sr.py (``score > 0.5`` on a {0, 0.5, 1} scale), and it is
#       the rule behind ``d["total"]["successes"]``.
#
# Cells where this actually bites (0.5 present):
#       qwen3vl_2b / t_rep     >0 = 8   >=1 = 7    paper 12.3 = 8/65
#       gui_owl_32b / t_rep    >0 = 14  >=1 = 13   paper 21.5 = 14/65
#       ma3_7b AndroidWorld    >0 = 79  >=1 = 78   paper successes = 78
#
SCORING = {
    "validation": "score > 0",   # HV / LV validation.json  (0.5 == success)
    "sr_summary": "score >= 1",  # AndroidWorld sr_summary.json (0.5 == failure)
}


def _score_of(record):
    """Numeric score of one episode record, or None when absent/NaN."""
    # Take the first key that is PRESENT AND NON-NULL.  Stopping at the first
    # key that merely exists loses the verdict whenever a producer writes
    # ``score: null`` beside a populated ``is_successful`` -- measured on a
    # published per_task.json where every record read {"score": null,
    # "is_successful": 1.0}, which scored the whole run 0/80 with no warning:
    # each record looked like an unscored episode rather than a successful one.
    #
    # A record whose keys are all null is still None -- an episode that produced
    # no verdict is a failure, and must not be dropped from the denominator.
    value = None
    for key in ("score", "is_successful", "success_score"):
        if record.get(key) is not None:
            value = record[key]
            break
    if value is None:
        return None
    if isinstance(value, bool):
        return 1.0 if value else 0.0
    try:
        value = float(value)
    except (TypeError, ValueError):
        return None
    if value != value:  # NaN
        return None
    return value


def is_success_validation(record):
    """SCORING["validation"] -- score > 0."""
    score = _score_of(record)
    return score is not None and score > 0.0


def is_success_sr_summary(record):
    """SCORING["sr_summary"] -- score >= 1."""
    score = _score_of(record)
    return score is not None and score >= 1.0


# TRAP: an entry's identity is its EPISODE, never its (source_model, task_name).
# llm_verified/replay_312 breaks that assumption -- ``task_name`` there is the
# RAW LLM-verified trajectory name, and one raw name can carry two different
# AndroidWorld templates.  In EVERY published LV cell these two pairs are two
# DISTINCT episodes each:
#   gemma_31b_m3a_gemma31b_improved_0716_4env / In_Simple_Calendar_Pro_create__worker_4
#       __00159_  SimpleCalendarAddOneEvent    __00171_  SimpleCalendarAddRepeatingEvent
#   gemma_31b_m3a_gemma_31b_m3a_4env          / In_Simple_Calendar_Pro_create__worker_4
#       __00160_  SimpleCalendarAddOneEvent    __00172_  SimpleCalendarAddRepeatingEvent
# Keying on the pair turns 312 entries into 310, and in 17 of the 42 collisions
# across the 21 published cells the two rows carry OPPOSITE verdicts (0.0 / 1.0),
# so whichever row survives decides the numerator.  Measured: all 21 LV cells
# move, by up to 0.30 pp -- five times the default --tolerance.  human_verified
# is immune (task_name is unique in all 211 published HV files), but the key is
# wrong there too, so it is used only as a last resort and never silently.
def episode_id_of(record):
    """Stable per-episode identity of one row, or None.

    ``results.json`` carries ``episode_dir`` and ``steps.jsonl`` carries
    ``episode``; they hold the same string, and that is what those two files
    join on.  ``validation.json`` carries neither, but its ``result_path`` ends
    in ``<episode_dir>/episode_result.json``, so the identity is recoverable --
    serial number included, which is exactly the part (source_model, task_name)
    throws away.
    """
    for key in ("episode_dir", "episode", "episode_id"):
        val = record.get(key)
        if val:
            return os.path.basename(str(val).rstrip("/"))
    path = record.get("result_path") or record.get("path")
    if path:
        return os.path.basename(os.path.dirname(str(path).rstrip("/")))
    return None


def check_entry_identity(rows, where, notes):
    """Re-derive entry identity instead of trusting the file's own bookkeeping.

    ``duplicates: []`` is only the producer's claim, and a file can carry the
    right ROW COUNT while one episode appears twice and another is absent --
    something ``len(rows)`` can never see, and which no existing check catches
    because the header agrees and the denominator is right.
    """
    ids = [episode_id_of(r) for r in rows]
    strong = [x for x in ids if x is not None]
    if not strong:
        # Older schema variant: no episode field and no result_path on any row
        # (73 of the published human_verified files).  Fall back to the pair
        # key, adequate ONLY while it stays unique -- true in every published
        # HV file.  Should it ever collide here, the file cannot tell a real
        # duplicate from two episodes sharing a raw task name, so say so
        # rather than pick one.
        pairs = set((r.get("source_model"), r.get("task_name")) for r in rows)
        if len(pairs) != len(rows):
            notes.append("ambiguous_entries")
            DIAG.warn("ENTRY_AMBIGUOUS", where,
                      "no episode_dir/result_path on any row and "
                      "(source_model, task_name) is not unique (%d rows, %d "
                      "pairs): entry identity cannot be established"
                      % (len(rows), len(pairs)))
        return
    counts = {}
    for x in strong:
        counts[x] = counts.get(x, 0) + 1
    if len(strong) != len(rows):
        DIAG.warn("PARTIAL_EPISODE_ID", where,
                  "%d of %d rows carry no episode identity; uniqueness was "
                  "checked over the %d that do"
                  % (len(rows) - len(strong), len(rows), len(strong)))
    repeated = sorted(k for k, v in counts.items() if v > 1)
    if repeated:
        notes.append("duplicate_entries")
        DIAG.error("ENTRY_NOT_UNIQUE", where,
                   "%d rows resolve to only %d distinct episodes -- an episode "
                   "is counted twice and another is absent: %s"
                   % (len(strong), len(counts), ", ".join(repeated[:4])
                      + (" ..." if len(repeated) > 4 else "")))
    # Recorded, not acted on: the pair key WOULD have been wrong here.  This is
    # the llm_verified 312 -> 310 trap, and the count is right precisely
    # because the pair key was not used.
    if all("source_model" in r and "task_name" in r for r in rows):
        naive = set((r["source_model"], r["task_name"]) for r in rows)
        if len(naive) < len(counts):
            DIAG.info("NAIVE_KEY_COLLIDES", where,
                      "(source_model, task_name) would collapse %d episodes to "
                      "%d; the entry key is the episode dir, not that pair"
                      % (len(counts), len(naive)))


SUCCESS_FN = {
    "validation": is_success_validation,
    "sr_summary": is_success_sr_summary,
}

# ==============================================================================
# 2.  DENOMINATORS
# ==============================================================================
#
# Denominators are READ FROM THE FILES (rows length / result_count / episode
# count).  The table below is only the expectation used to raise a warning when
# a file disagrees -- it is never substituted for the measured value.
#
# The one hard-coded denominator is AndroidWorld: the run is scored over the
# fixed 116-task suite, including the ~6 tasks that raise environment
# exceptions, so a run that loaded 115 episodes still reports out of 116.
#
AXIS_AW = "androidworld"
AXIS_HV_REP = "human_verified/replay_65"
AXIS_HV_SNAP = "human_verified/snapshot_15"
AXIS_LV = "llm_verified/replay_312"

CONDS = ["clean", "t_minus_5", "t_minus_3", "t_minus_1", "t",
         "t_plus_1_pos", "t_plus_1_neg"]

EXPECTED_DENOM = {
    (AXIS_HV_REP, "clean"): 65,
    (AXIS_HV_REP, "t_minus_5"): 65,   # clipped episodes are NOT dropped ...
    (AXIS_HV_REP, "t_minus_3"): 65,   # ... they are mapped to a clean start
    (AXIS_HV_REP, "t_minus_1"): 65,
    (AXIS_HV_REP, "t"): 65,
    (AXIS_HV_REP, "t_plus_1_pos"): 52,
    (AXIS_HV_REP, "t_plus_1_neg"): 52,
    (AXIS_HV_SNAP, "clean"): 15,
    (AXIS_HV_SNAP, "t_minus_1"): 15,
    (AXIS_HV_SNAP, "t"): 15,
    # Both LV conditions are scored over the full 312 entries (104 tasks x 3
    # source trajectories).  A clean-start rate is entry-independent, so the
    # same rate also falls out of the 104 unique tasks -- k/104 == 3k/312 -- but
    # the published denominator is 312 and that is what a file must carry.
    (AXIS_LV, "clean"): 312,
    (AXIS_LV, "t"): 312,
}

# Registry self-check.  Two edits to AW_RUNS have gone wrong in ways nothing else
# catches, so both are asserted at import:
#
#   1. A second "model": [...] entry silently SHADOWS the first -- Python keeps the
#      last one.  A canonical run appended as a fresh key once replaced a 15-entry
#      candidate list with a 1-entry one, and a row that matched the paper to the
#      decimal rendered n/a with no warning naming the loss.  Duplicate literal keys
#      cannot be detected after the dict is built, so the source text is scanned.
#
#   2. A list holding ONLY its canonical run has no fallback: if that directory is
#      not staged the row disappears instead of degrading to a published-value
#      match with AW_NON_CANONICAL_RUN.  Registering a canonical run must ADD to the
#      list, never replace it.
def _audit_aw_runs():
    import re as _re, collections as _c, io as _io, os as _os
    src = _os.path.abspath(__file__)
    try:
        text = _io.open(src, encoding="utf-8").read()
    except OSError:
        return
    blk = _re.search(r'^AW_RUNS = \{\n(.*?)^\}\n', text, _re.S | _re.M)
    if blk:
        keys = _re.findall(r'^\s{4}"([^"]+)":', blk.group(1), _re.M)
        dupes = sorted(k for k, n in _c.Counter(keys).items() if n > 1)
        if dupes:
            raise AssertionError(
                "AW_RUNS has duplicate keys %s -- the later entry shadows the "
                "earlier one and its candidate runs are lost" % dupes)
    thin = sorted(k for k, v in AW_RUNS.items() if len(v) == 1)
    for k in thin:
        DIAG.info("AW_RUNS_NO_FALLBACK", k,
                  "only one run is registered ('%s'); if it is not staged the row "
                  "renders n/a rather than falling back to another run that "
                  "reproduces the published columns" % AW_RUNS[k][0])


AW_DENOM = 116          # fixed by the suite, exceptions included
SCRATCH80_DENOM = 80    # AndroidWorld run restricted to the 80 recovery tasks
T_ALL_DENOM = 80        # 65 replay + 15 snapshot, disjoint
T_PLUS_1_ALL_DENOM = 104  # 52 positive + 52 negative

# t-3 / t-5 keep denominator 65; how many episodes actually have a deep enough
# prefix is reported as an auxiliary figure only (paper section "subset").
FEASIBLE = {"t_minus_1": 65, "t_minus_3": 39, "t_minus_5": 21}

# Cross-check list for the 80 recovery tasks.  The set is DERIVED from the data
# (union of the replay_65 and snapshot_15 task names); this constant only backs
# a warning when the derivation disagrees, and a fallback when no HV cell could
# be read at all.  A derived set of 79 means a v3_14-era snapshot manifest was
# used -- the missing task is SimpleCalendarDeleteEvents.
TASKS_80_REFERENCE = [
    "AudioRecorderRecordAudioWithFileName", "BrowserDraw", "BrowserMaze",
    "BrowserMultiply", "CameraTakePhoto", "CameraTakeVideo",
    "ClockStopWatchPausedVerify", "ClockTimerEntry", "ContactsAddContact",
    "ContactsNewContactDraft", "ExpenseAddMultiple",
    "ExpenseAddMultipleFromGallery", "ExpenseAddMultipleFromMarkor",
    "ExpenseAddSingle", "ExpenseDeleteDuplicates",
    "ExpenseDeleteDuplicates2", "ExpenseDeleteMultiple",
    "ExpenseDeleteMultiple2", "MarkorAddNoteHeader",
    "MarkorChangeNoteContent", "MarkorCreateFolder", "MarkorCreateNote",
    "MarkorCreateNoteAndSms", "MarkorCreateNoteFromClipboard",
    "MarkorDeleteAllNotes", "MarkorDeleteNewestNote", "MarkorEditNote",
    "MarkorMergeNotes", "MarkorMoveNote", "MarkorTranscribeReceipt",
    "MarkorTranscribeVideo", "OsmAndFavorite", "OsmAndMarker",
    "RecipeAddMultipleRecipes", "RecipeAddMultipleRecipesFromImage",
    "RecipeAddMultipleRecipesFromMarkor",
    "RecipeAddMultipleRecipesFromMarkor2", "RecipeAddSingleRecipe",
    "RecipeDeleteDuplicateRecipes", "RecipeDeleteDuplicateRecipes2",
    "RecipeDeleteDuplicateRecipes3", "RecipeDeleteMultipleRecipesWithNoise",
    "RetroCreatePlaylist", "RetroPlayingQueue", "RetroPlaylistDuration",
    "RetroSavePlaylist", "SaveCopyOfReceiptTaskEval",
    "SimpleCalendarAddOneEvent", "SimpleCalendarAddOneEventInTwoWeeks",
    "SimpleCalendarAddOneEventRelativeDay",
    "SimpleCalendarAddOneEventTomorrow", "SimpleCalendarAddRepeatingEvent",
    "SimpleCalendarDeleteEvents", "SimpleCalendarDeleteEventsOnRelativeDay",
    "SimpleCalendarEventsInNextWeek", "SimpleCalendarEventsInTimeRange",
    "SimpleCalendarNextMeetingWithPerson", "SimpleDrawProCreateDrawing",
    "SimpleSmsReply", "SimpleSmsReplyMostRecent", "SimpleSmsResend",
    "SimpleSmsSend", "SimpleSmsSendClipboardContent",
    "SimpleSmsSendReceivedAddress", "SportsTrackerActivitiesCountForWeek",
    "SportsTrackerActivitiesOnDate", "SportsTrackerLongestDistanceActivity",
    "SportsTrackerTotalDistanceForCategoryOverInterval",
    "SportsTrackerTotalDurationForCategoryThisWeek",
    "SystemBluetoothTurnOff", "SystemBrightnessMax", "SystemBrightnessMin",
    "SystemWifiTurnOffVerify", "TasksCompletedTasksForDate",
    "TasksDueNextWeek", "TasksHighPriorityTasks",
    "TasksHighPriorityTasksDueOnDate", "TurnOffWifiAndTurnOnBluetooth",
    "TurnOnWifiAndOpenApp", "VlcCreateTwoPlaylists",
]

# ==============================================================================
# 3.  MODEL REGISTRY
# ==============================================================================
#
# TRAP: a directory name is not a model key.  The published trees use three
# different naming schemes for the same model, e.g.
#     gemini_3_0_flash_preview_qwen_prompt_think_on   (HV publish key)
#     gemini_3_0_flash_preview_qwen_prompt            (LV key; bare == think_on)
#     mobile_run_gf30                                 (in-run model_key)
# In the released Evaluation_Output every axis uses the single canonical ``id``.
# ``dirs`` is the alias table the ADAPTER needs for the current repositories.
#
# TRAP: never resolve a cell by matching its value.  15/52 exists under
# qwen3vl_2b/positive and under qwen3vl_4b/negative; 28/65 exists under
# guiowl15_8b_think/clean and is also the value someone copied into mai_ui_8b.
# (model, condition) is fixed first, from this table, and only then read.

def M(mid, label, mtype=None, hv=None, lv=None, aw=None, note=None):
    return {
        "id": mid,
        "label": label,
        "type": mtype,
        "dirs": {
            AXIS_HV_REP: hv or mid,
            AXIS_HV_SNAP: hv or mid,
            AXIS_LV: lv or mid,
            AXIS_AW: aw or mid,
        },
        "note": note,
    }


MODELS = {m["id"]: m for m in [
    M("qwen3vl_2b", "Qwen3-VL-2B-Instruct", "General"),
    M("qwen3vl_4b", "Qwen3-VL-4B-Instruct", "General"),
    M("qwen3vl_8b", "Qwen3-VL-8B-Instruct", "General"),
    M("qwen3vl_30b_a3b", "Qwen3-VL-30B-A3B-Instruct", "General"),
    M("qwen3vl_32b", "Qwen3-VL-32B-Instruct", "General"),
    M("qwen3vl_4b_think", "Qwen3-VL-4B-Thinking", "Reasoning"),
    M("qwen3vl_8b_think", "Qwen3-VL-8B-Thinking", "Reasoning"),
    M("qwen3vl_32b_think", "Qwen3-VL-32B-Thinking", "Reasoning"),
    M("gemma_4_31b_it_improved_m3a_think_off", "Gemma-4-31B-IT (M3A)", "General",
      lv="gemma_31b_improved",
      note="paper 'Gemma-4-31B-IT (M3A)' == the improved M3A checkpoint, thinking off"),
    M("gemma_4_31b_it_m3a_think_on", "Gemma-4-31B-IT (M3A, think on)", "Reasoning",
      lv="gemma_31b_improved_think_on"),
    M("gemini_3_0_flash_preview_qwen_prompt_think_on", "Gemini Flash 3.0", "General",
      lv="gemini_3_0_flash_preview_qwen_prompt",
      note="tab:hvlvcomparison / tab:modelclass 'Gemini Flash 3.0' == think ON; "
           "the LV directory without a suffix is the think-on run"),
    M("gemini_3_0_flash_preview_qwen_prompt_think_off",
      "Gemini Flash 3.0 (Qwen3-VL prompt, think off)", "General",
      lv="gemini_3_0_flash_preview_qwen_prompt_think_off",
      note="tab:instreason 'Instruct' column for Gemini Flash 3.0"),
    M("gemini_3_5_flash_qwen_prompt", "Gemini Flash 3.5 (Qwen3-VL prompt)", "General"),
    M("gemini_3_5_flash_computer_use_task_only", "Gemini Flash 3.5 Computer Use", "Expert",
      lv="gemini_computer_use"),
    M("gui_owl_7b", "GUI-Owl-7B", "Expert"),
    M("gui_owl_32b", "GUI-Owl-32B", "Expert"),
    M("guiowl15_2b", "GUI-Owl-1.5-2B", "Expert"),
    M("guiowl15_4b", "GUI-Owl-1.5-4B", "Expert"),
    M("guiowl15_8b", "GUI-Owl-1.5-8B", "Expert"),
    M("guiowl15_32b", "GUI-Owl-1.5-32B", "Expert"),
    M("guiowl15_8b_think", "GUI-Owl-1.5-8B-Thinking", "Reasoning"),
    M("guiowl15_32b_think", "GUI-Owl-1.5-32B-Thinking", "Reasoning"),
    M("mai_ui_2b", "MAI-UI-2B", "Expert"),
    M("mai_ui_8b", "MAI-UI-8B", "Expert"),
    M("ma3_7b", "Mobile-Agent-v3-7B", "Agent"),
    M("ma3_32b", "Mobile-Agent-v3-32B", "Agent"),
    M("mobilerun_gemini_flash_3.0", "MobileRun (Gemini Flash 3.0)", "Agent",
      lv="mobilerun_gemini_flash"),
    M("gemini_3_0_flash_preview_final_run_appinfo_from_gui_owl",
      "FinalRun (M3A + app knowledge)", "Agent", lv="final_run_appinfo"),
    # --- four models added 2026-09 ------------------------------------------
    # Registered 2026-09-09.  The four
    # are Qwen3.8-27B, Qwen3.6-27B, Gemini 3.8 Flash, Gemini 3.1 Pro.  Each
    # reasoning model is a SEPARATE row, not a flag on the instruct row --
    # tab:instreason pairs them as two rows, and the published cell keys already
    # carry the think_on/think_off suffix.
    #
    # think_on/think_off must be read from the RUN, never from the local model
    # key: the same local key `mobile_run_gf30` was measured serving both a
    # think-off and a think-unspecified run on a separate box, so a key-to-variant
    # table silently merges two different cells.
    M("qwen38_27b_think_off", "Qwen3.8-27B", "General"),
    M("qwen38_27b_think_on", "Qwen3.8-27B (think on)", "Reasoning"),
    M("qwen36_27b_think_off", "Qwen3.6-27B", "General"),
    M("qwen36_27b_think_on", "Qwen3.6-27B (think on)", "Reasoning"),
    M("gemini_3_8_flash", "Gemini Flash 3.8", "General"),
    M("gemini_3_1_pro", "Gemini Pro 3.1", "General"),
    M("ui_tars_7b_sft", "UI-TARS-1.0-7B-SFT", "Expert"),
    M("ui_tars_1_5_7b", "UI-TARS-1.5-7B", "Expert"),
]}

#: Extra directory names to try for ONE (model, axis, condition) after the
#: model's normal alias.  The publisher renamed some cells mid-project, so the
#: same model appears under a different directory in a single condition.
#: Ordered best-first; the entry that passed its contract comes first.
DIR_ALIASES = {
    ("gemma_4_31b_it_improved_m3a_think_off", AXIS_HV_REP, "t_plus_1_neg"): [
        "gemma_4_31b_it_0716_improved_m3a",  # valid=True
        "gemma_31b_improved",                # same 19/52, valid=False
    ],
}

# NOT an alias -- ``qwen3vl_8b.dup1``.
# This table holds ONLY the case its docstring describes: the publisher renamed
# one cell, so the same run appears under a different directory.  dup1 is not a
# rename, it is a SEPARATE RUN on a different workstation -- FRE commit
# 1b555249 ("Put qwen3vl_8b.dup1 back -- it was not a copy") records dup1 at
# 65 episodes / 1018 steps against qwen3vl_8b's 65 / 1357, with an identical
# action sequence on only 9 of 65.  Commit 599d7a31 then withdrew dup1 a second
# time ("the other run is the one to keep"); it reappeared at HEAD only because
# a later bulk re-export resurrected it.
# Wiring it in as an alias would put that withdrawn run's 29/65 = 44.62 into the
# paper's 38.5 slot with no flag on it.  So the value is left empty and only the
# REASON is corrected, via LEGACY_ABSENT_CELL below.

# AndroidWorld run directory names, where the canonical run is known.  The
# appendix caption requires AndroidWorld(116) and Scratch(80) to come from the
# SAME run, so a run is named here, never selected by matching a value.
# Rows the paper cannot source from a single run are registered in AW_DISPUTED
# below, which also records WHICH way the row fails (see the verification record).
# NOTE on run names: androidworld/ is keyed by RUN, and one box carries 10-16 runs for
# the same model, so a short name like "qwen3vl_2b_4env" collides across five of
# them.  Runs staged from that box therefore carry
# <model>_<envs>__<inner_stamp>[__<outer_run>].  The outer run name is REQUIRED:
# two different outer runs were measured to share one inner stamp
# (guiowl15_4b_20260707_063747 and _044149 both hold docker_qwen_eval_20260706_162945),
# and a run_id built from the inner stamp alone silently OVERWROTE one of them
# during a staging build.  Never key a run on the inner timestamp alone.
#
# Order is significant -- _aw_dir() returns the FIRST directory that exists, so
# the canonical run leads.  "canonical" means the run reproduces BOTH published
# columns (AndroidWorld total AND Scratch(80)); a run matching only the total is
# NOT canonical and must not lead, because Scratch(80) is the sole tie-breaker
# between same-total runs (measured twice: qwen3vl_2b 33/116 with s80 13 vs 11,
# qwen3vl_4b 51/116 with s80 21 vs 23 -- the paper carries 13 and 21).
#
# TRAP: entries tagged FLOOR below report coverage=1.0 and exceptions=0, so the
# scorer reads them as healthy cells, but their raw_response is 100% empty
# (ConnectionResetError against the serving host).  AW 7 / s80 1 is the value of
# a run that answered nothing, not of a model.  They are listed so the run is
# accounted for, and ordered last so they can never lead.
AW_RUNS = {
    "qwen3vl_2b": [
        # CANONICAL 33/13.  TWO runs on TWO boxes reproduce BOTH published columns;
        # s65 breaks the tie -- 10 here against 8 for the run below, higher wins.
        # The other run stays second on purpose: it also yields 33/13, so if this
        # directory is not staged the row still renders the published value (with a
        # non-canonical warning) instead of vanishing.  A canonical entry must never
        # be the ONLY entry -- replacing the list with it once turned a row that
        # matched the paper to the decimal into a silent n/a.
        "docker_qwen_eval_qwen3vl_2b_4env__qwen3vl_2b_4env",
        "qwen3vl_2b_4env__20260618_195226",   # 33/13 s65 8 -- same published pair
        "qwen3vl_2b_1env__20260712_041204__qwen3vl_2b_20260711_111458",   # AW 40 s80 18
        "qwen3vl_2b_4env__20260619_041403",                               # AW 39 s80 19
        "qwen3vl_2b_1env__20260712_081516__qwen3vl_2b_20260711_111458",   # AW 38 s80 16
        "qwen3vl_2b_4env__20260620_124459",                               # AW 37 s80 16
        "qwen3vl_2b_1env__20260712_161840__qwen3vl_2b_20260711_111458",   # AW 37 s80 17
        "qwen3vl_2b_1env__20260711_155904__qwen3vl_2b_20260711_111458",   # AW 36 s80 14
        "qwen3vl_2b_1env__20260712_202314__qwen3vl_2b_20260711_111458",   # AW 36 s80 13
        "qwen3vl_2b_1env__20260712_121139__qwen3vl_2b_20260711_111458",   # AW 35 s80 15
        "qwen3vl_2b_1env__20260711_200324__qwen3vl_2b_20260711_111458",   # AW 34 s80 14
        "qwen3vl_2b_1env__20260712_000735__qwen3vl_2b_20260711_111458",   # AW 33 s80 11 -- same total, WRONG s80
        "qwen3vl_2b_4env__20260618_102820",                               # AW 21 s80 6
        "qwen3vl_2b_1env__20260711_152622__qwen3vl_2b_20260711_111458",   # AW 8  s80 1
        "qwen3vl_2b_8env__20260619_030852",                               # AW 3  s80 1 (exceptions 106)
        "qwen3vl_2b_4env",                                                # legacy short name
    ],
    "qwen3vl_4b": [
        "docker_qwen_eval_qwen3vl_4b_4env__qwen3vl_4b_4env",   # CANONICAL (confirmed against Table 8)
        # canonical: AW 51 (paper) AND s80 21 (paper)
        "qwen3vl_4b_1env__20260712_203007__qwen3vl_4b_20260711_111458",
        "qwen3vl_4b_4env__20260619_055700",                               # AW 54 s80 23
        "qwen3vl_4b_4env__20260620_142354",                               # AW 53 s80 23
        "qwen3vl_4b_1env__20260712_120149__qwen3vl_4b_20260711_111458",   # AW 51 s80 23 -- same total, WRONG s80
        "qwen3vl_4b_1env__20260712_075839__qwen3vl_4b_20260711_111458",   # AW 49 s80 22
        "qwen3vl_4b_1env__20260712_035536__qwen3vl_4b_20260711_111458",   # AW 49 s80 21
        "qwen3vl_4b_1env__20260711_233620__qwen3vl_4b_20260711_111458",   # AW 44 s80 18
        "qwen3vl_4b_1env__20260711_193125__qwen3vl_4b_20260711_111458",   # AW 43 s80 19
        "qwen3vl_4b_1env__20260711_152226__qwen3vl_4b_20260711_111458",   # AW 40 s80 16
        "qwen3vl_4b_1env__20260712_162037__qwen3vl_4b_20260711_111458",   # AW 37 s80 15
        "qwen3vl_4b_4env",                                                # legacy short name
    ],
    # NO CANONICAL RUN ON THIS BOX: the paper reports 63 and the best here is 59.
    # A run on a separate box (docker_qwen_eval_qwen3vl_8b_4env_gen3) is at 63 and
    # must lead once it is staged; until then this list resolves to a non-paper
    # run, so the AndroidWorld cell for this model is NOT sourced.
    "qwen3vl_8b": [
        "docker_qwen_eval_qwen3vl_8b_4env_gen3__qwen3vl_8b_4env",   # CANONICAL (confirmed against Table 8)
        "qwen3vl_8b_4env_gen3",                                           # AW 63, separate box
        "qwen3vl_8b_1env__20260712_023039__qwen3vl_8b_20260711_111458",   # AW 59 s80 30
        "qwen3vl_8b_1env__20260711_222314__qwen3vl_8b_20260711_111458",   # AW 52 s80 27
        "qwen3vl_8b_1env__20260712_114408__qwen3vl_8b_20260711_111458",   # AW 51 s80 26
        "qwen3vl_8b_1env__20260711_163408__qwen3vl_8b_20260711_111458",   # AW 47 s80 22
        "qwen3vl_8b_1env__20260712_202022__qwen3vl_8b_20260711_111458",   # AW 45 s80 20
        "qwen3vl_8b_1env__20260712_063505__qwen3vl_8b_20260711_111458",   # AW 36 s80 17
        "qwen3vl_8b_1env__20260712_155206__qwen3vl_8b_20260711_111458",   # AW 35 s80 16
        "qwen3vl_8b_4env",                                                # legacy short name
        # FLOOR -- raw_response 100% empty, ConnectionResetError.  AW 7 / s80 1.
        "qwen3vl_8b_1env__20260711_214035__qwen3vl_8b_20260711_111458",
        "qwen3vl_8b_1env__20260711_160407__qwen3vl_8b_20260711_111458",
        "qwen3vl_8b_1env__20260711_204254__qwen3vl_8b_20260711_111458",
        "qwen3vl_8b_1env__20260712_104708__qwen3vl_8b_20260711_111458",
        "qwen3vl_8b_1env__20260712_111540__qwen3vl_8b_20260711_111458",
        "qwen3vl_8b_1env__20260711_152230__qwen3vl_8b_20260711_111458",
    ],
    "qwen3vl_30b_a3b": [
        "docker_qwen_eval_qwen3vl_30b_a3b_4env__qwen3vl_30b_a3b_4env",   # CANONICAL
       "qwen3vl_30b_a3b_4env",
    ],
    "qwen3vl_32b": [
        "docker_qwen_eval_qwen3vl_32b_4env_gen4__qwen3vl_32b_4env",   # CANONICAL
       "qwen3vl_32b_4env_gen4",
    ],
    "qwen3vl_4b_think": [
        "docker_qwen_eval_qwen3vl_4b_think_4env_gen1__qwen3vl_4b_think_4env",   # CANONICAL
       "qwen3vl_4b_think_4env",
    ],
    "qwen3vl_8b_think": [
        "docker_qwen_eval_qwen3vl_8b_think_4env_gen1__qwen3vl_8b_think_4env",   # CANONICAL
       "qwen3vl_8b_think_4env_gen1",
    ],
    "gemma_4_31b_it_improved_m3a_think_off": [
        "docker_qwen_eval_gemma_31b_m3a_4env__gemma_31b_m3a_4env",   # CANONICAL
       "gemma31b_improved_0716_4env",
                                              "gemma_31b_m3a_4env",
    ],
    # This row is AW_ROW_DISPUTED: the two published columns come from two
    # DIFFERENT runs, so no single run reproduces both and "canonical" here is a
    # choice, not a match.  Under the held-run-is-higher rule the 59/31 run leads.
    #
    # CAVEAT on that leader: it was staged under the local key `mobile_run_gf30`,
    # and that same local key was measured serving BOTH a think-off run and a run
    # whose request body carries no thinking field at all.  Its think variant is
    # therefore [unverified] -- read the run's request body before treating this
    # as the think-off cell.  The two runs the published row actually mixes are
    # listed after it, so the row degrades to a sourced value rather than
    # vanishing if the leader is not staged.
    # AW_ROW_DISPUTED: the two published columns come from two DIFFERENT runs, so
    # no single run reproduces (48, 32) and "canonical" here is a choice.
    #
    # The variant is a SEPARATE problem from the value, and it is not settled.  A
    # run may be labelled think_off only when its request body carries
    # ``thinking_budget`` -- measured, not inferred.  Neither run below has been
    # checked that way, so the think-off label on this row is UNSOURCED even
    # though the numbers are.
    #
    # ``finalrun_aw116_20260828_131028`` (AW 59, s80 31) is deliberately NOT here.
    # It led this list until 300/300 of its steps were read: its
    # ``model_input.config`` carries only (max_output_tokens, temperature) --
    # ``thinking_budget`` is absent from every one.  A sibling run under the SAME
    # local key (``gf30_thinkoff_rerun``) sends ``thinking_budget: 0`` in 300/300.
    # Same model, same local key, different generation config.  So that run is
    # think_UNSPECIFIED, not think_off, and registering it here labelled a run
    # with a setting it never sent.
    "gemini_3_0_flash_preview_qwen_prompt_think_off": [
        "gemini_flash_g3preview_4env_gen1",     # AW 57 s80 32 -- s80 matches the paper; variant unchecked
        "gflash_full_20260721_012759",          # AW 48 s80 23 -- AW matches the paper; variant unchecked
    ],
    "gemini_3_5_flash_qwen_prompt": [
        "gemini_flash_g35flash_4env_gen1",   # CANONICAL
       "g35flash_4env_gen1",
    ],
    "gemini_3_5_flash_computer_use_task_only": [
        "cu_task_only_g35flash_4env_gen1",   # CANONICAL
       "cu_task_only_g35flash",
    ],
    "gui_owl_7b": [
        "docker_qwen_eval_gui_owl_7b_4env_gen2__gui_owl_7b_4env",   # CANONICAL
       "gui_owl_7b_4env_gap", "gui_owl_7b_4env_gen4",
    ],
    "gui_owl_32b": [
        "docker_qwen_eval_gui_owl_32b_4env__gui_owl_32b_4env",   # CANONICAL
       "gui_owl_32b_4env",
    ],
    "guiowl15_2b": [
        "docker_qwen_eval_guiowl15_2b_4env__guiowl15_2b_4env",   # CANONICAL
       "guiowl15_2b_4env",
    ],
    "guiowl15_4b": [
        "docker_qwen_eval_guiowl15_4b_4env__guiowl15_4b_4env",   # CANONICAL
       "guiowl15_4b_4env",
    ],
    "guiowl15_8b": [
        "docker_qwen_eval_guiowl15_8b_4env_gen1_traj__guiowl15_8b_4env",   # CANONICAL
       "guiowl15_8b_4env",
    ],
    "guiowl15_32b": [
        "docker_qwen_eval_guiowl15_32b_4env_gen2__guiowl15_32b_4env",   # CANONICAL
       "guiowl15_32b_4env",
    ],
    "guiowl15_8b_think": [
        "docker_qwen_eval_guiowl15_8b_think_4env__guiowl15_8b_think_4env",   # CANONICAL
       "guiowl15_8b_think_4env",
    ],
    # NO CANONICAL RUN ON THIS BOX: paper 49, a single run at 14.
    "mai_ui_2b": [
        # CANONICAL 44/17 s65 13.  gen2 is numerically identical (44/17, s65 13);
        # the median of the three runs picked gap.  Either reproduces the published
        # value -- the choice only names the source run.  gap carries per_task with
        # 115 rows (sr_summary episodes=115 != expected_tasks=116); that is the run
        # as it happened and must not be padded, so SCRATCH80_INCOMPLETE is expected.
        "docker_qwen_eval_mai_ui_2b_4env_gap__mai_ui_2b_4env",
        "docker_qwen_eval_mai_ui_2b_4env_gen2__mai_ui_2b_4env",
       "mai_ui_2b_4env_gen2", "mai_ui_2b_4env__20260629_123729",
    ],
    # NO CANONICAL RUN ON THIS BOX: paper 44, observed [7,28,29,30,31,32,48,55].
    "mai_ui_8b": [
        "docker_qwen_eval_appinfo_mai_ui_8b_ctrl_20260802_181224__mai_ui_8b_4env",   # CANONICAL (confirmed against Table 8)
        "mai_ui_8b_4env_gen4",                                            # legacy short name
        "mai_ui_8b_4env__20260628_214840",                                # AW 55 s80 27
        "mai_ui_8b_4env__20260629_055355",                                # AW 48 s80 27
        "mai_ui_8b_1env__20260712_162321__mai_ui_8b_20260711_111508",     # AW 32 s80 15
        "mai_ui_8b_1env__20260712_203658__mai_ui_8b_20260711_111508",     # AW 31 s80 13
        "mai_ui_8b_1env__20260712_005340__mai_ui_8b_20260711_111508",     # AW 30 s80 14
        "mai_ui_8b_1env__20260712_050633__mai_ui_8b_20260711_111508",     # AW 29 s80 13
        "mai_ui_8b_1env__20260711_160409__mai_ui_8b_20260711_111508",     # AW 29 s80 14
        "mai_ui_8b_1env__20260712_120555__mai_ui_8b_20260711_111508",     # AW 28 s80 14
        "mai_ui_8b_1env__20260711_203656__mai_ui_8b_20260711_111508",     # AW 28 s80 13
        # FLOOR -- raw_response 100% empty, ConnectionResetError.  AW 7 / s80 1.
        "mai_ui_8b_1env__20260711_152103__mai_ui_8b_20260711_111508",
        "mai_ui_8b_4env__20260629_000838",
        "mai_ui_8b_1env__20260712_110231__mai_ui_8b_20260711_111508",
        "mai_ui_8b_1env__20260712_113009__mai_ui_8b_20260711_111508",
        "mai_ui_8b_1env__20260712_092221__mai_ui_8b_20260711_111508",
        "mai_ui_8b_1env__20260712_103357__mai_ui_8b_20260711_111508",
        "mai_ui_8b_1env__20260712_095020__mai_ui_8b_20260711_111508",
    ],
    "ma3_7b": [
        "docker_qwen_eval_ma3_7b_4env_gen1__ma3_7b_4env",   # CANONICAL
       "ma3_7b_4env_gen1",
    ],
    "ma3_32b": [
        "docker_qwen_eval_ma3_32b_4env__ma3_32b_4env",   # CANONICAL
       "ma3_32b_4env", "ma3_32b_4env_gen2",
    ],
    "mobilerun_gemini_flash_3.0": [
        "docker_qwen_eval_mobilerun_gemini_flash_g3flash_4env_gen1__mobilerun_gemini_flash_4env",   # CANONICAL
       "mobilerun_gf30_4env",
    ],
    "gemini_3_0_flash_preview_final_run_appinfo_from_gui_owl": [
        "finalrun_gemini_flash_arvatitan_4shard",
       "final_run_appinfo_4env",
    ],
    "ui_tars_7b_sft": [
        "docker_qwen_eval_ui_tars_7b_sft_4env_gen2__ui_tars_7b_sft_4env",   # CANONICAL
       "ui_tars_7b_sft_4env",
    ],
    "ui_tars_1_5_7b": [
        "docker_qwen_eval_ui_tars_1_5_7b_4env__ui_tars_1_5_7b_4env",   # CANONICAL
       "ui_tars_1_5_7b_4env",
    ],
}

# Rows whose published AndroidWorld(116)/Scratch(80) pair cannot be sourced from
# ONE run.  Two shapes exist and they are not the same finding, so every entry
# carries the diagnostic code it is reported under -- the code lives in the
# entry, never hardcoded at the warn site, so the two cannot drift apart:
#
#   AW_ROW_DISPUTED     both published columns are reproducible, but from
#                       DIFFERENT runs -- or the AndroidWorld column is a copy
#                       of the row above it -- or NEITHER column has been
#                       sourced to any run yet.
#   AW_ONLY_UNSOURCED   the Scratch column IS reproduced exactly by one run,
#                       but that run's AndroidWorld total is not the published
#                       one and no run anywhere reproduces the published total.
#                       One run cannot yield one right column and one wrong one,
#                       so the AndroidWorld column alone came from elsewhere.
#
# Never widen AW_ONLY_UNSOURCED to a row where the Scratch column is also
# unreproduced: "we found neither" is AW_ROW_DISPUTED's job, and reporting it as
# AW_ONLY_UNSOURCED would claim a Scratch match that was never made.
#
# gemini_3_0_flash_preview_qwen_prompt_think_off was a CANDIDATE for
# AW_ONLY_UNSOURCED, on a single survey reporting that a 4env gemini_flash_preview
# run reproduces Scratch 32 while carrying AW 57, not the published 48.  It stays
# AW_ROW_DISPUTED, and the reason is now positive rather than cautionary: a second
# box located the missing half.  A 1env gemini_flash_preview run carries AW 48
# with Scratch 23, so BOTH published numbers are reproduced -- by two different
# runs.  That is the same shape as the four rows above it, not a column that came
# from nowhere, so AW_ONLY_UNSOURCED has no member and the category is retired in
# practice.  Its definition is kept only so a future row can be filed under it
# without re-deriving the distinction.
#
# Provenance: this box holds no AndroidWorld run of its own (no sr_summary.json
# anywhere), so both halves were supplied by peer boxes -- but as the verbatim
# d["total"] block of each file, not as a summary, which is why the run names are
# now written here.  Both were independently recomputed from their own 116
# checkpoints and agreed with the stored successes.
#
#   1env  gflash_full_20260721_012759          successes 48, score_points 48.5,
#         exceptions 6, score_missing_or_nan 6, coverage 1.0.  Restricted to the
#         80 recovery tasks: 23 at score >= 1, 24 at score > 0.
#   4env  gemini_flash_g3preview_4env_gen1     successes 57, score_points 57.5,
#         exceptions 0, coverage 1.0.  Restricted to the 80: 32 at >= 1, 33 at > 0.
#
# The published pair (48, 32) therefore takes its AndroidWorld column from the
# first run and its Scratch column from the second, and BOTH columns follow the
# >= 1 rule -- the split is between runs, not between scoring rules.
AW_DISPUTED = {
    "gemma_4_31b_it_improved_m3a_think_off": ("AW_ROW_DISPUTED",
        "paper AW 59 comes from gemma31b_improved_0716_4env (Scratch 31); "
        "paper Scratch 30 comes from gemma_31b_m3a_4env (AW 56) -- two runs in one row"),
    "gui_owl_7b": ("AW_ROW_DISPUTED",
        "paper AW 73 comes from gui_owl_7b_4env_gap (Scratch 41); "
        "paper Scratch 38 comes from gui_owl_7b_4env_gen4 (AW 71) -- two runs in one row"),
    "ma3_32b": ("AW_ROW_DISPUTED",
        "paper AW 75 comes from ma3_32b_4env (Scratch 44); "
        "paper Scratch 42 comes from ma3_32b_4env_gen2 (AW 74) -- two runs in one row"),
    "gemini_3_5_flash_computer_use_task_only": ("AW_ROW_DISPUTED",
        "paper AW 76 duplicates the row above; the run that yields Scratch 31 "
        "(cu_task_only_g35flash) has AW 45"),
    "gemini_3_0_flash_preview_qwen_prompt_think_off": ("AW_ROW_DISPUTED",
        "paper AW 48 comes from gflash_full_20260721_012759 (1env, Scratch 23); "
        "paper Scratch 32 comes from gemini_flash_g3preview_4env_gen1 (AW 57) "
        "-- two runs in one row.  Both runs set run_config.models to the same "
        "value, gemini_flash_preview, so models alone does not separate them"),
}


def aw_dispute_note(model_id):
    """Message half of an AW_DISPUTED entry; the code half is entry[0]."""
    entry = AW_DISPUTED.get(model_id)
    return entry[1] if entry else ""

# ==============================================================================
# 4.  TABLE DEFINITIONS
# ==============================================================================

COL_LABELS = {
    "hv_clean": ("Scratch", r"Scratch"),
    "hv_t_minus_5": ("t-5_rep", r"$t{-}5_{\text{rep}}$"),
    "hv_t_minus_3": ("t-3_rep", r"$t{-}3_{\text{rep}}$"),
    "hv_t_minus_1": ("t-1_rep", r"$t{-}1_{\text{rep}}$"),
    "hv_t_rep": ("t_rep", r"$t_{\text{rep}}$"),
    "hv_t_snap": ("t_snap", r"$t_{\text{snap}}$"),
    "hv_t_all": ("t_all", r"$t_{\text{all}}$"),
    "hv_tp1_pos": ("t+1^+", r"$t{+}1^{+}$"),
    "hv_tp1_neg": ("t+1^-", r"$t{+}1^{-}$"),
    "hv_tp1_all": ("t+1_all", r"$t{+}1_{\text{all}}$"),
    "lv_clean": ("LV Scratch", r"Scratch"),
    "lv_t": ("LV t", r"$t$"),
}

TAB1_COLS = ["hv_clean", "hv_t_minus_5", "hv_t_minus_3", "hv_t_minus_1",
             "hv_t_rep", "hv_t_snap", "hv_t_all", "hv_tp1_pos", "hv_tp1_neg",
             "hv_tp1_all", "lv_clean", "lv_t"]
TAB1_ROWS = ["qwen3vl_2b", "qwen3vl_4b", "gui_owl_32b", "ma3_32b", "mai_ui_8b",
             "gemini_3_0_flash_preview_qwen_prompt_think_on",
             # Two models added 2026-09-09.  This table's column set includes t-5/t-3,
             # which is being produced for exactly these two; every other column
             # is already staged from another box.
             "gemini_3_8_flash", "gemini_3_1_pro"]

TAB2_COLS = ["hv_clean", "hv_t_minus_1", "hv_t_rep", "hv_t_snap", "hv_t_all",
             "hv_tp1_pos", "hv_tp1_neg", "hv_tp1_all", "lv_clean", "lv_t"]
TAB2_ROWS = ["qwen3vl_8b", "qwen3vl_32b", "gemma_4_31b_it_improved_m3a_think_off",
             "gemini_3_0_flash_preview_qwen_prompt_think_on", "mai_ui_8b",
             "gui_owl_7b", "guiowl15_8b", "gemini_3_5_flash_computer_use_task_only",
             "ma3_7b", "mobilerun_gemini_flash_3.0",
             "gemini_3_0_flash_preview_final_run_appinfo_from_gui_owl",
             # Four models added 2026-09-09 -- instruct variants only; the think-on rows
             # belong to tab:instreason, not here.
             "gemini_3_8_flash", "gemini_3_1_pro",
             "qwen38_27b_think_off", "qwen36_27b_think_off"]

# (family label, instruct model id, reasoning model id)
TAB3_ROWS = [
    ("Qwen3-VL-32B", "qwen3vl_32b", "qwen3vl_32b_think"),
    ("Gemma-4-31B-IT", "gemma_4_31b_it_improved_m3a_think_off",
     "gemma_4_31b_it_m3a_think_on"),
    ("Gemini Flash 3.0", "gemini_3_0_flash_preview_qwen_prompt_think_off",
     "gemini_3_0_flash_preview_qwen_prompt_think_on"),
    ("GUI-Owl-1.5-32B", "guiowl15_32b", "guiowl15_32b_think"),
    # Two models added 2026-09-09.  Both carry a published think_off / think_on pair,
    # so they are the only new models that fit this table's shape.
    ("Qwen3.8-27B", "qwen38_27b_think_off", "qwen38_27b_think_on"),
    ("Qwen3.6-27B", "qwen36_27b_think_off", "qwen36_27b_think_on"),
]

TAB4_ROWS = ["qwen3vl_2b", "qwen3vl_4b", "qwen3vl_8b", "qwen3vl_30b_a3b",
             "qwen3vl_32b", "gemma_4_31b_it_improved_m3a_think_off",
             "gemini_3_0_flash_preview_qwen_prompt_think_off",
             "gemini_3_5_flash_qwen_prompt", "gui_owl_7b", "gui_owl_32b",
             "guiowl15_2b", "guiowl15_4b", "guiowl15_8b", "guiowl15_32b",
             "mai_ui_2b", "mai_ui_8b", "ui_tars_7b_sft", "ui_tars_1_5_7b",
             "gemini_3_5_flash_computer_use_task_only", "ma3_7b", "ma3_32b",
             "mobilerun_gemini_flash_3.0",
             "gemini_3_0_flash_preview_final_run_appinfo_from_gui_owl",
             "qwen3vl_4b_think", "qwen3vl_8b_think", "guiowl15_8b_think",
             # Four models added 2026-09-09 -- every one has AndroidWorld runs.
             "gemini_3_8_flash", "gemini_3_1_pro",
             # The AndroidWorld runs for these two were served with
             # --reasoning-parser qwen3, i.e. the think-ON condition, so the AW
             # row is the think_on cell.  The think_off cells exist on the
             # human-verified axis and belong to tab:instreason, not here.
             "qwen38_27b_think_on", "qwen36_27b_think_on",
]

# ==============================================================================
# 5.  DIAGNOSTICS -- nothing is dropped silently
# ==============================================================================

class Diagnostics(object):
    def __init__(self):
        self.items = []

    def add(self, severity, code, where, message):
        self.items.append({"severity": severity, "code": code,
                           "where": where, "message": message})

    def warn(self, code, where, message):
        self.add("WARN", code, where, message)

    def error(self, code, where, message):
        self.add("ERROR", code, where, message)

    def info(self, code, where, message):
        self.add("INFO", code, where, message)

    def count(self, severity):
        return sum(1 for i in self.items if i["severity"] == severity)

    def render_markdown(self):
        if not self.items:
            return "_No warnings._\n"
        out = ["| Severity | Code | Where | Message |", "|---|---|---|---|"]
        for i in self.items:
            out.append("| %s | `%s` | `%s` | %s |" % (
                i["severity"], i["code"], i["where"],
                i["message"].replace("|", "\\|")))
        return "\n".join(out) + "\n"


DIAG = Diagnostics()


# ==============================================================================
# 6.  CELL
# ==============================================================================

class Cell(object):
    """One measured (model, axis, condition) result, or an explicit absence."""

    __slots__ = ("num", "den", "valid", "issues", "source", "rule", "notes",
                 "missing_reason")

    def __init__(self, num=None, den=None, valid=None, issues=0, source=None,
                 rule="validation", notes=None, missing_reason=None):
        self.num = num
        self.den = den
        self.valid = valid
        self.issues = issues
        self.source = source
        self.rule = rule
        self.notes = list(notes or [])
        self.missing_reason = missing_reason

    @property
    def present(self):
        return self.num is not None and self.den

    @property
    def rate(self):
        if not self.present:
            return None
        return 100.0 * self.num / self.den

    @classmethod
    def missing(cls, reason):
        return cls(missing_reason=reason)

    def flags(self):
        f = ""
        if self.valid is False:
            f += "*"          # validation contract failed
        if "header_only" in self.notes:
            f += "~"          # denominator/numerator taken from the header
        if "per_episode" in self.notes:
            f += "#"          # rule re-applied over the sibling per-episode file
        if "denominator_mismatch" in self.notes:
            f += "!"          # denominator differs from expectation
        return f

    def render(self, show_counts=False, latex=False):
        if not self.present:
            return "n/a"
        text = "%.1f" % self.rate
        if show_counts:
            text = "%d/%d = %s" % (self.num, self.den, text)
        flag = self.flags()
        if flag and latex:
            flag = "$^{%s}$" % (flag.replace("*", r"\ast").replace("!", r"!")
                                .replace("~", r"\sim").replace("#", r"\#"))
        return text + flag


def derive(cells, denom, label):
    """Sum numerators of several cells over a fixed derived denominator."""
    if any(c is None or not c.present for c in cells):
        why = "; ".join(sorted(set(
            (c.missing_reason or "missing") for c in cells
            if c is None or not c.present)))
        return Cell.missing("%s needs %s" % (label, why))
    num = sum(c.num for c in cells)
    measured = sum(c.den for c in cells)
    out = Cell(num=num, den=denom, valid=all(c.valid is not False for c in cells),
               issues=sum(c.issues for c in cells),
               source=" + ".join(str(c.source) for c in cells),
               notes=["derived"])
    if measured != denom:
        out.notes.append("denominator_mismatch")
        DIAG.warn("DERIVED_DENOM", label,
                  "component denominators sum to %d but the definition fixes %d"
                  % (measured, denom))
    return out


# ==============================================================================
# 7.  FILE READERS
# ==============================================================================

def read_validation_payload(payload, where, axis, cond):
    """Turn a validation.json payload into a Cell using SCORING['validation']."""
    if not isinstance(payload, dict):
        DIAG.error("BAD_SCHEMA", where, "not a JSON object")
        return Cell.missing("unreadable at %s" % where)

    notes = []
    rows = payload.get("rows")
    if isinstance(rows, list) and rows:
        num = sum(1 for r in rows if is_success_validation(r))
        den = len(rows)
        header_num = payload.get("success_count")
        if header_num is not None and header_num != num:
            DIAG.warn("HEADER_DISAGREES", where,
                      "success_count=%s but recomputing with '%s' over rows gives %d"
                      % (header_num, SCORING["validation"], num))
        header_den = payload.get("result_count")
        if header_den is not None and header_den != den:
            DIAG.warn("HEADER_DISAGREES", where,
                      "result_count=%s but the file carries %d rows "
                      "(header not updated after a denominator fix)"
                      % (header_den, den))
        check_entry_identity(rows, where, notes)
        # LV_FOUR_WAY_DISAGREEMENT -- the published lv177 / lv254 subset cells.
        # Five directories (gemini_3_5_flash_qwen_prompt_lv177 / _lv254,
        # guiowl15_8b_lv177, ma3_7b_lv177, ui_tars_1_5_7b_lv177) let one file
        # yield FOUR different answers: success_rate*312 (a THIRD, earlier run --
        # it is not the published 312 cell either), success_count (the subset),
        # result_count (312), and len(rows) (177 / 254).  The file declares its
        # own ``subset`` / ``original_row_count`` / ``excluded_count``.
        # Measured: the 177 rows are all present in the published 312 run, but
        # the scores disagree on 34 of them for guiowl15_8b and 27 for ma3_7b --
        # so a subset is a SEPARATE EXECUTION, not a filtered view of the full
        # run.  No model is wired to these directories today, so this never
        # fires on the registered cells; it exists to name the trap if someone
        # ever connects one via a ``lv=`` alias.
        #
        # Deliberately WARN, not ERROR: the denominator gate already stops this
        # from reaching a table.  LV fixes EXPECTED_DENOM at 312, so a 177-row
        # file trips DENOM_MISMATCH, which IS in VERIFY_FATAL -- --verify
        # already fails.  This message only explains WHY.  Raising it to ERROR
        # would additionally break --verify for any legitimately-subset file
        # published in future, and the full 2998+6274 file corpus has NOT been
        # swept for the ``subset`` key -- only the 159 cells the scorer reads.
        subset_tag = payload.get("subset")
        orig_rows = payload.get("original_row_count")
        if subset_tag or (orig_rows is not None and orig_rows != den):
            notes.append("subset_not_full_denominator")
            rate = payload.get("success_rate")
            implied = ("%.0f" % (rate * header_den)
                       if isinstance(rate, float) and header_den else "?")
            DIAG.warn("LV_FOUR_WAY_DISAGREEMENT", where,
                      "subset=%s: one file yields four different answers -- "
                      "success_rate=%s (=> %s/%s, some EARLIER run -- it is "
                      "not the published 312 cell either), "
                      "success_count=%s (the subset), result_count=%s, "
                      "len(rows)=%d (excluded_count=%s, original_row_count=%s). "
                      "None is endorsed here: the published LV denominator is "
                      "fixed at 312, so a subset cell must not be wired into "
                      "an LV column. Value left unchanged."
                      % (subset_tag, rate, implied, header_den,
                         payload.get("success_count"), header_den, den,
                         payload.get("excluded_count"), orig_rows))
    else:
        # No per-episode rows: fall back to the header and say so.  The rule
        # cannot be re-applied, so the value is only as good as the producer.
        num = payload.get("success_count")
        den = payload.get("result_count") or payload.get("expected_entries")
        notes.append("header_only")
        DIAG.warn("NO_ROWS", where,
                  "file has no 'rows'; using header success_count/result_count, "
                  "so SCORING['validation'] could not be re-applied")
        if num is None or not den:
            DIAG.error("NO_COUNTS", where, "neither rows nor usable header counts")
            return Cell.missing("no scoreable content at %s" % where)

    expected = EXPECTED_DENOM.get((axis, cond))
    if expected is not None and den != expected:
        notes.append("denominator_mismatch")
        DIAG.warn("DENOM_MISMATCH", where,
                  "denominator read from file is %d, expected %d for (%s, %s)"
                  % (den, expected, axis, cond))

    valid = payload.get("valid")
    issues = len(payload.get("issues") or [])
    if valid is False:
        DIAG.warn("INVALID_CELL", where,
                  "validation contract failed (valid=false, %d issue(s)); "
                  "value is reported but marked" % issues)
    for field in ("missing", "unexpected", "duplicates"):
        vals = payload.get(field) or []
        if vals:
            DIAG.warn("ENTRY_SET", where, "%s: %d entr(y/ies)" % (field, len(vals)))

    return Cell(num=num, den=den, valid=valid, issues=issues, source=where,
                rule="validation", notes=notes)


def read_per_episode_payload(payload, where, axis, cond, note_absent=True):
    """per_episode.json fallback: a list of episode records."""
    records = payload
    if isinstance(payload, dict):
        records = payload.get("episodes") or payload.get("rows") or payload.get("records")
    if not isinstance(records, list) or not records:
        return Cell.missing("no episodes in %s" % where)
    num = sum(1 for r in records if is_success_validation(r))
    den = len(records)
    notes = []
    check_entry_identity(records, where, notes)
    expected = EXPECTED_DENOM.get((axis, cond))
    if expected is not None and den != expected:
        notes.append("denominator_mismatch")
        DIAG.warn("DENOM_MISMATCH", where,
                  "per_episode denominator %d, expected %d" % (den, expected))
    if note_absent:
        DIAG.info("NO_VALIDATION", where,
                  "validation.json absent; scored from per_episode.json, so no "
                  "start-state contract result is available")
    return Cell(num=num, den=den, valid=None, issues=0, source=where,
                rule="validation", notes=notes)


def per_episode_sibling(path):
    """Path of the per-episode file beside a validation file, or None.

    Measured against the two published trees (2026-09-06):
      * FRE keeps ``<...>/eval/validation/<model>/<cond>.json`` beside
        ``<...>/eval/per_episode/<model>/<cond>.json``  -- 259 such files.
      * RES publishes NO per-episode file anywhere (its episode records are
        sharded into ``shards/shard_NN/results.json``), so the second form
        below simply 404s and the header value is kept.
    """
    if "/validation/" in path:
        return path.replace("/validation/", "/per_episode/", 1)
    if path.endswith("/validation.json"):
        return path[:-len("validation.json")] + "per_episode.json"
    return None


def adopt_per_episode(cell, pe, where):
    """rows -> per_episode -> header: swap a header-only cell for the recount.

    Only a ``header_only`` cell (or one that yielded nothing scoreable at all)
    reaches this.  A validation.json that carries rows has already been scored
    under SCORING['validation'] and is never second-guessed by a second file.
    The per-episode recount is refused when it covers a different number of
    episodes than the header claims, because a partial per-episode file would
    silently shrink the denominator -- FRE publishes such files: the
    ``*_lv177`` LV trees carry 177 episodes against a 312 header.
    """
    if not pe.present:
        return cell
    if cell is None:
        return pe                  # no validation.json at all: unchanged path
    if cell.present:
        if pe.den != cell.den:
            DIAG.warn("PER_EPISODE_PARTIAL", where,
                      "sibling per_episode has %d episode(s) but the header "
                      "counts %d; keeping the header value" % (pe.den, cell.den))
            return cell
        if pe.num != cell.num:
            DIAG.warn("HEADER_DISAGREES", where,
                      "header success_count=%s but recomputing with '%s' over "
                      "the sibling per_episode gives %d"
                      % (cell.num, SCORING["validation"], pe.num))
        pe.valid = cell.valid      # the contract result lives in validation.json
        pe.issues = cell.issues
    pe.notes.append("per_episode")
    DIAG.info("PER_EPISODE_FALLBACK", where,
              "validation.json carries no 'rows'; SCORING['validation'] was "
              "re-applied over the sibling per_episode file instead of trusting "
              "the header")
    return pe


#: Below this fraction of the 116 expected episodes a run cannot be explained by
#: exception attrition, so the cell is refused rather than flagged.  The observed
#: filtered case keeps 15/116 = 0.129; genuine attrition has been a few episodes.
AW_COVERAGE_FLOOR = 0.95


def read_sr_summary_payload(payload, where):
    """AndroidWorld sr_summary.json -> AW(116) cell using SCORING['sr_summary'].

    The count lives at d["total"]["successes"] -- NOT at the top level, and NOT
    d["total"]["score_points"] (which sums 0.5s and is therefore a different
    quantity).
    """
    if not isinstance(payload, dict):
        return Cell.missing("unreadable sr_summary at %s" % where)
    total = payload.get("total")
    if not isinstance(total, dict) or "successes" not in total:
        DIAG.error("BAD_SR_SUMMARY", where,
                   "no d['total']['successes']; refusing to guess from top-level keys")
        return Cell.missing("no total.successes at %s" % where)
    num = total["successes"]
    episodes = total.get("episodes")
    notes = []
    # A short run has two very different causes and they must not share a message.
    #
    #   * a handful of suite tasks errored out -- legitimate; the denominator
    #     stays 116 and those tasks count against the run
    #   * the task REGISTRY was filtered, so a different task set ran entirely
    #
    # The second happens when a run_catalog entry carries "supplementary_model":
    # android_world_interface.py exports it as ANDROID_WORLD_SUPPLEMENTARY_MODEL and
    # registry.py:_filter_registry_by_supplementary drops every task outside that
    # model's list -- qwen3_2b keeps 15 of 116.  summarize_eval_sr.py does not raise
    # on the mismatch; it records both denominators, and sr_loaded_denominator makes
    # the truncated run look healthy.  A cell built from such a run is unusable, so
    # a large shortfall is an error rather than a warning.
    coverage = total.get("coverage")
    if coverage is None and episodes is not None and AW_DENOM:
        coverage = float(episodes) / AW_DENOM
    if episodes is not None and episodes != AW_DENOM:
        notes.append("denominator_mismatch")
        if coverage is not None and coverage < AW_COVERAGE_FLOOR:
            DIAG.error("AW_COVERAGE_SHORT", where,
                       "run holds %s of %d episodes (coverage %.4f): too few to be "
                       "exception attrition. The task registry was probably filtered "
                       "-- check the run_catalog entry for a 'supplementary_model' "
                       "field, which silently reduces the task set"
                       % (episodes, AW_DENOM, coverage))
        else:
            DIAG.warn("AW_EPISODES", where,
                      "run loaded %s of %d episodes (coverage %.4f), denominator stays "
                      "fixed at %d (the suite's exception tasks count against the run)"
                      % (episodes, AW_DENOM, coverage if coverage is not None else -1.0,
                         AW_DENOM))
    # Independent cross-check: when the two denominators agree the run covered the
    # expected set, so a divergence is the same defect seen from another angle. It is
    # worth reading separately because coverage can be absent from older summaries.
    sr_exp = total.get("sr_expected_denominator")
    sr_loaded = total.get("sr_loaded_denominator")
    if (sr_exp is not None and sr_loaded is not None
            and abs(float(sr_exp) - float(sr_loaded)) > 1e-9):
        DIAG.warn("AW_DENOM_DISAGREE", where,
                  "sr_expected_denominator %.5f != sr_loaded_denominator %.5f: the run "
                  "did not cover the expected task set" % (sr_exp, sr_loaded))
    exceptions = total.get("exceptions") or 0
    if exceptions:
        DIAG.warn("AW_EXCEPTIONS", where, "%d episode(s) ended in an exception" % exceptions)
    nan = total.get("score_missing_or_nan") or 0
    if nan:
        DIAG.warn("AW_NAN", where, "%d episode(s) have a missing/NaN score" % nan)
    return Cell(num=num, den=AW_DENOM, valid=None, issues=0, source=where,
                rule="sr_summary", notes=notes)


def read_per_task_payload(payload, where, tasks80):
    """AndroidWorld per_task.json restricted to the 80 recovery tasks."""
    records = payload
    if isinstance(payload, dict):
        records = (payload.get("records") or payload.get("tasks")
                   or payload.get("episodes"))
    if not isinstance(records, list) or not records:
        return Cell.missing("no per-task records in %s" % where)

    def task_of(r):
        for k in ("task_name", "task_template", "task", "template"):
            if k in r and r[k]:
                return str(r[k])
        return None

    seen = {}
    for r in records:
        name = task_of(r)
        if name is None:
            continue
        if name in seen:
            DIAG.warn("AW_DUPLICATE_TASK", where, "task %s appears more than once" % name)
            continue
        seen[name] = r
    hit = [seen[t] for t in tasks80 if t in seen]
    absent = [t for t in tasks80 if t not in seen]
    if absent:
        DIAG.warn("SCRATCH80_INCOMPLETE", where,
                  "%d of the 80 recovery tasks are absent from the run "
                  "(counted as failures): %s"
                  % (len(absent), ", ".join(sorted(absent)[:6])
                     + (" ..." if len(absent) > 6 else "")))
    num = sum(1 for r in hit if is_success_sr_summary(r))
    return Cell(num=num, den=SCRATCH80_DENOM, valid=None, issues=0, source=where,
                rule="sr_summary",
                notes=["denominator_mismatch"] if absent else [])


# ==============================================================================
# 8.  STORES
# ==============================================================================

class BaseStore(object):
    name = "base"

    def get(self, axis, cond, model_id):
        raise NotImplementedError

    def get_aw(self, model_id):
        raise NotImplementedError

    def get_aw_scratch80(self, model_id, tasks80):
        raise NotImplementedError

    def task_names(self, axis, cond, model_id):
        return None

    def list_models(self, axis, cond):
        return []

    def get_raw(self, axis, cond, model_id):
        """Return (payload, where) for --explain, or (None, None)."""
        return None, None


class NativeStore(BaseStore):
    """Reads the released Evaluation_Output layout."""

    name = "native"

    def __init__(self, root, aw_root=None):
        self.root = os.path.abspath(root)
        self.aw_root = os.path.abspath(aw_root) if aw_root else None
        if not os.path.isdir(self.root):
            raise SystemExit("--root is not a directory: %s" % self.root)

    def _dir(self, axis, cond, model_id):
        return os.path.join(self.root, axis, cond, model_id)

    def get(self, axis, cond, model_id):
        d = self._dir(axis, cond, model_id)
        vpath = os.path.join(d, "validation.json")
        cell = None
        if os.path.exists(vpath):
            with open(vpath) as fh:
                cell = read_validation_payload(json.load(fh), vpath, axis, cond)
            if cell.present and "header_only" not in cell.notes:
                return cell
        epath = os.path.join(d, "per_episode.json")
        if os.path.exists(epath):
            with open(epath) as fh:
                pe = read_per_episode_payload(json.load(fh), epath, axis, cond,
                                              note_absent=cell is None)
            return adopt_per_episode(cell, pe, epath)
        # Do not drop a header-only cell just because no sibling exists: the
        # "~" value is still the best answer available.
        if cell is not None:
            return cell
        return Cell.missing("no validation.json/per_episode.json under %s"
                            % os.path.relpath(d, self.root))

    def task_names(self, axis, cond, model_id):
        d = self._dir(axis, cond, model_id)
        for fname in ("validation.json", "per_episode.json"):
            p = os.path.join(d, fname)
            if not os.path.exists(p):
                continue
            with open(p) as fh:
                payload = json.load(fh)
            rows = payload.get("rows") if isinstance(payload, dict) else payload
            if isinstance(payload, dict) and rows is None:
                rows = payload.get("episodes")
            if isinstance(rows, list):
                names = [r.get("task_name") for r in rows if r.get("task_name")]
                if names:
                    return sorted(set(names))
        return None

    def list_models(self, axis, cond):
        d = os.path.join(self.root, axis, cond)
        if not os.path.isdir(d):
            return []
        return sorted(x for x in os.listdir(d) if os.path.isdir(os.path.join(d, x)))

    def get_raw(self, axis, cond, model_id):
        p = os.path.join(self._dir(axis, cond, model_id), "validation.json")
        if not os.path.exists(p):
            return None, None
        with open(p) as fh:
            return json.load(fh), p

    def _aw_dir(self, model_id):
        """androidworld/ is keyed by RUN, and a run name need not equal the
        model id (the appendix pairs AW and Scratch from one run), so the
        canonical id is tried first and the registry's run names after it."""
        base = self.aw_root or os.path.join(self.root, AXIS_AW)
        runs = list(AW_RUNS.get(model_id) or [])
        # AW_RUNS is ORDERED and its first entry is the canonical run -- the one
        # that reproduces BOTH published columns.  Falling past it still yields a
        # value, and that value is a DIFFERENT run's, so it must never pass
        # silently.  Measured on a single-box tree: Qwen3-VL-8B rendered 59/116
        # where the paper has 63, MAI-UI-2B 14 where the paper has 49, and
        # MAI-UI-8B 55 where the paper has 44 -- no flag, no warning, because
        # every one of those runs is itself healthy.  The cell was not wrong; it
        # was the wrong cell.
        for i, name in enumerate([model_id] + runs):
            d = os.path.join(base, name)
            if os.path.isdir(d):
                if name != model_id:
                    DIAG.info("AW_RUN_DIR", model_id,
                              "AndroidWorld cell read from run directory '%s'" % name)
                # name == model_id is the canonical directory by construction: a
                # published run is stored under the model id precisely because it
                # IS that model's canonical run (the run name lives in
                # MANIFEST:identity.run_name so the shard/env layout never leaks
                # into a path).  Comparing it against AW_RUNS[0] -- which holds
                # the producing box's run name -- reported every renamed cell as
                # non-canonical.
                if runs and name != runs[0] and name != model_id:
                    DIAG.warn("AW_NON_CANONICAL_RUN", model_id,
                              "the canonical run '%s' is not present, so this cell "
                              "was read from '%s' instead -- a different run, whose "
                              "published columns need not match. Stage the canonical "
                              "run or treat this value as unsourced."
                              % (runs[0], name))
                return d
        if runs:
            DIAG.warn("AW_NO_RUN_ON_DISK", model_id,
                      "none of %d registered run director%s exist under %s "
                      "(canonical: %s)"
                      % (len(runs), "y" if len(runs) == 1 else "ies",
                         os.path.relpath(base, self.root) if self.aw_root is None else base,
                         runs[0]))
        return os.path.join(base, model_id)

    def get_aw(self, model_id):
        d = self._aw_dir(model_id)
        p = os.path.join(d, "sr_summary.json")
        if not os.path.exists(p):
            return Cell.missing("no sr_summary.json under androidworld/ for %s "
                                "(tried %s)" % (model_id,
                                                ", ".join([model_id] + list(AW_RUNS.get(model_id) or []))))
        with open(p) as fh:
            return read_sr_summary_payload(json.load(fh), p)

    def get_aw_scratch80(self, model_id, tasks80):
        d = self._aw_dir(model_id)
        # The released tree normalises per-task scores to per_task.json, but a
        # run copied straight off a box carries the producer's own name
        # (summarize_eval_sr.py writes mobilerun_trajectory_index.json next to
        # sr_summary.json).  Accept either instead of dropping the cell.
        for name in ("per_task.json", "mobilerun_trajectory_index.json"):
            p = os.path.join(d, name)
            if os.path.exists(p):
                with open(p) as fh:
                    return read_per_task_payload(json.load(fh), p, tasks80)
        return Cell.missing("no per_task.json in %s (Scratch(80) requires "
                            "per-task scores from the SAME run)"
                            % os.path.relpath(d, self.root))


# --- adapter over the current repositories -----------------------------------

REPO_FRE = "Gyubeum/AndroidFlux_Failure_Recovery_Eval"
REPO_RES = "Gyubeum/AndroidFlux_results"

#: (axis, cond) -> ordered list of (repo, path template, kind).  The first
#: readable path wins; later entries are byte-identical mirrors kept as
#: fallbacks and reported when they are the ones actually used.
LEGACY_PATHS = {
    (AXIS_HV_REP, "clean"): [
        (REPO_FRE, "human_verified_set/t_minus_n_and_t/replay_65/eval/validation/{m}/clean.json", "primary"),
        (REPO_FRE, "v2_65_eval_results/validation/{m}/clean.json", "mirror"),
    ],
    (AXIS_HV_REP, "t_minus_1"): [
        (REPO_FRE, "human_verified_set/t_minus_n_and_t/replay_65/eval/validation/{m}/pre_error_t_minus_1.json", "primary"),
        (REPO_FRE, "v2_65_eval_results/validation/{m}/pre_error_t_minus_1.json", "mirror"),
    ],
    (AXIS_HV_REP, "t"): [
        (REPO_FRE, "human_verified_set/t_minus_n_and_t/replay_65/eval/validation/{m}/error_t.json", "primary"),
        (REPO_RES, "human_verified_80/error_t/{m}/core_65/validation.json", "primary"),
        (REPO_FRE, "v2_65_eval_results/validation/{m}/error_t.json", "mirror"),
    ],
    (AXIS_HV_REP, "t_minus_3"): [
        (REPO_RES, "v2_65_t_minus_n/{m}/pre_error_t_minus_3/validation.json", "primary"),
    ],
    (AXIS_HV_REP, "t_minus_5"): [
        (REPO_RES, "v2_65_t_minus_n/{m}/pre_error_t_minus_5/validation.json", "primary"),
    ],
    (AXIS_HV_REP, "t_plus_1_pos"): [
        (REPO_FRE, "human_verified_set/t_plus_1/replay_65/eval/validation/{m}/t_plus_1_positive.json", "primary"),
    ],
    (AXIS_HV_REP, "t_plus_1_neg"): [
        (REPO_FRE, "human_verified_set/t_plus_1/replay_65/eval/validation/{m}/t_plus_1_negative.json", "primary"),
    ],
    (AXIS_HV_SNAP, "clean"): [
        (REPO_FRE, "human_verified_set/t_minus_n_and_t/snapshot_15/eval/validation/{m}/snapshot_clean.json", "primary"),
        (REPO_FRE, "v3_15_eval_results/validation/{m}/snapshot_clean.json", "mirror"),
    ],
    (AXIS_HV_SNAP, "t_minus_1"): [
        (REPO_FRE, "human_verified_set/t_minus_n_and_t/snapshot_15/eval/validation/{m}/snapshot_pre_error_t_minus_1.json", "primary"),
        (REPO_FRE, "v3_15_eval_results/validation/{m}/snapshot_pre_error_t_minus_1.json", "mirror"),
    ],
    (AXIS_HV_SNAP, "t"): [
        (REPO_FRE, "human_verified_set/t_minus_n_and_t/snapshot_15/eval/validation/{m}/snapshot_error_t.json", "primary"),
        (REPO_RES, "human_verified_80/error_t/{m}/snapshot_ext_15/validation.json", "primary"),
        (REPO_FRE, "v3_15_eval_results/validation/{m}/snapshot_error_t.json", "mirror"),
    ],
    # Beware: FRE also carries ..._lv177 / ..._lv254 directories, but those are
    # SUBSETS (177 / 254 rows) and do not match the LV denominator of 312.  The
    # paper's LV t comes from the full 312 runs -- guiowl15_8b 138/312 (paper
    # 44.20), ma3_7b 141/312 (paper 45.20).  ui_tars_1_5_7b and
    # gemini_3_5_flash_qwen_prompt appear only in tab:aw-vs-recovery, which has
    # no LV column, so there is no LV t paper cell for them at all -- do not try
    # to fill their MISSING with lv177/lv254.
    # Never add lv177/lv254 here or as an ``lv=`` alias -- LV_FOUR_WAY_DISAGREEMENT.
    (AXIS_LV, "t"): [
        (REPO_RES, "llm_verified_v2_n3/error_t/{m}/validation.json", "primary"),
        (REPO_FRE, "llm_verified_set/v2_n3/eval/validation/{m}/error_t.json", "primary"),
    ],
    (AXIS_LV, "clean"): [
        (REPO_RES, "llm_verified_v2_n3/clean/{m}/validation.json", "primary"),
        (REPO_FRE, "llm_verified_set/v2_n3/eval/validation/{m}/clean.json", "primary"),
    ],
}

# Conditions that provably have no cell anywhere yet.  Listed so the tables can
# say WHY a column is empty instead of just printing n/a.
LEGACY_ABSENT = {
    (AXIS_LV, "clean"): "LLM-verified clean-start runs are not published "
                        "(only mobilerun_gemini_pro_3.1 exists, without a scored "
                        "validation.json)",
    (AXIS_HV_SNAP, "t_plus_1_pos"): "t+1 was run on the 52-task replay subset only",
    (AXIS_HV_SNAP, "t_plus_1_neg"): "t+1 was run on the 52-task replay subset only",
}

#: Reasons that block ONE cell.  (model_id, axis, cond) -> why it cannot be read.
#: LEGACY_ABSENT covers a whole CONDITION being empty; this covers the case where
#: the condition does have a published file, but that file belongs to a
#: DIFFERENT RUN and so cannot stand for this model's cell.  The point is to
#: leave the value empty while stating the true reason -- the generic
#: "not published: tried <paths>" message would be false here.
LEGACY_ABSENT_CELL = {
    ("qwen3vl_8b", AXIS_HV_REP, "clean"):
        "the canonical qwen3vl_8b clean run is not published anywhere in FRE/RES "
        "(no .../validation/qwen3vl_8b/clean.json at any revision checked); the "
        "only published clean cell for this model is qwen3vl_8b.dup1 "
        "(29/65 = 44.62, valid=true), which FRE commit 1b555249 documents as a "
        "SECOND run on another workstation (1018 steps vs 1357, action sequence "
        "identical on 9 of 65) and commit 599d7a31 withdrew -- it is a different "
        "run, so it is NOT substituted for the paper's 38.5",
}


def _read_token(token_file):
    """Token from the environment, else from a token FILE.  Never from argv."""
    for var in ("HF_TOKEN", "HUGGINGFACE_HUB_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
        val = os.environ.get(var)
        if val:
            return val.strip()
    if token_file and os.path.exists(os.path.expanduser(token_file)):
        with open(os.path.expanduser(token_file)) as fh:
            return fh.read().strip()
    return None


class LegacyStore(BaseStore):
    """Adapter: presents the current repositories through the released layout.

    ``backend='hf'``     fetches https://huggingface.co/datasets/<repo>/resolve/<rev>/<path>
    ``backend='local'``  reads <legacy_root>/<repo-basename>/<path>
    """

    name = "adapter"

    def __init__(self, backend="hf", cache_dir=None, legacy_root=None,
                 revision="main", token_file="~/.hf_token", aw_root=None,
                 offline=False):
        self.backend = backend
        self.revision = revision
        self.offline = offline
        self.legacy_root = os.path.abspath(legacy_root) if legacy_root else None
        self.cache_dir = os.path.expanduser(
            cache_dir or "~/.cache/androidflux_score_tables")
        self.aw_root = os.path.abspath(aw_root) if aw_root else None
        self.token = _read_token(token_file) if backend == "hf" else None
        self._payloads = {}
        self._trees = {}
        if backend == "hf" and not self.token:
            DIAG.info("NO_TOKEN", "adapter",
                      "no HF token in env or token file; public reads may still work")
        if backend == "local" and not self.legacy_root:
            raise SystemExit("--adapter legacy requires --legacy-root")

    # -- transport -------------------------------------------------------
    def _local_path(self, repo, path):
        base = repo.split("/")[-1]
        return os.path.join(self.legacy_root, base, path)

    def _cache_path(self, repo, path):
        return os.path.join(self.cache_dir, self.revision, repo.replace("/", "__"), path)

    def _fetch(self, repo, path):
        """Return parsed JSON, or None when the file does not exist."""
        key = (repo, path)
        if key in self._payloads:
            return self._payloads[key]
        payload = None
        if self.backend == "local":
            p = self._local_path(repo, path)
            if os.path.exists(p):
                with open(p) as fh:
                    payload = json.load(fh)
        else:
            cached = self._cache_path(repo, path)
            if os.path.exists(cached):
                with open(cached) as fh:
                    try:
                        payload = json.load(fh)
                    except ValueError:
                        payload = None
            elif not self.offline:
                blob = self._http_get(self._resolve_url(repo, path))
                if blob is not None:
                    try:
                        os.makedirs(os.path.dirname(cached))
                    except OSError:
                        pass
                    with open(cached, "wb") as fh:
                        fh.write(blob)
                    try:
                        payload = json.loads(blob.decode("utf-8"))
                    except ValueError as exc:
                        DIAG.error("BAD_JSON", "%s:%s" % (repo, path), str(exc))
        self._payloads[key] = payload
        return payload

    def _resolve_url(self, repo, path):
        # TRAP: the commits API's ``path=`` filter does not work on this Hub;
        # to read an older value, pin --revision and hit resolve/<rev>/<path>
        # directly rather than trying to filter a commit list.
        from urllib.parse import quote
        return ("https://huggingface.co/datasets/%s/resolve/%s/%s"
                % (repo, self.revision, quote(path)))

    def _http_get(self, url, tries=3):
        import urllib.error
        import urllib.request
        headers = {"User-Agent": "androidflux-score-tables/1.0"}
        if self.token:
            headers["Authorization"] = "Bearer " + self.token
        for attempt in range(tries):
            try:
                req = urllib.request.Request(url, headers=headers)
                with urllib.request.urlopen(req, timeout=60) as resp:
                    return resp.read()
            except urllib.error.HTTPError as exc:
                if exc.code in (401, 403):
                    DIAG.error("HTTP_AUTH", url, "HTTP %d -- token missing or "
                               "not authorized" % exc.code)
                    return None
                if exc.code == 404:
                    return None
                if attempt == tries - 1:
                    DIAG.error("HTTP", url, "HTTP %d" % exc.code)
                    return None
            except Exception as exc:  # network hiccup
                if attempt == tries - 1:
                    DIAG.error("HTTP", url, repr(exc))
                    return None
        return None

    def hf_tree(self, repo):
        """Full recursive listing.

        TRAP: the tree API paginates via the ``Link: <...>; rel="next"`` header.
        Ignoring it truncates the listing at 50 entries.
        """
        import urllib.request
        if repo in self._trees:
            return self._trees[repo]
        headers = {"User-Agent": "androidflux-score-tables/1.0"}
        if self.token:
            headers["Authorization"] = "Bearer " + self.token
        url = ("https://huggingface.co/api/datasets/%s/tree/%s/?recursive=1&expand=0"
               % (repo, self.revision))
        out = []
        while url:
            req = urllib.request.Request(url, headers=headers)
            try:
                with urllib.request.urlopen(req, timeout=120) as resp:
                    out.extend(json.loads(resp.read().decode("utf-8")))
                    link = resp.headers.get("Link") or ""
            except Exception as exc:
                DIAG.error("HTTP", url, repr(exc))
                self._trees[repo] = out
                return out
            match = re.search(r'<([^>]+)>;\s*rel="next"', link)
            url = match.group(1) if match else None
        self._trees[repo] = out
        return out

    # -- store interface --------------------------------------------------
    def _candidates(self, axis, cond, model_id):
        model = MODELS.get(model_id)
        primary = model["dirs"][axis] if model else model_id
        aliases = [primary] + list(DIR_ALIASES.get((model_id, axis, cond), []))
        out = []
        for alias in aliases:
            for repo, template, kind in LEGACY_PATHS.get((axis, cond), []):
                out.append((repo, template.format(m=alias), kind, alias))
        return out, primary

    def get(self, axis, cond, model_id):
        # Short-circuit BEFORE building candidate paths: for these cells the
        # honest reason is "what is published is a different run", not the
        # generic "not published: tried ..." the loop below would produce.
        # Warned, not silently dropped.
        withheld = LEGACY_ABSENT_CELL.get((model_id, axis, cond))
        if withheld:
            DIAG.warn("CELL_WITHHELD", "%s %s/%s" % (model_id, axis, cond), withheld)
            return Cell.missing(withheld)
        cands, primary = self._candidates(axis, cond, model_id)
        if not cands:
            reason = LEGACY_ABSENT.get((axis, cond),
                                       "adapter has no path for (%s, %s)" % (axis, cond))
            return Cell.missing(reason)
        for repo, path, kind, alias in cands:
            payload = self._fetch(repo, path)
            if payload is None:
                continue
            where = "%s:%s" % (repo.split("/")[-1], path)
            cell = read_validation_payload(payload, where, axis, cond)
            cell = self._rescue_header_only(cell, repo, path, axis, cond)
            if kind == "mirror" and cell.present:
                cell.notes.append("mirror")
                DIAG.warn("MIRROR_SOURCE", where,
                          "primary path absent; value taken from a mirror tree")
            if alias != model_id:
                cell.notes.append("alias:%s" % alias)
            if alias != primary:
                DIAG.warn("DIR_ALIAS", "%s %s/%s" % (model_id, axis, cond),
                          "cell published under directory '%s', not '%s'"
                          % (alias, primary))
            return cell
        reason = LEGACY_ABSENT.get((axis, cond))
        if reason is None:
            reason = ("not published: tried %s"
                      % ", ".join("%s:%s" % (r.split("/")[-1], p)
                                  for r, p, _k, _a in cands))
        return Cell.missing(reason)

    def _rescue_header_only(self, cell, repo, path, axis, cond):
        """rows -> per_episode.json -> header, for the adapter trees.

        read_validation_payload sees ONE file, so the fallback cannot live
        there: only the store can still fetch the sibling.  _fetch is cached,
        so this costs at most one extra request per header-only cell (RES has
        no per-episode files at all, so it simply 404s and the header stands).
        """
        if cell.present and "header_only" not in cell.notes:
            return cell
        pe_path = per_episode_sibling(path)
        if pe_path is None:
            return cell
        pe_payload = self._fetch(repo, pe_path)
        if pe_payload is None:
            return cell
        pe_where = "%s:%s" % (repo.split("/")[-1], pe_path)
        pe = read_per_episode_payload(pe_payload, pe_where, axis, cond,
                                      note_absent=False)
        return adopt_per_episode(cell, pe, pe_where)

    def get_raw(self, axis, cond, model_id):
        cands, _ = self._candidates(axis, cond, model_id)
        for repo, path, _kind, _alias in cands:
            payload = self._fetch(repo, path)
            if payload is not None:
                return payload, "%s:%s" % (repo.split("/")[-1], path)
        return None, None

    def task_names(self, axis, cond, model_id):
        cands, _ = self._candidates(axis, cond, model_id)
        for repo, path, _kind, _alias in cands:
            payload = self._fetch(repo, path)
            if isinstance(payload, dict) and isinstance(payload.get("rows"), list):
                names = [r.get("task_name") for r in payload["rows"] if r.get("task_name")]
                if names:
                    return sorted(set(names))
        return None

    def list_models(self, axis, cond):
        found = set()
        for repo, template, _kind in LEGACY_PATHS.get((axis, cond), []):
            prefix = template.split("{m}")[0]
            suffix = template.split("{m}")[-1]
            if self.backend == "local":
                pattern = os.path.join(self.legacy_root, repo.split("/")[-1],
                                       prefix + "*" + suffix)
                for hit in globmod.glob(pattern):
                    rel = os.path.relpath(hit, os.path.join(self.legacy_root,
                                                            repo.split("/")[-1]))
                    found.add(rel[len(prefix):len(rel) - len(suffix)])
            else:
                for entry in self.hf_tree(repo):
                    p = entry.get("path", "")
                    if p.startswith(prefix) and p.endswith(suffix):
                        found.add(p[len(prefix):len(p) - len(suffix)])
        return sorted(x for x in found if x and "/" not in x)

    # -- AndroidWorld -----------------------------------------------------
    def _aw_files(self, model_id):
        """Locate sr_summary.json for a model under --aw-root."""
        if not self.aw_root:
            return []
        # The canonical model id is tried FIRST and the registry's run names
        # after it -- the same order NativeStore._aw_dir uses.  AW_RUNS.get()
        # or [model_id] dropped the canonical id whenever a registry entry
        # existed, so a directory literally named after the model was invisible.
        # When both exist, every hit is still collected and AW_AMBIGUOUS warns.
        runs = [model_id] + [r for r in (AW_RUNS.get(model_id) or [])
                             if r != model_id]
        hits = []
        for run in runs:
            for pattern in ("%s/sr_summary.json" % run,
                            "*/%s/sr_summary.json" % run,
                            "**/%s/sr_summary.json" % run):
                # recursive=True is required: without it glob treats "**" as a
                # single "*", so a run nested deeper than one level below
                # --aw-root was unreachable despite the documented "**" promise.
                for path in sorted(globmod.glob(os.path.join(self.aw_root, pattern),
                                                recursive=True)):
                    if path not in hits:
                        hits.append(path)
        return hits

    def get_aw(self, model_id):
        if not self.aw_root:
            return Cell.missing(
                "AndroidWorld runs are box-local, not on the Hub; pass --aw-root "
                "at a tree containing <run>/sr_summary.json")
        hits = self._aw_files(model_id)
        if not hits:
            return Cell.missing("no sr_summary.json under --aw-root for run(s) %s"
                                % (AW_RUNS.get(model_id) or [model_id]))
        if len(hits) > 1:
            DIAG.warn("AW_AMBIGUOUS", model_id,
                      "%d candidate runs: %s -- the appendix requires AW and "
                      "Scratch from ONE run; using the first"
                      % (len(hits), ", ".join(hits)))
        with open(hits[0]) as fh:
            return read_sr_summary_payload(json.load(fh), hits[0])

    def get_aw_scratch80(self, model_id, tasks80):
        if not self.aw_root:
            return Cell.missing("AndroidWorld runs are box-local; pass --aw-root")
        hits = self._aw_files(model_id)
        if not hits:
            return Cell.missing("no run located for %s" % model_id)
        run_dir = os.path.dirname(hits[0])
        # mobilerun_trajectory_index.json is what summarize_eval_sr.py actually
        # writes next to sr_summary.json; the three names above never existed.
        # It goes LAST so a normalised per_task.json still wins.  Caveat: that
        # index skips workers with zero trajectories, so it can be partial --
        # read_per_task_payload then raises SCRATCH80_INCOMPLETE and marks the
        # cell "!", which is why a partial file cannot pass silently.
        for name in ("per_task.json", "sr_index.json", "mobilerun_index.json",
                     "mobilerun_trajectory_index.json"):
            p = os.path.join(run_dir, name)
            if os.path.exists(p):
                with open(p) as fh:
                    return read_per_task_payload(json.load(fh), p, tasks80)
        return Cell.missing("no per_task.json next to %s (Scratch(80) needs "
                            "per-task scores)" % hits[0])


# ==============================================================================
# 9.  TABLE BUILDING
# ==============================================================================

def read_task_list_file(path):
    """scripts/scratch_80_tasks.txt: one task per line, optional second column."""
    if not path or not os.path.exists(path):
        return None
    names = []
    for line in open(path):
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        names.append(line.split()[0])
    return sorted(set(names)) or None


def resolve_tasks80(store, list_file=None):
    """Derive the 80 recovery tasks from the data; cross-check the constant."""
    # Both halves must come from the SAME model: mixing two models' entry sets
    # would silently build an 80-task set that no single run ever covered.
    replay, snap, donor = None, None, None
    for mid in ("qwen3vl_2b", "mai_ui_8b", "gui_owl_32b", "ma3_32b",
                "qwen3vl_4b", "guiowl15_8b"):
        r = store.task_names(AXIS_HV_REP, "t", mid)
        s = store.task_names(AXIS_HV_SNAP, "t", mid)
        if r and s:
            replay, snap, donor = r, s, mid
            break
    if donor:
        DIAG.info("TASKS80_SOURCE", "scratch80",
                  "task set derived from %s (%d replay + %d snapshot)"
                  % (donor, len(replay), len(snap)))
    if not replay or not snap:
        DIAG.warn("TASKS80_FALLBACK", "scratch80",
                  "could not derive the task set from HV cells; using the "
                  "embedded reference list of %d tasks" % len(TASKS_80_REFERENCE))
        return sorted(TASKS_80_REFERENCE)
    overlap = set(replay) & set(snap)
    if overlap:
        DIAG.warn("TASKS80_OVERLAP", "scratch80",
                  "replay_65 and snapshot_15 share %d task(s): %s"
                  % (len(overlap), ", ".join(sorted(overlap))))
    derived = sorted(set(replay) | set(snap))
    if len(derived) != SCRATCH80_DENOM:
        DIAG.warn("TASKS80_SIZE", "scratch80",
                  "derived %d tasks, expected %d (79 means a v3_14-era snapshot "
                  "manifest; the missing task is SimpleCalendarDeleteEvents)"
                  % (len(derived), SCRATCH80_DENOM))
    published = read_task_list_file(list_file)
    if published and set(published) != set(derived):
        DIAG.error("TASKS80_FILE", list_file or "scratch_80_tasks.txt",
                   "the published task list disagrees with the data: +%s -%s"
                   % (sorted(set(published) - set(derived)) or "[]",
                      sorted(set(derived) - set(published)) or "[]"))
    if set(derived) != set(TASKS_80_REFERENCE):
        only_d = sorted(set(derived) - set(TASKS_80_REFERENCE))
        only_r = sorted(set(TASKS_80_REFERENCE) - set(derived))
        DIAG.warn("TASKS80_DRIFT", "scratch80",
                  "derived set differs from the reference list: +%s -%s"
                  % (only_d or "[]", only_r or "[]"))
    return derived


def collect_model(store, model_id):
    """All cells and derived quantities for one model."""
    g = {}
    g["hv_clean"] = store.get(AXIS_HV_REP, "clean", model_id)
    g["hv_t_minus_5"] = store.get(AXIS_HV_REP, "t_minus_5", model_id)
    g["hv_t_minus_3"] = store.get(AXIS_HV_REP, "t_minus_3", model_id)
    g["hv_t_minus_1"] = store.get(AXIS_HV_REP, "t_minus_1", model_id)
    g["hv_t_rep"] = store.get(AXIS_HV_REP, "t", model_id)
    g["hv_t_snap"] = store.get(AXIS_HV_SNAP, "t", model_id)
    g["hv_tp1_pos"] = store.get(AXIS_HV_REP, "t_plus_1_pos", model_id)
    g["hv_tp1_neg"] = store.get(AXIS_HV_REP, "t_plus_1_neg", model_id)
    g["lv_clean"] = store.get(AXIS_LV, "clean", model_id)
    g["lv_t"] = store.get(AXIS_LV, "t", model_id)

    # t_all = (t_rep * 65 + t_snap * 15) / 80, i.e. the pooled 80-case rate.
    g["hv_t_all"] = derive([g["hv_t_rep"], g["hv_t_snap"]], T_ALL_DENOM,
                           "%s t_all" % model_id)
    if g["hv_t_all"].present and g["hv_t_rep"].present and g["hv_t_snap"].present:
        weighted = (g["hv_t_rep"].rate * g["hv_t_rep"].den
                    + g["hv_t_snap"].rate * g["hv_t_snap"].den) / T_ALL_DENOM
        if abs(weighted - g["hv_t_all"].rate) > 1e-9:
            DIAG.error("T_ALL_IDENTITY", model_id,
                       "pooled rate %.4f != weighted rate %.4f"
                       % (g["hv_t_all"].rate, weighted))

    # t+1_all = (positive + negative) / 104
    g["hv_tp1_all"] = derive([g["hv_tp1_pos"], g["hv_tp1_neg"]],
                             T_PLUS_1_ALL_DENOM, "%s t+1_all" % model_id)

    # An absent cell is a finding, not a blank.  Every n/a printed in a table
    # has a matching MISSING_CELL row in the diagnostics saying why.
    for col, cell in sorted(g.items()):
        if not cell.present:
            DIAG.warn("MISSING_CELL", "%s %s" % (model_id, COL_LABELS.get(col, (col,))[0]),
                      cell.missing_reason or "no cell")
    return g


def collect_aw(store, model_id, tasks80):
    out = {"aw": store.get_aw(model_id),
           "scratch80": store.get_aw_scratch80(model_id, tasks80)}
    for col, cell in sorted(out.items()):
        if not cell.present:
            DIAG.warn("MISSING_CELL", "%s %s" % (model_id, col),
                      cell.missing_reason or "no cell")
    return out


# ==============================================================================
# 10.  RENDERING
# ==============================================================================

LEGEND = ("Flags: `*` cell reported `valid=false` (start-state contract failed); "
          "`~` value taken from the file header because no per-episode rows were "
          "present, so the scoring rule could not be re-applied; "
          "`#` validation.json had no rows, so the rule was re-applied over the "
          "sibling per-episode file (the value is recomputed, not copied); "
          "`!` denominator read from the file differs from the expected one; "
          "`n/a` no such cell in this store (see Diagnostics for the reason).")


def md_table(header, rows, align=None):
    out = ["| " + " | ".join(header) + " |"]
    if align is None:
        align = ["---"] + ["---:"] * (len(header) - 1)
    out.append("| " + " | ".join(align) + " |")
    for r in rows:
        out.append("| " + " | ".join(r) + " |")
    return "\n".join(out)


def latex_table(caption, label, colspec, header_rows, body_rows, note=None):
    out = [r"\begin{table}[t]", r"\centering", r"\small",
           r"\begin{tabular}{%s}" % colspec, r"\toprule"]
    for hr in header_rows:
        out.append(" & ".join(hr) + r" \\")
    out.append(r"\midrule")
    for br in body_rows:
        out.append(" & ".join(br) + r" \\")
    out.append(r"\bottomrule")
    out.append(r"\end{tabular}")
    if note:
        out.append(r"\caption{%s}" % caption)
        out.append("%% %s" % note)
    else:
        out.append(r"\caption{%s}" % caption)
    out.append(r"\label{%s}" % label)
    out.append(r"\end{table}")
    return "\n".join(out)


def tex_escape(text):
    return (text.replace("\\", r"\textbackslash{}").replace("&", r"\&")
            .replace("_", r"\_").replace("%", r"\%").replace("#", r"\#"))


def build_tab1(data, show_counts):
    header = ["Model"] + [COL_LABELS[c][0] for c in TAB1_COLS]
    rows = []
    for mid in TAB1_ROWS:
        cells = data[mid]
        rows.append([MODELS[mid]["label"]] +
                    [cells[c].render(show_counts) for c in TAB1_COLS])
    md = ("### Table 1 -- `tab:hvlvcomparison`\n\n"
          "Human-verified (65 replay + 15 snapshot; t+1 on 52 matched tasks) vs. "
          "LLM-verified (312 entries = 104 tasks x 3 source trajectories).\n\n"
          + md_table(header, rows) + "\n\n" + LEGEND + "\n")
    tex_header = [["Model"] + [COL_LABELS[c][1] for c in TAB1_COLS]]
    tex_body = [[tex_escape(MODELS[mid]["label"])]
                + [data[mid][c].render(show_counts, latex=True)
                   .replace("n/a", r"\textemdash") for c in TAB1_COLS]
                for mid in TAB1_ROWS]
    tex = latex_table(
        "Human-verified (HV) vs.\\ LLM-verified (LV) sets on error recovery.",
        "tab:hvlvcomparison", "l" + "c" * len(TAB1_COLS), tex_header, tex_body)
    return md, tex


def build_tab2(data, show_counts):
    header = ["Type", "Model"] + [COL_LABELS[c][0] for c in TAB2_COLS]
    rows = []
    for mid in TAB2_ROWS:
        cells = data[mid]
        rows.append([MODELS[mid]["type"] or "", MODELS[mid]["label"]] +
                    [cells[c].render(show_counts) for c in TAB2_COLS])
    align = ["---", "---"] + ["---:"] * len(TAB2_COLS)
    md = ("### Table 2 -- `tab:modelclass`\n\n"
          "Failure recovery across agent architectures.\n\n"
          + md_table(header, rows, align) + "\n\n" + LEGEND + "\n")
    tex_header = [["Type", "Model"] + [COL_LABELS[c][1] for c in TAB2_COLS]]
    tex_body = [[tex_escape(MODELS[mid]["type"] or ""),
                 tex_escape(MODELS[mid]["label"])]
                + [data[mid][c].render(show_counts, latex=True)
                   .replace("n/a", r"\textemdash") for c in TAB2_COLS]
                for mid in TAB2_ROWS]
    tex = latex_table("Failure recovery across agent architectures.",
                      "tab:modelclass", "ll" + "c" * len(TAB2_COLS),
                      tex_header, tex_body)
    return md, tex


def build_tab3(data, show_counts):
    header = ["Model", "HV t Instruct", "HV t Reasoning", "LV t Instruct",
              "LV t Reasoning"]
    rows = []
    for family, instruct_id, reasoning_id in TAB3_ROWS:
        inst = data[instruct_id]
        reas = data[reasoning_id]
        rows.append([family,
                     inst["hv_t_all"].render(show_counts),
                     reas["hv_t_all"].render(show_counts),
                     inst["lv_t"].render(show_counts),
                     reas["lv_t"].render(show_counts)])
    md = ("### Table 3 -- `tab:instreason`\n\n"
          "Instruct vs. explicit chain-of-thought at the first-error checkpoint "
          "$t$.  The human-verified column is $t_{all}$ over 80 cases; the "
          "LLM-verified column is $t$ over 312 entries.\n\n"
          + md_table(header, rows) + "\n\n" + LEGEND + "\n")
    tex_header = [["Model", r"\multicolumn{2}{c}{Human-verified $t$}",
                   r"\multicolumn{2}{c}{LLM-verified $t$}"],
                  ["", "Instruct", "Reasoning", "Instruct", "Reasoning"]]
    tex_body = []
    for family, instruct_id, reasoning_id in TAB3_ROWS:
        tex_body.append([tex_escape(family)] + [
            c.render(show_counts, latex=True).replace("n/a", r"\textemdash")
            for c in (data[instruct_id]["hv_t_all"], data[reasoning_id]["hv_t_all"],
                      data[instruct_id]["lv_t"], data[reasoning_id]["lv_t"])])
    tex = latex_table("Instruct vs.\\ explicit Chain of Thought reasoning modes "
                      "at the first-error checkpoint $t$.",
                      "tab:instreason", "lcccc", tex_header, tex_body)
    return md, tex


def build_tab4(data, aw_data, show_counts):
    header = ["Model", "Type", "AW Correct", "AW SR (%)", "Scratch Correct",
              "Scratch SR (%)", "t_all Correct", "t_all SR (%)"]
    rows = []
    for mid in TAB4_ROWS:
        aw = aw_data[mid]["aw"]
        sc = aw_data[mid]["scratch80"]
        ta = data[mid]["hv_t_all"]

        def pair(cell, denom):
            if not cell.present:
                return ["n/a", "n/a"]
            return ["%d/%d" % (cell.num, denom),
                    "%.2f%s" % (cell.rate, cell.flags())]

        rows.append([MODELS[mid]["label"], MODELS[mid]["type"] or ""]
                    + pair(aw, AW_DENOM) + pair(sc, SCRATCH80_DENOM)
                    + pair(ta, T_ALL_DENOM))
        if mid in AW_DISPUTED:
            code, message = AW_DISPUTED[mid]
            DIAG.warn(code, mid, message)
    md = ("### Table 4 -- `tab:aw-vs-recovery`\n\n"
          "AndroidWorld clean-start success and human-verified recovery at $t$.  "
          "*AndroidWorld* is the 116-task Docker run; *Scratch* is the SAME run "
          "restricted to the 80 recovery tasks; $t_{all}$ replays the recorded "
          "prefix to the first-error checkpoint over the same 80 cases.\n\n"
          + md_table(header, rows, ["---", "---"] + ["---:"] * 6)
          + "\n\n" + LEGEND + "\n")
    tex_header = [["Model", "Type", r"\multicolumn{2}{c}{AndroidWorld (116)}",
                   r"\multicolumn{2}{c}{Scratch (80)}",
                   r"\multicolumn{2}{c}{$t_{\mathrm{all}}$ (80)}"],
                  ["", "", "Correct", "SR (\\%)", "Correct", "SR (\\%)",
                   "Correct", "SR (\\%)"]]
    tex_body = [[tex_escape(r[0]), tex_escape(r[1])] +
                [x.replace("n/a", r"\textemdash") for x in r[2:]] for r in rows]
    tex = latex_table("AndroidWorld clean-start success and human-verified "
                      "recovery at the first-error checkpoint.",
                      "tab:aw-vs-recovery", "llcccccc", tex_header, tex_body)
    return md, tex


# ==============================================================================
# 11.  PAPER COMPARISON (--compare-paper main.md)
# ==============================================================================

NUM_RE = re.compile(r"^-?\d+(?:\.\d+)?$")


def _strip_label(text):
    text = re.sub(r"\[@[^\]]*\]", "", text)
    text = re.sub(r"\\?\$[^$]*\$", "", text)
    text = re.sub(r"\s+", " ", text)
    return text.strip(" *")


def parse_grid_table(block):
    """Parse a pandoc grid table into a list of rows of joined cell strings."""
    rows, current = [], []
    for line in block.splitlines():
        if line.startswith("+") and set(line) <= set("+-=: "):
            if current:
                rows.append(current)
                current = []
            continue
        if not line.startswith("|"):
            continue
        cells = [c.strip() for c in line.strip().strip("|").split("|")]
        if not current:
            current = cells
        else:
            for i, c in enumerate(cells):
                if i < len(current):
                    if c:
                        current[i] = (current[i] + " " + c).strip()
                else:
                    current.append(c)
    if current:
        rows.append(current)
    return rows


def extract_block(text, start_marker, end_marker=":::"):
    i = text.find(start_marker)
    if i < 0:
        return None
    j = text.find("\n" + end_marker, i)
    return text[i:j if j > 0 else len(text)]


def parse_paper(md_path):
    """Extract the four tables' numbers from the manuscript."""
    with open(md_path) as fh:
        text = fh.read()
    paper = {}

    # -- tab:hvlvcomparison (grid table) --------------------------------
    block = extract_block(text, "::: {#tab:hvlvcomparison}")
    values = {}
    if block:
        for row in parse_grid_table(block):
            if not row:
                continue
            label = _strip_label(row[0])
            nums = [c for c in row[1:] if NUM_RE.match(c.strip())]
            if len(nums) >= 10 and label:
                values[label] = [float(x) for x in nums]
    paper["tab:hvlvcomparison"] = values

    # -- tab:modelclass (latex tabular inside ::: tabular) ---------------
    values = {}
    idx = text.find("Qwen3-VL-8B-Instruct &")
    if idx > 0:
        start = text.rfind("::: tabular", 0, idx)
        end = text.find("\n:::", idx)
        block = text[start:end]
        for chunk in block.split("\\\n"):
            # the final row of the block keeps its trailing "\\"
            parts = [p.strip().rstrip("\\").strip()
                     for p in chunk.replace("\n", " ").split("&")]
            nums = [p for p in parts if NUM_RE.match(p)]
            labels = [_strip_label(p) for p in parts if not NUM_RE.match(p)]
            labels = [l for l in labels if l and not l.startswith("(lr)")]
            if len(nums) >= 9 and labels:
                values[labels[-1]] = [float(x) for x in nums]
    paper["tab:modelclass"] = values

    # -- tab:instreason (grid table) ------------------------------------
    block = extract_block(text, "::: {#tab:instreason}")
    values = {}
    if block:
        for row in parse_grid_table(block):
            if not row:
                continue
            label = _strip_label(row[0])
            if not label or label.lower().startswith("model"):
                continue
            cells = row[1:5]
            if any(NUM_RE.match(c) for c in cells):
                values[label] = [float(c) if NUM_RE.match(c) else None for c in cells]
    paper["tab:instreason"] = values

    # -- tab:aw-vs-recovery (grid table with n/d cells) -----------------
    block = extract_block(text, "::: {#tab:aw-vs-recovery}")
    values = {}
    if block:
        for row in parse_grid_table(block):
            if not row or len(row) < 8:
                continue
            label = _strip_label(row[0])
            nums = []
            for c in row[2:]:
                c = c.strip()
                m = re.match(r"^(\d+)/(\d+)$", c)
                if m:
                    nums.append(float(m.group(1)))
                elif NUM_RE.match(c):
                    nums.append(float(c))
            if len(nums) >= 6 and label and not label.lower().startswith("model"):
                values[label] = nums[:6]
    paper["tab:aw-vs-recovery"] = values
    return paper


# Paper row label -> registry model id, per table.  Labels are matched exactly
# after citations and math are stripped; nothing is matched by value.
PAPER_LABEL_TO_ID = {
    "Qwen3-VL-2B-Instruct": "qwen3vl_2b",
    "Qwen3-VL-4B-Instruct": "qwen3vl_4b",
    "Qwen3-VL-8B-Instruct": "qwen3vl_8b",
    "Qwen3-VL-30B-A3B-Instruct": "qwen3vl_30b_a3b",
    "Qwen3-VL-32B-Instruct": "qwen3vl_32b",
    "Qwen3-VL-4B-Thinking": "qwen3vl_4b_think",
    "Qwen3-VL-8B-Thinking": "qwen3vl_8b_think",
    "GUI-Owl-32B-Instruct": "gui_owl_32b",
    "GUI-Owl-32B": "gui_owl_32b",
    "GUI-Owl-7B": "gui_owl_7b",
    "GUI-Owl-1.5-2B": "guiowl15_2b",
    "GUI-Owl-1.5-4B": "guiowl15_4b",
    "GUI-Owl-1.5-8B": "guiowl15_8b",
    "GUI-Owl-1.5-32B": "guiowl15_32b",
    "GUI-Owl-1.5-8B-Thinking": "guiowl15_8b_think",
    "Mobile-Agent-v3-32B": "ma3_32b",
    "Mobile-Agent-v3-7B": "ma3_7b",
    "MAI-UI-8B": "mai_ui_8b",
    "MAI-UI-2B": "mai_ui_2b",
    "Gemini Flash 3.0": "gemini_3_0_flash_preview_qwen_prompt_think_on",
    "Gemini Flash 3.0 (Qwen3-VL prompt, think off)":
        "gemini_3_0_flash_preview_qwen_prompt_think_off",
    "Gemini Flash 3.5 (Qwen3-VL prompt)": "gemini_3_5_flash_qwen_prompt",
    "Gemini Flash 3.5 Computer Use": "gemini_3_5_flash_computer_use_task_only",
    "Gemma-4-31B-IT (M3A)": "gemma_4_31b_it_improved_m3a_think_off",
    "MobileRun": "mobilerun_gemini_flash_3.0",
    "MobileRun (Gemini Flash 3.0)": "mobilerun_gemini_flash_3.0",
    "FinalRun": "gemini_3_0_flash_preview_final_run_appinfo_from_gui_owl",
    "FinalRun (M3A + app knowledge)":
        "gemini_3_0_flash_preview_final_run_appinfo_from_gui_owl",
    "UI-TARS-1.0-7B-SFT": "ui_tars_7b_sft",
    "UI-TARS-1.5-7B": "ui_tars_1_5_7b",
}

TAB3_LABEL_TO_ROW = {family: (family, i, r) for family, i, r in TAB3_ROWS}


def compare_with_paper(paper, data, aw_data, tolerance):
    """Return (rows, counters).  Nothing is matched by value; only by (model, column)."""
    rows = []
    counters = {"MATCH": 0, "MISMATCH": 0, "NO_DATA": 0, "NO_PAPER_VALUE": 0,
                "UNMAPPED": 0}

    def emit(table, label, column, paper_value, cell):
        computed = cell.rate if (cell is not None and cell.present) else None
        if paper_value is None and computed is None:
            return
        if paper_value is None:
            status = "NO_PAPER_VALUE"
            delta = ""
        elif computed is None:
            status = "NO_DATA"
            delta = ""
        else:
            delta = computed - paper_value
            status = "MATCH" if abs(delta) <= tolerance else "MISMATCH"
            delta = "%+.2f" % delta
        counters[status] += 1
        rows.append({
            "table": table, "row": label, "column": column,
            "paper": ("" if paper_value is None else "%.2f" % paper_value),
            "computed": ("" if computed is None else "%.2f" % computed),
            "counts": ("" if computed is None else "%d/%d" % (cell.num, cell.den)),
            "delta": delta, "status": status,
            "note": (cell.missing_reason or "") if computed is None else
                    ("valid=false" if cell.valid is False else ""),
        })

    # Table 1
    for label, values in sorted(paper.get("tab:hvlvcomparison", {}).items()):
        mid = PAPER_LABEL_TO_ID.get(label)
        if mid is None or mid not in data:
            counters["UNMAPPED"] += 1
            rows.append({"table": "tab:hvlvcomparison", "row": label, "column": "*",
                         "paper": "", "computed": "", "counts": "", "delta": "",
                         "status": "UNMAPPED",
                         "note": "no registry entry for this paper label"})
            continue
        for col, value in zip(TAB1_COLS, values):
            emit("tab:hvlvcomparison", label, COL_LABELS[col][0], value, data[mid][col])

    # Table 2
    for label, values in sorted(paper.get("tab:modelclass", {}).items()):
        mid = PAPER_LABEL_TO_ID.get(label)
        if mid is None or mid not in data:
            counters["UNMAPPED"] += 1
            rows.append({"table": "tab:modelclass", "row": label, "column": "*",
                         "paper": "", "computed": "", "counts": "", "delta": "",
                         "status": "UNMAPPED",
                         "note": "no registry entry for this paper label"})
            continue
        for col, value in zip(TAB2_COLS, values):
            emit("tab:modelclass", label, COL_LABELS[col][0], value, data[mid][col])

    # Table 3
    for label, values in sorted(paper.get("tab:instreason", {}).items()):
        entry = TAB3_LABEL_TO_ROW.get(label)
        if entry is None:
            counters["UNMAPPED"] += 1
            rows.append({"table": "tab:instreason", "row": label, "column": "*",
                         "paper": "", "computed": "", "counts": "", "delta": "",
                         "status": "UNMAPPED", "note": "not a tab:instreason family"})
            continue
        _, inst_id, reas_id = entry
        pairs = [("HV t Instruct", data[inst_id]["hv_t_all"]),
                 ("HV t Reasoning", data[reas_id]["hv_t_all"]),
                 ("LV t Instruct", data[inst_id]["lv_t"]),
                 ("LV t Reasoning", data[reas_id]["lv_t"])]
        for (colname, cell), value in zip(pairs, values):
            emit("tab:instreason", label, colname, value, cell)

    # Table 4 (paper reports Correct and SR; comparing SR covers both)
    for label, values in sorted(paper.get("tab:aw-vs-recovery", {}).items()):
        mid = PAPER_LABEL_TO_ID.get(label)
        if mid is None or mid not in data:
            counters["UNMAPPED"] += 1
            rows.append({"table": "tab:aw-vs-recovery", "row": label, "column": "*",
                         "paper": "", "computed": "", "counts": "", "delta": "",
                         "status": "UNMAPPED",
                         "note": "no registry entry for this paper label"})
            continue
        cells = [("AW correct", aw_data[mid]["aw"], AW_DENOM),
                 ("AW SR", aw_data[mid]["aw"], None),
                 ("Scratch correct", aw_data[mid]["scratch80"], SCRATCH80_DENOM),
                 ("Scratch SR", aw_data[mid]["scratch80"], None),
                 ("t_all correct", data[mid]["hv_t_all"], T_ALL_DENOM),
                 ("t_all SR", data[mid]["hv_t_all"], None)]
        for (colname, cell, as_count), value in zip(cells, values):
            if as_count is not None:
                computed = float(cell.num) if cell.present else None
                if value is None and computed is None:
                    continue
                if computed is None:
                    counters["NO_DATA"] += 1
                    status, delta, shown = "NO_DATA", "", ""
                else:
                    delta_v = computed - value
                    status = "MATCH" if abs(delta_v) < 0.5 else "MISMATCH"
                    counters[status] += 1
                    delta = "%+.0f" % delta_v
                    shown = "%.0f" % computed
                rows.append({"table": "tab:aw-vs-recovery", "row": label,
                             "column": colname, "paper": "%.0f" % value,
                             "computed": shown, "counts": "", "delta": delta,
                             "status": status,
                             "note": (cell.missing_reason or "") if computed is None
                                     else aw_dispute_note(mid)})
            else:
                emit("tab:aw-vs-recovery", label, colname, value, cell)
    return rows, counters


def render_comparison(rows, counters, tolerance):
    header = ["Table", "Row", "Column", "Paper", "Computed", "n/d", "Delta",
              "Status", "Note"]
    body = [[r["table"], r["row"], r["column"], r["paper"], r["computed"],
             r["counts"], r["delta"], r["status"],
             (r["note"] or "").replace("|", "\\|")[:160]] for r in rows]
    summary = "  ".join("%s=%d" % (k, counters[k]) for k in sorted(counters))
    return ("## Paper comparison\n\n"
            "Tolerance %.2f pp (the manuscript prints one decimal place).  "
            "Rows are matched by (model, column) from the registry -- never by "
            "value, because identical values recur across models.\n\n"
            "**%s**\n\n" % (tolerance, summary)
            + md_table(header, body, align=["---"] * len(header)) + "\n")


# ==============================================================================
# 12.  MAIN
# ==============================================================================

TABLE_KEYS = {
    "tab:hvlvcomparison": "hvlv",
    "tab:modelclass": "modelclass",
    "tab:instreason": "instreason",
    "tab:aw-vs-recovery": "aw",
    "hvlv": "hvlv", "modelclass": "modelclass",
    "instreason": "instreason", "aw": "aw",
}

VERIFY_FATAL = ("HEADER_DISAGREES", "DENOM_MISMATCH", "NO_COUNTS", "BAD_SCHEMA",
                "BAD_SR_SUMMARY", "T_ALL_IDENTITY", "TASKS80_FILE",
                "TASKS80_SIZE", "TASKS80_OVERLAP", "DERIVED_DENOM",
                "ENTRY_NOT_UNIQUE", "ENTRY_AMBIGUOUS")


def score_histogram(rows):
    hist = {}
    for r in rows:
        score = _score_of(r)
        key = "missing" if score is None else ("%.1f" % score)
        hist[key] = hist.get(key, 0) + 1
    return hist


def explain_cell(store, cell_path):
    """--cell <axis>/<subset>/<cond>/<model> --explain"""
    parts = [x for x in cell_path.strip("/").split("/") if x]
    if len(parts) == 4:
        axis, cond, model_id = "%s/%s" % (parts[0], parts[1]), parts[2], parts[3]
    elif len(parts) == 3 and parts[0] == AXIS_AW:
        axis, cond, model_id = AXIS_AW, None, parts[2]
    elif len(parts) == 2 and parts[0] == AXIS_AW:
        axis, cond, model_id = AXIS_AW, None, parts[1]
    else:
        sys.stderr.write("cell path must be <axis>/<subset>/<condition>/<model> "
                         "or androidworld/<run>\n")
        return 1

    print(cell_path)
    if axis == AXIS_AW:
        cell = store.get_aw(model_id)
        print("  rule          %s            (sr_summary.json: total.successes)"
              % SCORING["sr_summary"])
        if not cell.present:
            print("  MISSING       %s" % cell.missing_reason)
            return 1
        print("  success       %d / %d  = %.2f %%" % (cell.num, cell.den, cell.rate))
        print("  source        %s" % cell.source)
        if model_id in AW_DISPUTED:
            code, message = AW_DISPUTED[model_id]
            print("  disputed      [%s] %s" % (code, message))
        return 0

    payload, where = store.get_raw(axis, cond, model_id)
    cell = store.get(axis, cond, model_id)
    print("  rule          %s            (validation.json: rows[].score)"
          % SCORING["validation"])
    if payload is None or not cell.present:
        print("  MISSING       %s" % (cell.missing_reason or "no payload"))
        return 1
    rows = payload.get("rows") or []
    if rows:
        hist = score_histogram(rows)
        print("  scores        " + "   ".join("%s x%d" % (k, hist[k])
                                              for k in sorted(hist)))
        alt = sum(1 for r in rows if is_success_sr_summary(r))
        print("  success       %d / %d  = %.2f %%" % (cell.num, cell.den, cell.rate))
        print("  alt rule      %d / %d  = %.2f %%   (%s)"
              % (alt, cell.den, 100.0 * alt / cell.den, SCORING["sr_summary"]))
    else:
        print("  success       %d / %d  = %.2f %%   (header only, no rows)"
              % (cell.num, cell.den, cell.rate))
    counts = {}
    for issue in (payload.get("issues") or []):
        name = issue.get("issue", "?")
        counts[name] = counts.get(name, 0) + 1
    print("  valid         %-8s issues: %s"
          % (payload.get("valid"),
             ", ".join("%s %d" % (k, counts[k]) for k in sorted(counts)) or "none"))
    print("  header        success_count=%s result_count=%s expected_entries=%s"
          % (payload.get("success_count"), payload.get("result_count"),
             payload.get("expected_entries")))
    print("  entry set     %s" % (payload.get("entry_set") or "-"))
    print("  model_key     %s   (NOT an identifier -- keys are shared across "
          "directories)" % payload.get("model_key"))
    print("  source        %s" % where)
    return 0


def run_verify(store, tasks80):
    """Recompute every registry cell and fail on any internal disagreement."""
    ids = set(TAB1_ROWS) | set(TAB2_ROWS) | set(TAB4_ROWS)
    for _f, i, r in TAB3_ROWS:
        ids.add(i)
        ids.add(r)
    seen = 0
    for mid in sorted(ids):
        for axis in (AXIS_HV_REP, AXIS_HV_SNAP, AXIS_LV):
            for cond in CONDS:
                if (axis, cond) not in EXPECTED_DENOM:
                    continue
                cell = store.get(axis, cond, mid)
                if cell.present:
                    seen += 1
        store.get_aw(mid)
        store.get_aw_scratch80(mid, tasks80)
    fatal = [i for i in DIAG.items
             if i["severity"] == "ERROR" or i["code"] in VERIFY_FATAL]
    print("# verify -- %d cell(s) recomputed, %d fatal finding(s)"
          % (seen, len(fatal)))
    for i in fatal:
        print("  %-7s %-18s %s\n          %s"
              % (i["severity"], i["code"], i["where"], i["message"]))
    return 1 if fatal else 0


def build_store(args):
    if args.root:
        return NativeStore(args.root, aw_root=args.aw_root)
    if args.adapter == "hf":
        return LegacyStore(backend="hf", cache_dir=args.cache_dir,
                           revision=args.revision, token_file=args.token_file,
                           aw_root=args.aw_root, offline=args.offline)
    if args.adapter == "legacy":
        return LegacyStore(backend="local", legacy_root=args.legacy_root,
                           aw_root=args.aw_root)
    raise SystemExit("give --root <Evaluation_Output>, or --adapter hf, "
                     "or --adapter legacy --legacy-root <dir>")


def audit_mirror_divergence(store):
    """Cells whose primary and mirror disagree, and siblings left un-refreshed.

    ``get()`` returns the first readable candidate, so once a primary exists the
    mirror is never read and a stale mirror is invisible.  That silence hides two
    real defects we hit on ``guiowl15_32b error_t``:

      * the mirror still carries the pre-rerun value (3/65 next to a primary 18/65)
      * the rerun publish refreshed ``validation`` and ``per_episode`` but NOT
        ``per_step``, so the cell served new scores beside old steps

    The second is only detectable by comparing the sibling file against the mirror:
    a per_step that is byte-identical to the superseded tree was never re-published.
    """
    print("# Mirror divergence audit -- store: %s\n" % store.name)
    rows = []
    for axis in (AXIS_HV_REP, AXIS_HV_SNAP):
        for cond in CONDS:
            for model_id in sorted(MODELS):
                cands, _ = store._candidates(axis, cond, model_id)
                prim = [c for c in cands if c[2] == "primary"]
                mirr = [c for c in cands if c[2] == "mirror"]
                if not prim or not mirr:
                    continue
                pp = store._fetch(prim[0][0], prim[0][1])
                mp = store._fetch(mirr[0][0], mirr[0][1])
                if pp is None or mp is None:
                    continue
                pc = read_validation_payload(pp, "primary", axis, cond)
                mc = read_validation_payload(mp, "mirror", axis, cond)
                if pc.num == mc.num:
                    continue
                stale = _sibling_is_stale(store, prim[0], mirr[0], pc.num, mc.num)
                rows.append((model_id, axis, cond, pc.num, mc.num, stale))
                DIAG.warn("MIRROR_DIVERGED", "%s %s/%s" % (model_id, axis, cond),
                          "primary %s vs mirror %s -- the mirror predates a rerun"
                          % (pc.num, mc.num))
                if stale:
                    DIAG.warn("SIBLING_NOT_REFRESHED", "%s %s/%s" % (model_id, axis, cond),
                              "%s is byte-identical to the superseded tree: the rerun "
                              "published new scores but kept the old intermediate steps"
                              % stale)
    if not rows:
        print("no cell has a primary and a mirror that disagree.\n")
        return
    print("| Model | Axis | Condition | Primary | Mirror | Un-refreshed sibling |")
    print("| --- | --- | --- | ---: | ---: | --- |")
    for m, a, c, pn, mn, st in rows:
        print("| %s | %s | %s | %s | %s | %s |" % (m, a, c, pn, mn, st or "--"))
    print("")


def _sibling_is_stale(store, prim, mirr, primary_num=None, mirror_num=None):
    """Name the sibling file the rerun forgot to re-publish, or None.

    Compares each sibling kind by content: identical bytes across the primary and
    the superseded mirror mean that file was never rewritten.
    """
    # ``_fetch`` returns parsed JSON, so compare canonical content rather than
    # raw bytes -- a file re-serialised with different whitespace but identical
    # content is still un-refreshed, and byte equality would miss that.
    #
    # Identical content is NOT by itself proof of staleness.  It also happens when
    # the mirror's sibling was already correct and only the mirror's own
    # ``validation`` is the outlier -- that is the ``mobilerun_gemini_flash_3.0
    # t_minus_1`` shape, where both per_episode files carry 41 and only the mirror
    # validation says 19.  So when the sibling can be scored, ask which side it
    # agrees with: agreeing with the primary means it is current, not stale.
    for kind in ("per_episode", "per_step"):
        pth_p = prim[1].replace("/validation/", "/%s/" % kind)
        pth_m = mirr[1].replace("/validation/", "/%s/" % kind)
        if pth_p == prim[1] or pth_m == mirr[1]:
            continue
        a = store._fetch(prim[0], pth_p)
        b = store._fetch(mirr[0], pth_m)
        if a is None or b is None:
            continue
        ca = json.dumps(a, sort_keys=True, separators=(",", ":"))
        cb = json.dumps(b, sort_keys=True, separators=(",", ":"))
        if ca != cb:
            continue
        scored = _count_successes(a)
        if scored is None:
            # per_step carries no verdicts, so content identity is all we have.
            return ("%s (%d chars, identical to the superseded tree; carries no "
                    "verdicts so this is suggestive, not conclusive)" % (kind, len(ca)))
        if scored == primary_num:
            continue          # current, and the mirror's validation is the outlier
        return ("%s (%d chars, scores %s -- matches the superseded %s, not the "
                "published %s)" % (kind, len(ca), scored, mirror_num, primary_num))
    return None


def _count_successes(payload):
    """Successes in a per_episode payload, or None when it carries no verdicts."""
    rows = payload if isinstance(payload, list) else (
        payload.get("rows") or payload.get("episodes") or payload.get("per_episode") or [])
    if not rows or not isinstance(rows[0], dict):
        return None
    if not any(k in rows[0] for k in ("is_successful", "success", "score")):
        return None
    n = 0
    for r in rows:
        if r.get("is_successful") or r.get("success") or (r.get("score") or 0) > 0:
            n += 1
    return n


def run_audit(store):
    audit_mirror_divergence(store)
    print("# Cell audit -- store: %s\n" % store.name)
    for axis in (AXIS_HV_REP, AXIS_HV_SNAP, AXIS_LV):
        for cond in CONDS:
            if (axis, cond) not in EXPECTED_DENOM and (axis, cond) not in LEGACY_PATHS:
                continue
            models = store.list_models(axis, cond)
            print("## %s / %s  (%d model dir(s))" % (axis, cond, len(models)))
            if models:
                print("   " + ", ".join(models))
            print("")


_audit_aw_runs()


def main(argv=None):
    ap = argparse.ArgumentParser(
        description="Reproduce the AndroidFlux paper tables from Evaluation_Output.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__)
    ap.add_argument("--root", help="root of the released Evaluation_Output tree")
    ap.add_argument("--adapter", choices=["hf", "legacy"],
                    help="read the current repositories instead of --root")
    ap.add_argument("--legacy-root", help="local mirror root for --adapter legacy")
    ap.add_argument("--cache-dir", help="download cache for --adapter hf "
                    "(default ~/.cache/androidflux_score_tables)")
    ap.add_argument("--revision", default="main",
                    help="dataset revision for --adapter hf; use this to read an "
                         "older value (resolve/<rev>/<path>), because the commits "
                         "API path filter does not work")
    ap.add_argument("--token-file", default="~/.hf_token",
                    help="file holding the HF token; the token itself is never "
                         "accepted on argv (env HF_TOKEN wins)")
    ap.add_argument("--offline", action="store_true",
                    help="use only what is already in --cache-dir")
    ap.add_argument("--aw-root", help="tree containing AndroidWorld <run>/sr_summary.json")
    ap.add_argument("--all", action="store_true",
                    help="emit every paper table (the default)")
    ap.add_argument("--table", action="append", metavar="LABEL",
                    help="emit one table; repeatable.  Accepts the paper label "
                         "(tab:hvlvcomparison, tab:modelclass, tab:instreason, "
                         "tab:aw-vs-recovery) or the short name")
    ap.add_argument("--tables", default="all",
                    help="comma-separated subset of: hvlv,modelclass,instreason,aw")
    ap.add_argument("--cell", metavar="PATH",
                    help="one cell, e.g. human_verified/replay_65/t_plus_1_pos/ma3_32b")
    ap.add_argument("--explain", action="store_true",
                    help="with --cell: print numerator, denominator, rule, score "
                         "histogram, and the contract result")
    ap.add_argument("--verify", action="store_true",
                    help="recompute every cell and exit non-zero on any header, "
                         "denominator, or identity disagreement")
    ap.add_argument("--task-list", metavar="FILE",
                    help="scripts/scratch_80_tasks.txt to cross-check the derived "
                         "80-task set against (auto-detected under --root)")
    ap.add_argument("--format", default="both",
                    choices=["md", "latex", "both", "json"])
    ap.add_argument("--out", help="write files into this directory instead of stdout")
    ap.add_argument("--show-counts", action="store_true",
                    help="print n/d = rate instead of rate alone")
    ap.add_argument("--compare-paper", metavar="MAIN_MD",
                    help="diff the computed tables against the manuscript")
    ap.add_argument("--tolerance", type=float, default=0.06,
                    help="comparison tolerance in percentage points (default 0.06)")
    ap.add_argument("--audit", action="store_true",
                    help="list every model directory the store can see, then exit")
    ap.add_argument("--strict", action="store_true",
                    help="exit 1 if any cell is missing, invalid, or mismatched")
    args = ap.parse_args(argv)

    store = build_store(args)
    if args.audit:
        run_audit(store)
        return 0

    task_list = args.task_list
    if not task_list and args.root:
        guess = os.path.join(args.root, "scripts", "scratch_80_tasks.txt")
        if os.path.exists(guess):
            task_list = guess

    if args.cell:
        return explain_cell(store, args.cell)

    if args.verify:
        tasks80 = resolve_tasks80(store, task_list)
        return run_verify(store, tasks80)

    if args.table:
        wanted = []
        for name in args.table:
            key = TABLE_KEYS.get(name.strip())
            if key is None:
                raise SystemExit("unknown --table %r; use one of %s"
                                 % (name, ", ".join(sorted(TABLE_KEYS))))
            wanted.append(key)
    elif args.tables != "all" and not args.all:
        wanted = []
        for name in args.tables.split(","):
            key = TABLE_KEYS.get(name.strip())
            if key is None:
                raise SystemExit("unknown table %r" % name)
            wanted.append(key)
    else:
        wanted = ["hvlv", "modelclass", "instreason", "aw"]

    tasks80 = resolve_tasks80(store, task_list)

    needed = set(TAB1_ROWS) | set(TAB2_ROWS) | set(TAB4_ROWS)
    for _f, i, r in TAB3_ROWS:
        needed.add(i)
        needed.add(r)
    data = {}
    for mid in sorted(needed):
        data[mid] = collect_model(store, mid)
    aw_data = {}
    for mid in TAB4_ROWS:
        aw_data[mid] = collect_aw(store, mid, tasks80)

    md_parts = ["# AndroidFlux paper tables",
                "",
                "Store: `%s`   Scoring: validation `%s`, sr_summary `%s`"
                % (store.name, SCORING["validation"], SCORING["sr_summary"]),
                "Denominators: AndroidWorld %d (fixed) | Scratch %d | "
                "$t_{all}$ %d | HV replay 65 | HV snapshot 15 | "
                "$t{+}1$ 52 per arm, %d pooled | LV 312"
                % (AW_DENOM, SCRATCH80_DENOM, T_ALL_DENOM, T_PLUS_1_ALL_DENOM),
                "Feasible $t{-}n$ prefixes (auxiliary; the denominator stays 65): "
                + ", ".join("%s %d/65" % (k, v) for k, v in sorted(FEASIBLE.items())),
                ""]
    tex_parts = []

    builders = [("hvlv", lambda: build_tab1(data, args.show_counts)),
                ("modelclass", lambda: build_tab2(data, args.show_counts)),
                ("instreason", lambda: build_tab3(data, args.show_counts)),
                ("aw", lambda: build_tab4(data, aw_data, args.show_counts))]
    for key, fn in builders:
        if key not in wanted:
            continue
        md, tex = fn()
        md_parts.append(md)
        tex_parts.append(tex)

    compare_md = ""
    exit_code = 0
    if args.compare_paper:
        paper = parse_paper(args.compare_paper)
        empty = [k for k, v in paper.items() if not v]
        if empty:
            DIAG.error("PAPER_PARSE", args.compare_paper,
                       "no rows parsed for: %s" % ", ".join(empty))
        rows, counters = compare_with_paper(paper, data, aw_data, args.tolerance)
        compare_md = render_comparison(rows, counters, args.tolerance)
        md_parts.append(compare_md)
        if counters["MISMATCH"] or counters["UNMAPPED"]:
            exit_code = 2

    md_parts.append("## Diagnostics\n\n" + DIAG.render_markdown())
    md_out = "\n".join(md_parts)
    tex_out = "\n\n".join(tex_parts) + "\n"

    if args.format == "json":
        payload = {
            "scoring": SCORING,
            "denominators": {"androidworld": AW_DENOM, "scratch_80": SCRATCH80_DENOM,
                             "t_all": T_ALL_DENOM, "t_plus_1_all": T_PLUS_1_ALL_DENOM,
                             "expected": {"%s|%s" % k: v
                                          for k, v in EXPECTED_DENOM.items()}},
            "cells": {mid: {col: {"num": c.num, "den": c.den,
                                  "rate": c.rate, "valid": c.valid,
                                  "issues": c.issues, "source": c.source,
                                  "notes": c.notes,
                                  "missing_reason": c.missing_reason}
                            for col, c in cells.items()}
                      for mid, cells in data.items()},
            "androidworld": {mid: {col: {"num": c.num, "den": c.den, "rate": c.rate,
                                         "source": c.source,
                                         "missing_reason": c.missing_reason}
                                   for col, c in cells.items()}
                             for mid, cells in aw_data.items()},
            "diagnostics": DIAG.items,
        }
        text = json.dumps(payload, indent=2, sort_keys=True)
        if args.out:
            try:
                os.makedirs(args.out)
            except OSError:
                pass
            with open(os.path.join(args.out, "tables.json"), "w") as fh:
                fh.write(text + "\n")
            print("wrote %s" % os.path.join(args.out, "tables.json"))
        else:
            print(text)
        return exit_code

    if args.out:
        try:
            os.makedirs(args.out)
        except OSError:
            pass
        if args.format in ("md", "both"):
            with open(os.path.join(args.out, "tables.md"), "w") as fh:
                fh.write(md_out)
        if args.format in ("latex", "both"):
            with open(os.path.join(args.out, "tables.tex"), "w") as fh:
                fh.write(tex_out)
        with open(os.path.join(args.out, "diagnostics.json"), "w") as fh:
            json.dump(DIAG.items, fh, indent=2)
        print("wrote %s" % args.out)
    else:
        if args.format in ("md", "both"):
            print(md_out)
        if args.format in ("latex", "both"):
            print("\n" + tex_out)

    missing = sum(1 for m in data.values() for c in m.values() if not c.present)
    invalid = sum(1 for m in data.values() for c in m.values() if c.valid is False)
    sys.stderr.write("[score_tables] cells missing=%d invalid=%d  "
                     "warnings=%d errors=%d\n"
                     % (missing, invalid, DIAG.count("WARN"), DIAG.count("ERROR")))
    if args.strict and (missing or invalid or DIAG.count("ERROR") or exit_code):
        return 1
    return exit_code


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