qrcode-barcode-scanner 0.12.3

QR code decoding and scannability scoring for artistic, AI-generated, and photo-captured QR codes
Documentation
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
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
//! The score (spec/04-score.md) — survival ramps · caps · UEC · hints.
//!
//! Output language: VALIDATION, never ISO verification (no calibrated
//! optics). Geometry-class signals (perspective/rotation survival, finder
//! integrity, quiet zone) transfer to uncalibrated digital images;
//! reflectance-class signals (contrast/lighting survival) are relative.
//!
//! Determinism: every stress cell is a pure transform of the normalized
//! luma; ramps stop at the first failure (the knee). The lighting set is
//! unordered — no knee-exit, though depth still picks the cell subset.
//! Same input + same depth ⇒ same score, as far as the decode engines are
//! deterministic. Known exception until fixed upstream: rxing's PDF417
//! decoder breaks codeword-confidence ties in `HashMap` iteration order
//! (randomized per map), so a PDF417 cell near a decode threshold can pass
//! on one run and fail on the next (`pdf417_*_repeatability` diagnostics).
//!
//! Budget: a judgment runs its calibration and EVERY planned cell, or it is
//! absent. An unrun cell is not a failed one — read as a failure, a
//! deadline cut would ship a pristine symbol as a fragile verdict. Only the
//! deadline (or the test-only work quota) makes a judgment absent; a
//! cancelled token stays an error (`QRS-005`, the scan-wide contract). The
//! bound remembers every step it refused — an absent judgment, or a knee
//! bisection a complete one could not run — and the report says the budget
//! cut planned work (`trace.budget_exhausted`).

pub(crate) mod iso15415;
pub(crate) mod margin;
pub(crate) mod structural;
pub(crate) mod uec;
pub(crate) mod warp;

use web_time::Instant;

use crate::engine::{self, content::ContentKey};
use crate::error::Result;
use crate::input::LumaImage;
use crate::ladder::{CancelToken, MergedDetection, ScoreDepth};
use crate::report::{AxisScore, EcLevel, Grade, Hint, Score, StressAxis, Symbology};
use crate::transform;

/// A stress-cell builder: base image + ramp index → transformed cell.
type RampBuilder<'a> = &'a dyn Fn(&LumaImage, usize) -> LumaImage;
/// Builds the ONE bisection cell between the knee and its lower neighbour
/// (the unstressed base for a knee at index 0) + its wire label.
type RampRefiner<'a> = &'a dyn Fn(&LumaImage, usize) -> (LumaImage, String);

/// Stress cells run on a ≤512px base — bounded cost, consistent geometry.
const STRESS_BASE_SIDE: u32 = 512;
/// The longest side the stress base of a linear symbology may keep.
const LINEAR_BASE_SIDE_CAP: u32 = 2048;

/// The longest side of the stress base of a `width` × `height` frame.
///
/// A matrix or stacked symbology is judged on the square budget: longest
/// side ≤ 512 px. A linear symbology carries its data along one direction,
/// in a frame that is wide and short: its base keeps the PIXEL COUNT of
/// that square instead of its side, so the bars keep their width (at most
/// 2048 px on the longest side). A square frame gets 512 px either way.
fn stress_base_side(width: u32, height: u32, symbology: Symbology) -> u32 {
    if !symbology.is_linear() {
        return STRESS_BASE_SIDE;
    }
    let longest = u64::from(width.max(height));
    let shortest = u64::from(width.min(height).max(1));
    let budget = u64::from(STRESS_BASE_SIDE) * u64::from(STRESS_BASE_SIDE);
    // the longest side whose frame, at this aspect ratio, holds `budget` pixels
    let side = (budget * longest / shortest).isqrt();
    u32::try_from(side)
        .unwrap_or(LINEAR_BASE_SIDE_CAP)
        .clamp(STRESS_BASE_SIDE, LINEAR_BASE_SIDE_CAP)
}

/// A resolution cell of the square base, scaled to a base whose longest
/// side is `unit` (`unit` 512 returns `side`).
fn ramp_side(side: u32, unit: u32) -> u32 {
    u32::try_from(u64::from(side) * u64::from(unit) / u64::from(STRESS_BASE_SIDE)).unwrap_or(side)
}

#[cfg(test)]
thread_local! {
    /// Stress bases built on this thread — the witness that a judgment the
    /// deadline refuses at its first step costs nothing.
    static STRESS_BASES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
    /// Test-only: while set, a judgment panics in its own computation once
    /// its first step is admitted — a contained fault with no real panic
    /// source.
    pub(crate) static JUDGMENT_FAULT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Composite weights per axis (sum = 100). The contract constants of v3.
const WEIGHTS: [(StressAxis, u32); 6] = [
    (StressAxis::Resolution, 22),
    (StressAxis::Blur, 18),
    (StressAxis::Contrast, 15),
    (StressAxis::Perspective, 20),
    (StressAxis::Rotation, 10),
    (StressAxis::Lighting, 15),
];

/// Structural caps: a dead finder caps the composite at 40, a violated
/// quiet zone at 60 (the two documented AI-art killers).
const FINDER_INTEGRITY_FLOOR: f32 = 0.5;
const FINDER_DAMAGE_CAP: u8 = 40;
const QUIET_ZONE_CAP: u8 = 60;
/// UEC margin cap (the occlusion-cliff fix · door-admin probe 2026-08-05):
/// a consumed RS budget is invisible to the stress axes — the composite sat
/// flat while a growing center logo ate the margin, then decode died with
/// zero warning (at EC=H the raise-EC hint can never fire). Below the
/// half-budget line the margin caps the value CONTINUOUSLY: 0.5 → 100
/// (no-op seam) · 0.25 (ISO D) → 70 · 0.0 (ISO F, at the RS limit) → 40,
/// the finder-damage floor; at ISO's limit v1, v2-L, v3-L cap at 47-91 (spec/04).
const UEC_HEALTHY_MARGIN: f32 = 0.5;
const UEC_ZERO_MARGIN_CAP: u8 = 40;

/// The composite cap a measured RS margin allows — 100 (no-op) at or above
/// the healthy half-budget, then a continuous slope down to
/// [`UEC_ZERO_MARGIN_CAP`] at margin zero.
fn uec_margin_cap(margin: f32) -> u8 {
    if margin >= UEC_HEALTHY_MARGIN {
        return 100;
    }
    let span = f32::from(100 - UEC_ZERO_MARGIN_CAP);
    let cap = f32::from(UEC_ZERO_MARGIN_CAP) + (margin.max(0.0) / UEC_HEALTHY_MARGIN) * span;
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "cap in 40..=100"
    )]
    let cap = cap.round() as u8;
    cap
}

/// Whether a cell's reads carry the scored content: one read that would join
/// the primary detection — identical bytes, an agreeing FNC1 position, a
/// compatible ECI account ([`ContentKey::admits`], 07-pipeline property 7).
/// Neither text nor corners are compared; [`cell_decode`] filters the
/// symbology.
#[cfg(test)]
fn detections_match(found: &[engine::RawDetection], expected: &ContentKey) -> bool {
    found.iter().any(|d| expected.admits(d))
}

/// The whole single-symbology pass a probe step answers for: every reader
/// of the scored symbology, every read. The reference [`Bound::reads`] is
/// held to — a step asks only whether one of those reads carries the scored
/// content, and stops at the first that does.
#[cfg(test)]
fn cell_decode(img: &LumaImage, symbology: crate::report::Symbology) -> engine::EngineOutcome {
    engine::decode_filtered(img, engine::FormatFilter::Only(symbology))
}

/// One image a probe step may read: the cell as built, its Otsu
/// binarization, or the baseline's deep rung over it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Variant {
    Plain,
    Otsu,
    Rung,
}

/// One probe of a step: an image of the cell under one reader.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Pair {
    variant: Variant,
    reader: crate::report::EngineKind,
}

impl Pair {
    /// Its place in [`Schedule::trials`].
    fn slot(self) -> usize {
        let variant = match self.variant {
            Variant::Otsu => 0,
            Variant::Plain => 1,
            Variant::Rung => 2,
        };
        variant * 2 + usize::from(self.reader == crate::report::EngineKind::Rqrr)
    }
}

/// What a judgment remembers of a pair's last pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Trial {
    /// It read the expected content.
    read: bool,
    /// Its wall time as a power-of-two class ([`Schedule::class_of`]).
    cost: u8,
}

/// The order a probe step tries its pairs in: the cheapest expected first.
///
/// A step passes when ANY image of the cell reads under ANY reader of the
/// symbology, so the order decides only what a step costs, never whether it
/// passes. And the cost is far from even: on a degraded image of a design
/// whose modules look like finders (outlines, rings, dashes) one reader can
/// spend a hundred times a clean read on its finder candidates, to fail or
/// to read, while the same cell binarized reads at once — or the reverse,
/// depending on the design. No fixed order is cheap on every design, so the
/// judgment measures: each pass leaves its outcome and its wall time, and
/// the next step tries first the pair whose last pass was the cheapest, a
/// pass that failed counted [`Schedule::FAILED`] classes dearer and a pair
/// not yet tried one class above the cheapest read so far.
///
/// The clock orders work and nothing else: the verdict of a step, the score
/// and the report do not depend on it (`trace.engine_panics` counts the
/// panics of the passes that ran, as it always did). Costs are compared by
/// power-of-two class, so timer noise rarely reorders two pairs.
#[derive(Debug, Clone, Copy)]
struct Schedule {
    /// The reader tried first among pairs that are otherwise level: the one
    /// that read the detection.
    first: crate::report::EngineKind,
    /// The last pass of each pair ([`Pair::slot`]).
    trials: [Option<Trial>; 6],
    /// The cheapest read so far.
    floor: Option<u8>,
}

impl Schedule {
    /// Cost classes a failed pass counts above its own: a pair that failed
    /// is tried after one that read up to four times slower.
    const FAILED: u8 = 2;

    fn new() -> Self {
        Self {
            first: crate::report::EngineKind::Rxing,
            trials: [None; 6],
            floor: None,
        }
    }

    /// The class of a wall time: the bit length of its microseconds — one
    /// class per doubling, 0 for a time the clock cannot tell from none.
    fn class_of(elapsed: std::time::Duration) -> u8 {
        let bits = u128::BITS - elapsed.as_micros().leading_zeros();
        u8::try_from(bits).unwrap_or(u8::MAX)
    }

    /// The pairs of a step for `probe`, in the order to try them: by
    /// expected cost, then a pair that read before one never tried before
    /// one that failed, then the binarized image before the cell as built
    /// before the rung, and the first reader before the other.
    fn order(&self, probe: CellProbe) -> Vec<Pair> {
        let readers = engine::probe_readers(probe.symbology);
        let mut pairs = Vec::with_capacity(6);
        for variant in [Variant::Otsu, Variant::Plain, Variant::Rung] {
            if variant == Variant::Rung && probe.rung.is_none() {
                continue;
            }
            let ordered = std::iter::once(self.first)
                .filter(|reader| readers.contains(reader))
                .chain(readers.iter().copied().filter(|r| *r != self.first));
            for reader in ordered {
                pairs.push(Pair { variant, reader });
            }
        }
        // stable: level pairs keep the order built above
        pairs.sort_by_key(|pair| match self.trials[pair.slot()] {
            Some(Trial { read: true, cost }) => (cost, 0u8),
            None => (self.floor.map_or(0, |floor| floor.saturating_add(1)), 1),
            Some(Trial { read: false, cost }) => (cost.saturating_add(Self::FAILED), 2),
        });
        pairs
    }

    /// Remember a pass of `pair`.
    fn record(&mut self, pair: Pair, read: bool, elapsed: std::time::Duration) {
        let cost = Self::class_of(elapsed);
        self.trials[pair.slot()] = Some(Trial { read, cost });
        if read {
            self.floor = Some(self.floor.map_or(cost, |floor| floor.min(cost)));
        }
    }
}

/// The limits one judgment runs under — the shared scan deadline, the
/// cancel token and, in tests, a deterministic work quota — plus the work
/// units it spent and the decoder panics its decodes caught. One unit = one
/// probe step: a calibration decode class, one stress cell, one knee
/// bisection or one envelope probe. Each step is admitted BEFORE it runs (an
/// in-flight decode is not interruptible), so a quota cuts exactly where a
/// deadline can, but on the same step every run.
pub(crate) struct Bound<'a> {
    cancel: &'a CancelToken,
    deadline: Option<Instant>,
    quota: Option<u32>,
    spent: u32,
    /// A planned step was refused.
    cut: bool,
    /// Decoder panics the engine boundary caught in this bound's decodes —
    /// the report counts them in `trace.engine_panics`.
    panics: u8,
    /// The order its probe steps try their pairs in ([`Schedule`]).
    schedule: Schedule,
}

impl<'a> Bound<'a> {
    /// The scan's own limits: its cancel token and shared deadline.
    pub(crate) fn new(cancel: &'a CancelToken, deadline: Option<Instant>) -> Self {
        Self {
            cancel,
            deadline,
            quota: None,
            spent: 0,
            cut: false,
            panics: 0,
            schedule: Schedule::new(),
        }
    }

    /// Start the probes with the reader that read the detection: rqrr when
    /// it did, rxing otherwise. The order never changes a step's outcome
    /// ([`Schedule`]).
    fn lead_with(&mut self, engines: &[crate::report::EngineKind]) {
        if engines.contains(&crate::report::EngineKind::Rqrr) {
            self.schedule.first = crate::report::EngineKind::Rqrr;
        }
    }

    /// The same limits capped at `units` probe steps.
    #[cfg(test)]
    fn with_quota(self, units: u32) -> Self {
        Self {
            quota: Some(units),
            ..self
        }
    }

    /// Probe steps admitted so far.
    #[cfg(test)]
    fn spent(&self) -> u32 {
        self.spent
    }

    /// Admit one probe step — `Ok(false)` once the deadline passed or the
    /// quota is spent: the step must not run, and the bound remembers the
    /// cut. A cancelled token is `Err(Cancelled)` instead — cancellation is
    /// the caller's `QRS-005`, never an absent judgment.
    pub(crate) fn admit(&mut self) -> Result<bool> {
        if self.cancel.is_cancelled() {
            return Err(crate::error::ScanError::Cancelled);
        }
        if self.deadline.is_some_and(|d| Instant::now() >= d)
            || self.quota.is_some_and(|units| self.spent >= units)
        {
            self.cut = true;
            return Ok(false);
        }
        self.spent += 1;
        Ok(true)
    }

    /// Whether a planned step was refused — the judgment is then absent, or
    /// a knee bisection of a complete one is missing.
    pub(crate) fn cut(&self) -> bool {
        self.cut
    }

    /// The decoder panics this bound's decodes caught.
    pub(crate) fn panics(&self) -> u8 {
        self.panics
    }

    /// One pass of a probe step: whether `pair`'s reader reads `expected` in
    /// `img`, the image of `pair`'s variant ([`engine::probe`], restricted
    /// to `symbology`). The pass is remembered ([`Schedule::record`]) and
    /// the decoder panics it caught are added to the tally. How the step is
    /// judged does not change — a panicking decoder read nothing.
    fn reads(
        &mut self,
        img: &LumaImage,
        symbology: crate::report::Symbology,
        pair: Pair,
        expected: &ContentKey,
    ) -> bool {
        let started = Instant::now();
        let probe = engine::probe(img, symbology, pair.reader, &|read| expected.admits(read));
        self.schedule
            .record(pair, probe.accepted, started.elapsed());
        self.panics = self.panics.saturating_add(probe.panics);
        probe.accepted
    }
}

/// Whether a judgment at `depth` that skips `skip` plans any stress cell:
/// `false` for depth `Off` or with every axis skipped. The one rule behind
/// [`crate::ScanConfig::computes_score`] and [`Judgment::NoAxes`].
pub(crate) fn plans_cells(depth: ScoreDepth, skip: &[StressAxis]) -> bool {
    !depth_indices(depth).is_empty() && !WEIGHTS.iter().all(|(axis, _)| skip.contains(axis))
}

/// What one bounded judgment produced.
#[derive(Debug)]
pub(crate) enum Judgment {
    /// Calibration and every planned cell ran.
    Complete(Score, Vec<Hint>),
    /// No cell is planned (every axis skipped, or depth `Off`) — an
    /// axis-less composite would be fiction.
    NoAxes,
    /// The deadline or the work quota cut a planned step: no verdict, never
    /// a partial composite whose unrun cells read as failures.
    Interrupted,
}

/// How a bounded calibration walk ended.
pub(crate) enum Calibrated {
    /// The cheapest decode class that reads the base.
    Class(CellProbe),
    /// No class reads the base at stress scale (the score then
    /// legitimately reads zero margin).
    Undecodable,
    /// The deadline or the quota cut the walk first.
    Interrupted,
}

/// The decode class a symbol's UNSTRESSED baseline needs — stress cells
/// probe the same class. An artistic symbol that only decodes through a
/// boost rung would otherwise read margin-zero on every cell (direct+otsu
/// fail even unstressed), conflating "fragile" with "undecodable".
#[derive(Clone, Copy)]
pub(crate) struct CellProbe {
    /// The deep rung the baseline needed, if any.
    pub(crate) rung: Option<crate::ladder::Rung>,
    /// The symbology being scored — every cell decode filters on it.
    pub(crate) symbology: crate::report::Symbology,
}

impl CellProbe {
    /// Calibrate on the unstressed base: direct → otsu → first decoding
    /// deep rung that reads `expected`, the primary's content. `None` = the
    /// base does not decode at stress scale at all (score legitimately reads
    /// zero margin).
    #[cfg(test)]
    pub(crate) fn calibrate(
        base: &LumaImage,
        expected: &ContentKey,
        symbology: crate::report::Symbology,
    ) -> Option<Self> {
        // a fresh token, no deadline, no quota: this walk is never cut
        let never = CancelToken::new();
        let mut unbounded = Bound::new(&never, None);
        match Self::calibrate_within(base, expected, symbology, &mut unbounded) {
            Ok(Calibrated::Class(probe)) => Some(probe),
            Ok(Calibrated::Undecodable | Calibrated::Interrupted) | Err(_) => None,
        }
    }

    /// The calibration walk under a judgment's bound. The shallow class
    /// (direct + otsu — what every cell tries first) is one step, each deep
    /// rung one more: up to 16 steps, never one past the deadline.
    #[cfg(test)]
    fn calibrate_within(
        base: &LumaImage,
        expected: &ContentKey,
        symbology: crate::report::Symbology,
        bound: &mut Bound<'_>,
    ) -> Result<Calibrated> {
        if !bound.admit()? {
            return Ok(Calibrated::Interrupted);
        }
        Self::calibrate_admitted(base, expected, symbology, bound)
    }

    /// The calibration walk once `bound` admitted its first step, the
    /// shallow class: its caller admits that step before building `base`,
    /// so a walk the deadline already prevents costs no pixel work.
    pub(crate) fn calibrate_admitted(
        base: &LumaImage,
        expected: &ContentKey,
        symbology: crate::report::Symbology,
        bound: &mut Bound<'_>,
    ) -> Result<Calibrated> {
        let shallow = Self {
            rung: None,
            symbology,
        };
        if cell_passes(base, expected, shallow, bound) {
            return Ok(Calibrated::Class(shallow));
        }
        for rung in crate::ladder::DEEP_RUNGS {
            if !bound.admit()? {
                return Ok(Calibrated::Interrupted);
            }
            let boosted = rung.apply(base);
            let class = Self {
                rung: Some(rung),
                symbology,
            };
            // neither the base nor its binarization read: only the rung's
            // own pairs can
            let pairs = bound.schedule.order(class);
            for pair in pairs
                .into_iter()
                .filter(|pair| pair.variant == Variant::Rung)
            {
                if bound.reads(&boosted, symbology, pair, expected) {
                    return Ok(Calibrated::Class(class));
                }
            }
        }
        Ok(Calibrated::Undecodable)
    }
}

/// One stress cell: did the (transformed) image still decode to the same
/// SYMBOL? Identity is the content, never its text (07-pipeline property
/// 7): a cell's read counts when it would join the primary detection — the
/// same bytes, an agreeing FNC1 position, a compatible ECI account. A lone
/// cell read cannot see what decided the primary's text — the segments or
/// declarations a parse of the symbol observed — so a text match failed
/// symbols that survived: unmarked Kanji or Hanzi, declared bytes.
///
/// Probe = direct + otsu + the baseline's deep rung when it needed one —
/// the margin is measured RELATIVE to the symbol's own decode class, never
/// with the full ladder's recovery power (that asymmetry is the point).
/// The cell passes when any of those images reads under any reader of the
/// symbology: the pairs are tried cheapest expected first ([`Schedule`])
/// and the first read ends the step. The decodes run through `bound`, which
/// tallies the decoder panics they caught.
pub(crate) fn cell_passes(
    img: &LumaImage,
    expected: &ContentKey,
    probe: CellProbe,
    bound: &mut Bound<'_>,
) -> bool {
    // each image is built once, and only when a pair reaches it
    let mut otsu: Option<LumaImage> = None;
    let mut boosted: Option<LumaImage> = None;
    for pair in bound.schedule.order(probe) {
        let image = match (pair.variant, probe.rung) {
            (Variant::Plain, _) => img,
            (Variant::Otsu, _) => otsu.get_or_insert_with(|| transform::otsu_threshold(img)),
            (Variant::Rung, Some(rung)) => boosted.get_or_insert_with(|| rung.apply(img)),
            (Variant::Rung, None) => continue,
        };
        if bound.reads(image, probe.symbology, pair, expected) {
            return true;
        }
    }
    false
}

/// Ramp cell indices at a given depth (Reduced takes the 2nd and 4th
/// intensities of each five-step ramp).
fn depth_indices(depth: ScoreDepth) -> &'static [usize] {
    match depth {
        ScoreDepth::Off => &[],
        ScoreDepth::Reduced => &[1, 3],
        ScoreDepth::Full => &[0, 1, 2, 3, 4],
    }
}

/// Lighting cell picks at a given depth — the set's own subset (Reduced
/// keeps hard shadow + glare).
fn lighting_indices(depth: ScoreDepth) -> &'static [usize] {
    match depth {
        ScoreDepth::Off => &[],
        ScoreDepth::Reduced => &[1, 2],
        ScoreDepth::Full => &[0, 1, 2, 3, 4],
    }
}

/// Run one ordered ramp with early-stop at the first failure (the knee):
/// `(passed, knee)`. Stopping at a knee COMPLETES the ramp — intensities
/// are ordered, later cells only get harder. `Ok(None)` = the deadline or
/// the quota cut a planned cell before the ramp could say where it breaks.
fn run_ramp(
    base: &LumaImage,
    expected: &ContentKey,
    bound: &mut Bound<'_>,
    probe: CellProbe,
    indices: &[usize],
    build: impl Fn(&LumaImage, usize) -> LumaImage,
) -> Result<Option<(u8, Option<usize>)>> {
    let mut passed = 0u8;
    for &i in indices {
        if !bound.admit()? {
            return Ok(None);
        }
        let cell = build(base, i);
        if !cell_passes(&cell, expected, probe, bound) {
            return Ok(Some((passed, Some(i))));
        }
        passed += 1;
    }
    Ok(Some((passed, None)))
}

/// Wire label of one stress cell — what `AxisScore.failed_at` carries. Human-
/// readable, stable (the panel prints it verbatim): the intensity that killed
/// the ramp, or the lighting defect that failed. Indexes the FULL ramp. The
/// resolution labels are the square base's: a wider base (`stress_base_side`)
/// labels the sides its cells ran at (`run_axes`).
fn cell_label(axis: StressAxis, i: usize) -> &'static str {
    match axis {
        StressAxis::Resolution => ["358px", "256px", "179px", "128px", "90px"][i.min(4)],
        StressAxis::Blur => ["blur 0.5", "blur 1.0", "blur 1.5", "blur 2.0", "blur 2.5"][i.min(4)],
        StressAxis::Contrast => [
            "contrast 70%",
            "contrast 55%",
            "contrast 40%",
            "contrast 30%",
            "contrast 20%",
        ][i.min(4)],
        StressAxis::Perspective => ["10°", "18°", "26°", "34°", "42°"][i.min(4)],
        StressAxis::Rotation => ["10°", "20°", "30°", "40°", "50°"][i.min(4)],
        StressAxis::Lighting => [
            "soft shadow",
            "hard shadow",
            "glare",
            "overexposure",
            "underexposure",
        ][i.min(4)],
    }
}

/// Wire label of a ramp's knee: the side the cell ran at on the resolution
/// axis, the fixed label of the cell on the others.
fn knee_label(axis: StressAxis, i: usize, resolution_sides: &[u32; 5]) -> String {
    match axis {
        StressAxis::Resolution => format!("{}px", resolution_sides[i.min(4)]),
        _ => cell_label(axis, i).to_owned(),
    }
}

/// One bisection probe tightens a knee (Full depth only): the report gains
/// the tightest TESTED failing intensity, the composite reads nothing from
/// it. Deadline or quota cut / no knee / Reduced depth → honestly absent.
fn refine_knee(
    base: &LumaImage,
    expected: &ContentKey,
    probe: CellProbe,
    knee: (usize, &str),
    bound: &mut Bound<'_>,
    refine: RampRefiner<'_>,
) -> Result<Option<String>> {
    if !bound.admit()? {
        return Ok(None);
    }
    let (knee, knee_label) = knee;
    let (cell, label) = refine(base, knee);
    Ok(Some(if cell_passes(&cell, expected, probe, bound) {
        knee_label.to_owned()
    } else {
        label
    }))
}

/// The lighting defect SET (unordered — no knee, no refinement): shadows,
/// centred glare, exposure extremes. Split from `run_axes` for line-budget
/// and because its pass-set semantics differ from the ordered ramps: the
/// set is complete only once EVERY pick ran — `Ok(None)` when the deadline
/// or the quota cut one.
fn run_lighting(
    base: &LumaImage,
    expected: &ContentKey,
    depth: ScoreDepth,
    bound: &mut Bound<'_>,
    probe: CellProbe,
) -> Result<Option<AxisScore>> {
    #[allow(
        clippy::cast_precision_loss,
        reason = "image dimensions bounded by Limits::max_dimension (lint presence varies by build shape)"
    )]
    // Glare lands on the DATA region (the symbol centre), never a finder:
    // at the old (0.3w, 0.3h) placement the saturated spot erased the
    // top-left finder — a structural kill NO design survives (a pristine
    // black-on-white symbol capped at 4/5 lighting forever, the 95-ceiling
    // class). Centred, the error-correction budget decides: weak ECC dies,
    // healthy ECC recovers — measurable, actionable (raise ECC), honest.
    let (cx, cy, radius) = (
        base.width() as f32 * 0.5,
        base.height() as f32 * 0.5,
        base.width().min(base.height()) as f32 * 0.18,
    );
    let lighting_cells: [&dyn Fn(&LumaImage) -> LumaImage; 5] = [
        &|b| warp::shadow_gradient(b, 0.4),
        &|b| warp::shadow_gradient(b, 0.7),
        &|b| warp::glare_blob(b, cx, cy, radius),
        &|b| warp::exposure(b, 60),
        &|b| warp::exposure(b, -60),
    ];
    let lighting_picks = lighting_indices(depth);
    let mut lighting_passed = 0u8;
    let mut first_failed = None;
    for &i in lighting_picks {
        if !bound.admit()? {
            return Ok(None);
        }
        if cell_passes(&lighting_cells[i](base), expected, probe, bound) {
            lighting_passed += 1;
        } else if first_failed.is_none() {
            first_failed = Some(i);
        }
    }
    Ok(Some(AxisScore {
        axis: StressAxis::Lighting,
        passed: lighting_passed,
        total: u8::try_from(lighting_picks.len()).unwrap_or(u8::MAX),
        failed_at: first_failed.map(|i| cell_label(StressAxis::Lighting, i).to_owned()),
        // an unordered defect SET has no knee to bisect
        refined_failed_at: None,
    }))
}

/// Run the five ordered ramps + the lighting set at the given depth, then
/// bisect their knees. Axes in `skip` never run — their cells are never
/// built (the integration perf win) and they are absent from the returned
/// list (the report self-describes what was measured). `Ok(None)` = the
/// deadline or the quota cut a planned cell: no axis list, never a partial
/// one.
fn run_axes(
    base: &LumaImage,
    expected: &ContentKey,
    depth: ScoreDepth,
    skip: &[StressAxis],
    bound: &mut Bound<'_>,
    probe: CellProbe,
) -> Result<Option<Vec<AxisScore>>> {
    // ---- ordered ramps (intensity grows with the index) ----
    // A base wider than the square side (a linear symbology's,
    // `stress_base_side`) scales the resolution ramp with it: each cell is
    // the same share of the base, and its label names the side it ran at.
    let unit = base.width().max(base.height()).max(STRESS_BASE_SIDE);
    let resolution_sides: [u32; 5] = [358, 256, 179, 128, 90].map(|side| ramp_side(side, unit));
    let blur_sigmas: [f32; 5] = [0.5, 1.0, 1.5, 2.0, 2.5];
    let contrast_factors: [f32; 5] = [0.7, 0.55, 0.4, 0.3, 0.2];
    let tilt_degrees: [f32; 5] = [10.0, 18.0, 26.0, 34.0, 42.0];
    let rotation_degrees: [f32; 5] = [10.0, 20.0, 30.0, 40.0, 50.0];

    let indices = depth_indices(depth);
    let mut axes = Vec::with_capacity(6);
    // midpoint of the knee cell and its lower neighbour (index 0 bisects
    // against the UNSTRESSED value: the base side · sigma 0 · factor 1 · 0°)
    let mid = |arr: &[f32; 5], i: usize, unstressed: f32| -> f32 {
        f32::midpoint(if i == 0 { unstressed } else { arr[i - 1] }, arr[i])
    };
    let ramps: [(StressAxis, RampBuilder<'_>, RampRefiner<'_>); 5] = [
        (
            StressAxis::Resolution,
            &|b, i| transform::downscale_to(b, resolution_sides[i]),
            &|b, i| {
                let side = u32::midpoint(
                    if i == 0 {
                        unit
                    } else {
                        resolution_sides[i - 1]
                    },
                    resolution_sides[i],
                );
                (transform::downscale_to(b, side), format!("{side}px"))
            },
        ),
        (
            StressAxis::Blur,
            &|b, i| transform::gaussian_blur(b, blur_sigmas[i]),
            &|b, i| {
                let sigma = mid(&blur_sigmas, i, 0.0);
                (transform::gaussian_blur(b, sigma), format!("blur {sigma}"))
            },
        ),
        (
            StressAxis::Contrast,
            &|b, i| transform::contrast_boost(b, contrast_factors[i], 1.0),
            &|b, i| {
                let factor = mid(&contrast_factors, i, 1.0);
                (
                    transform::contrast_boost(b, factor, 1.0),
                    format!("contrast {:.0}%", factor * 100.0),
                )
            },
        ),
        (
            StressAxis::Perspective,
            &|b, i| warp::perspective_tilt(b, tilt_degrees[i]),
            &|b, i| {
                let deg = mid(&tilt_degrees, i, 0.0);
                (warp::perspective_tilt(b, deg), format!("{deg}\u{b0}"))
            },
        ),
        (
            StressAxis::Rotation,
            &|b, i| warp::rotate(b, rotation_degrees[i]),
            &|b, i| {
                let deg = mid(&rotation_degrees, i, 0.0);
                (warp::rotate(b, deg), format!("{deg}\u{b0}"))
            },
        ),
    ];
    let mut knees = Vec::new();
    for (axis, build, refine) in ramps {
        if skip.contains(&axis) {
            continue; // never built, never run — absent from the report
        }
        let Some((passed, knee)) = run_ramp(base, expected, bound, probe, indices, build)? else {
            return Ok(None);
        };
        if let Some(i) = knee {
            knees.push((axes.len(), i, refine));
        }
        axes.push(AxisScore {
            axis,
            passed,
            total: u8::try_from(indices.len()).unwrap_or(u8::MAX),
            failed_at: knee.map(|i| knee_label(axis, i, &resolution_sides)),
            refined_failed_at: None,
        });
    }

    if !skip.contains(&StressAxis::Lighting) {
        let Some(lighting) = run_lighting(base, expected, depth, bound, probe)? else {
            return Ok(None);
        };
        axes.push(lighting);
    }

    // Bisection runs LAST: informational, it may only spend what the
    // composite's cells left — a cut drops a label, never the judgment.
    if matches!(depth, ScoreDepth::Full) {
        for (slot, knee, refine) in knees {
            if let Some(entry) = axes.get_mut(slot) {
                let label = entry.failed_at.clone().unwrap_or_default();
                entry.refined_failed_at =
                    refine_knee(base, expected, probe, (knee, &label), bound, refine)?;
            }
        }
    }
    Ok(Some(axes))
}

/// Weighted composite + structural caps + the margin cap + the hint list.
///
/// `uec` is the MEASURED margin: it caps the value whether or not its
/// section ships, so skipping the check can never move `value`.
/// `publish_uec` gates only what the wire shows — `score.uec` and the two
/// hints it drives.
fn compose(
    axes: Vec<AxisScore>,
    structural: Option<crate::report::StructuralReport>,
    uec: Option<crate::report::UecReport>,
    publish_uec: bool,
    iso15415: Option<crate::report::Iso15415Report>,
    detection: &MergedDetection,
) -> (Score, Vec<Hint>) {
    // Renormalize over the axes that RAN: with the full six this divides by
    // 100 (Σ contract weights — byte-identical to the fixed divisor it
    // replaces); with skipped axes the remaining weights re-span 0-100.
    // run_axes never returns an empty list (judge() short-circuits the
    // all-skipped config before composing), so the divisor is never 0.
    let mut weighted = 0u32;
    let mut weight_run = 0u32;
    for score in &axes {
        let weight = WEIGHTS
            .iter()
            .find(|(axis, _)| *axis == score.axis)
            .map_or(0, |(_, w)| *w);
        weight_run += weight;
        if score.total > 0 {
            weighted += weight * u32::from(score.passed) * 100 / u32::from(score.total);
        }
    }
    let mut value = u8::try_from((weighted / weight_run.max(1)).min(100)).unwrap_or(100);

    let mut hints = Vec::new();
    if let Some(s) = &structural {
        let weakest = s
            .finder_integrity
            .iter()
            .enumerate()
            .min_by(|a, b| a.1.total_cmp(b.1))
            .map(|(i, v)| (i, *v));
        if let Some((corner, integrity)) = weakest
            && integrity < FINDER_INTEGRITY_FLOOR
        {
            value = value.min(FINDER_DAMAGE_CAP);
            #[expect(clippy::cast_possible_truncation, reason = "corner in 0..3")]
            hints.push(Hint::FixFinderPattern {
                corner: corner as u8,
            });
        }
        if !s.quiet_zone_ok {
            value = value.min(QUIET_ZONE_CAP);
            hints.push(Hint::RestoreQuietZone);
        }
    }
    // The raise-EC `value < 70` gate reads the composite BEFORE the margin
    // cap: a cap-driven drop is the margin's own verdict, and margin-driven
    // hints speak only through the published section (published, the
    // thin-margin path covers every cap below 70 — such a margin is grade F).
    let pre_margin_cap = value;
    // A melting RS margin caps the composite on a continuous slope (see the
    // UEC_HEALTHY_MARGIN doc) — the report's `uec` field carries the why.
    if let Some(u) = &uec {
        value = value.min(uec_margin_cap(u.margin));
    }
    let uec = uec.filter(|_| publish_uec);

    // ---- axis-derived hints (stable order) ----
    let fraction = |axis: StressAxis| -> Option<(u8, u8)> {
        axes.iter()
            .find(|a| a.axis == axis)
            .map(|a| (a.passed, a.total))
    };
    if let Some((p, t)) = fraction(StressAxis::Contrast)
        && t > 0
        && u32::from(p) * 100 / u32::from(t) <= 40
    {
        hints.push(Hint::IncreaseContrast);
    }
    if let Some((p, t)) = fraction(StressAxis::Resolution)
        && t > 0
        && u32::from(p) * 100 / u32::from(t) <= 40
    {
        hints.push(Hint::EnlargeModules);
    }
    if let Some((p, t)) = fraction(StressAxis::Blur)
        && t > 0
        && p == 0
    {
        // dies at the mildest blur — art texture is eating the margin
        hints.push(Hint::ReduceArtTexture);
    }
    // UEC drives the EC hint with priority: a thin real margin is the
    // strongest possible "raise EC" signal even when stress survival is OK.
    let thin_margin = uec.is_some_and(|u| {
        matches!(
            u.grade,
            crate::report::UecGrade::D | crate::report::UecGrade::F
        )
    });
    if let Some(current) = detection.ec
        && current < EcLevel::H
        && (pre_margin_cap < 70 || thin_margin)
    {
        hints.push(Hint::RaiseErrorCorrection { current });
    }
    // Margin ZERO is qualitatively different from thin: the worst block
    // consumed its entire correction budget, which is exactly the signature
    // of a Reed-Solomon miscorrection (caught live on the zxing blackbox
    // corpus: rqrr returned "photography" for a "photograph" ground truth
    // at 12/24 errors — this hint is the machine-readable distrust signal).
    // It reads only the PUBLISHED section by design: its errors/capacity ARE
    // the section's numbers, so a host that skips `uec` gets neither — the
    // margin still capped the value (at most 40 at margin zero).
    if let Some(u) = &uec
        && u.margin <= 0.0
    {
        hints.push(Hint::LowCorrectionMargin {
            errors: u.worst_block_errors,
            capacity: u.worst_block_capacity,
        });
    }

    let score = Score {
        value,
        grade: Grade::from_value(value),
        // the honesty integer: how much contract stands behind `value`
        weights_run: u8::try_from(weight_run.min(100)).unwrap_or(100),
        axes,
        structural,
        uec,
        iso15415,
    };
    (score, hints)
}

/// Evaluate the score for the primary detection under `bound` (the scan's
/// shared deadline), its cells matching `key`, the detection's content. No
/// judgment when no cell is planned (every axis skipped — an axis-less
/// composite would be fiction; callers treat it exactly like
/// `ScoreDepth::Off`) and when the deadline cuts it: absent, never partial.
/// `bound` then says whether the deadline prevented a planned step — the
/// judgment's (then absent) or a knee bisection's (the score stands, its
/// label is missing) — and how many decoder panics the cells caught. A
/// cancelled token is `Err(Cancelled)` (`QRS-005`).
pub(crate) fn evaluate(
    luma: &LumaImage,
    detection: &MergedDetection,
    key: &ContentKey,
    depth: ScoreDepth,
    skip: &[StressAxis],
    skip_checks: &[crate::ladder::ScoreCheck],
    bound: &mut Bound<'_>,
) -> Result<Option<(Score, Vec<Hint>)>> {
    Ok(
        match judge(luma, detection, key, depth, skip, skip_checks, bound)? {
            Judgment::Complete(score, hints) => Some((score, hints)),
            Judgment::NoAxes | Judgment::Interrupted => None,
        },
    )
}

/// Judge the primary detection under `bound`: calibration, every planned
/// cell, then the knee bisections — every cell matching `key`, the
/// detection's content. Structural, UEC and ISO run only once every planned
/// cell has run — a judgment the deadline or the quota cuts is
/// `Interrupted`, while a cancelled token is `Err(Cancelled)` (`QRS-005`).
pub(crate) fn judge(
    luma: &LumaImage,
    detection: &MergedDetection,
    key: &ContentKey,
    depth: ScoreDepth,
    skip: &[StressAxis],
    skip_checks: &[crate::ladder::ScoreCheck],
    bound: &mut Bound<'_>,
) -> Result<Judgment> {
    if !plans_cells(depth, skip) {
        return Ok(Judgment::NoAxes);
    }
    // the calibration's first step is admitted before the stress base is
    // built: a judgment the deadline already prevents costs nothing
    if !bound.admit()? {
        return Ok(Judgment::Interrupted);
    }
    #[cfg(test)]
    STRESS_BASES.with(|built| built.set(built.get() + 1));
    #[cfg(test)]
    assert!(
        !JUDGMENT_FAULT.with(std::cell::Cell::get),
        "injected judgment fault"
    );
    let base = transform::downscale_to(
        luma,
        stress_base_side(luma.width(), luma.height(), detection.symbology),
    );
    bound.lead_with(&detection.engines);
    // calibrate the cell probe on the unstressed base (its decode class)
    let probe = match CellProbe::calibrate_admitted(&base, key, detection.symbology, bound)? {
        Calibrated::Class(probe) => probe,
        // no class reads the unstressed base: the shallow probe measures
        // it anyway — a legitimately (near-)zero margin, fully judged
        Calibrated::Undecodable => CellProbe {
            rung: None,
            symbology: detection.symbology,
        },
        Calibrated::Interrupted => return Ok(Judgment::Interrupted),
    };
    let Some(axes) = run_axes(&base, key, depth, skip, bound, probe)? else {
        return Ok(Judgment::Interrupted);
    };
    // Photometric checks sample the ORIGINAL luma — when the geometry came
    // from an INVERTING attempt (light-on-dark symbol), hand them an
    // inverted view or every module's polarity reads flipped (a clean
    // symbol would score finder integrity ≈ 0.33 + earn bogus caps/hints).
    let photometric_view = detection
        .photometric_inverted
        .then(|| transform::invert(luma));
    let sample_luma = photometric_view.as_ref().unwrap_or(luma);
    let structural = match (detection.corners, detection.version) {
        (Some(corners), Some(version)) => structural::check(sample_luma, corners, version),
        _ => None,
    };
    // The UEC replay runs whenever the bitstream exists: its margin caps the
    // composite, and skipping a check never moves a published verdict. A
    // skipped `uec` withholds only what it shows — `score.uec`, the two hints
    // it drives (compose) and the ISO block's unused_error_correction
    // parameter, whose grade still counts in the ISO `overall` (the minimum
    // over every MEASURED parameter). A skipped ISO block never runs. The
    // stream is the verified orientation's, and it measures a margin only
    // when it error-corrects errors-only under the detection's format — a
    // stream the S5 rescue recovered with erasures keeps its own count.
    let publish_uec = !skip_checks.contains(&crate::ladder::ScoreCheck::Uec);
    let skip_iso = skip_checks.contains(&crate::ladder::ScoreCheck::Iso15415);
    let source = if detection
        .engines
        .contains(&crate::report::EngineKind::Rescue)
    {
        uec::Stream::Rescued
    } else {
        uec::Stream::Decoded
    };
    let uec_report = match (
        &detection.masked_stream,
        detection.version,
        detection.ec,
        detection.mask,
    ) {
        (Some(stream), Some(version), Some(ec), Some(mask)) => {
            uec::compute(&stream.bits, stream.bit_len, version, ec, mask, source)
        }
        _ => None,
    };
    let iso = if skip_iso {
        None
    } else {
        match (detection.corners, detection.version, &structural) {
            (Some(corners), Some(version), Some(s)) => {
                iso15415::compute(sample_luma, corners, version, s, uec_report.as_ref()).map(
                    |mut card| {
                        if !publish_uec {
                            card.unused_error_correction = None;
                        }
                        card
                    },
                )
            }
            _ => None,
        }
    };
    let (score, hints) = compose(axes, structural, uec_report, publish_uec, iso, detection);
    Ok(Judgment::Complete(score, hints))
}

#[cfg(test)]
mod tests {

    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;
    use crate::input::{ImageInput, Limits};
    use crate::ladder::{self, ScanConfig};
    use crate::transform::normalize;

    /// A linear symbology's base holds the pixel count of the 512 px square
    /// at the frame's aspect ratio; every other symbology keeps the side.
    #[test]
    fn a_linear_base_keeps_the_pixel_count_of_the_square_base() {
        // a square frame, and every symbology that is not linear: the side
        assert_eq!(stress_base_side(2000, 2000, Symbology::Code128), 512);
        for other in Symbology::ALL.into_iter().filter(|s| !s.is_linear()) {
            assert_eq!(stress_base_side(1600, 400, other), 512, "{other:?}");
        }
        // four to one: twice the side, half the height, the same pixel count
        assert_eq!(stress_base_side(4000, 1000, Symbology::Ean13), 1024);
        assert_eq!(stress_base_side(1000, 4000, Symbology::Ean13), 1024);
        // a frame already under the budget is kept: its bars are not resampled
        assert!(stress_base_side(1032, 240, Symbology::Code128) >= 1032);
        assert!(stress_base_side(516, 121, Symbology::Code128) >= 516);
        // bounded on the side, and never above the budget in pixels
        assert_eq!(stress_base_side(60_000, 30, Symbology::Code128), 2048);
        assert_eq!(stress_base_side(u32::MAX, 1, Symbology::Itf), 2048);
        assert_eq!(stress_base_side(0, 0, Symbology::Itf), 512);
        for (width, height) in [(1037, 205), (892, 233), (604, 385), (3000, 700), (640, 480)] {
            for linear in Symbology::ALL.into_iter().filter(|s| s.is_linear()) {
                let side = u64::from(stress_base_side(width, height, linear));
                let short = side * u64::from(height) / u64::from(width);
                assert!(
                    side * short <= 512 * 512,
                    "{width}x{height} {linear:?}: {side}"
                );
                assert!(side >= 512, "{width}x{height} {linear:?}: {side}");
            }
        }
        assert_eq!(
            Symbology::ALL.into_iter().filter(|s| s.is_linear()).count(),
            12,
            "seven of the nineteen symbologies are matrix or stacked"
        );
    }

    /// The resolution cells are shares of the base: the square base's own
    /// sides at 512, the same shares of a wider one.
    #[test]
    fn the_resolution_ramp_keeps_its_shares_on_a_wider_base() {
        let cells = [358, 256, 179, 128, 90];
        assert_eq!(cells.map(|side| ramp_side(side, 512)), cells);
        assert_eq!(
            cells.map(|side| ramp_side(side, 1024)),
            [716, 512, 358, 256, 180]
        );
        assert_eq!(
            cells.map(|side| ramp_side(side, 1037)),
            [725, 518, 362, 259, 182]
        );
    }

    fn detection_with(ec: Option<EcLevel>) -> MergedDetection {
        MergedDetection {
            symbology: crate::report::Symbology::QrCode,
            raw: b"x".to_vec(),
            text: "x".into(),
            charset: crate::report::Charset::Utf8,
            masked_stream: None,
            corners: None,
            version: Some(2),
            ec,
            mask: Some(0),
            fnc1: false,
            photometric_inverted: false,
            engines: vec![crate::report::EngineKind::Rqrr],
            occurrences: vec![crate::engine::occurrence::Footprint::unavailable()],
        }
    }

    /// `compose` under the default checks — the UEC section published.
    fn compose_published(
        axes: Vec<AxisScore>,
        structural: Option<crate::report::StructuralReport>,
        uec: Option<crate::report::UecReport>,
        iso15415: Option<crate::report::Iso15415Report>,
        detection: &MergedDetection,
    ) -> (Score, Vec<Hint>) {
        compose(axes, structural, uec, true, iso15415, detection)
    }

    fn axes_with(overrides: &[(StressAxis, u8, u8)]) -> Vec<AxisScore> {
        let mut axes: Vec<AxisScore> = WEIGHTS
            .iter()
            .map(|&(axis, _)| AxisScore {
                axis,
                passed: 5,
                total: 5,
                failed_at: None,
                refined_failed_at: None,
            })
            .collect();
        for &(axis, passed, total) in overrides {
            let slot = axes.iter_mut().find(|a| a.axis == axis).unwrap();
            slot.passed = passed;
            slot.total = total;
        }
        axes
    }

    /// The composite is a PUBLISHED contract — pin its arithmetic exactly
    /// (mutation testing showed the weighted math was never value-pinned).
    #[test]
    fn composite_weights_are_exact() {
        let d = detection_with(Some(EcLevel::H));
        let (score, _) = compose_published(axes_with(&[]), None, None, None, &d);
        assert_eq!(score.value, 100);

        // resolution 4/5: (22·80 + 78·100)/100 = 95
        let (score, _) = compose_published(
            axes_with(&[(StressAxis::Resolution, 4, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert_eq!(score.value, 95);

        // blur 0/5: (18·0 + 82·100)/100 = 82
        let (score, hints) =
            compose_published(axes_with(&[(StressAxis::Blur, 0, 5)]), None, None, None, &d);
        assert_eq!(score.value, 82);
        assert!(hints.contains(&Hint::ReduceArtTexture), "{hints:?}");

        // rotation 2/5: (10·40 + 90·100)/100 = 94
        let (score, _) = compose_published(
            axes_with(&[(StressAxis::Rotation, 2, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert_eq!(score.value, 94);
    }

    #[test]
    fn structural_caps_are_exact_with_boundaries() {
        use crate::report::StructuralReport;
        let d = detection_with(Some(EcLevel::H));

        // worst finder 0.49 < 0.5 floor → capped at 40 + the corner named
        let (score, hints) = compose_published(
            axes_with(&[]),
            Some(StructuralReport {
                finder_integrity: [1.0, 1.0, 0.49],
                quiet_zone_ok: true,
            }),
            None,
            None,
            &d,
        );
        assert_eq!(score.value, FINDER_DAMAGE_CAP);
        assert!(
            hints.contains(&Hint::FixFinderPattern { corner: 2 }),
            "{hints:?}"
        );

        // exactly at the floor → NO cap
        let (score, hints) = compose_published(
            axes_with(&[]),
            Some(StructuralReport {
                finder_integrity: [1.0, 1.0, 0.5],
                quiet_zone_ok: true,
            }),
            None,
            None,
            &d,
        );
        assert_eq!(score.value, 100);
        assert!(hints.is_empty(), "{hints:?}");

        // quiet zone violated → capped at 60
        let (score, hints) = compose_published(
            axes_with(&[]),
            Some(StructuralReport {
                finder_integrity: [1.0, 1.0, 1.0],
                quiet_zone_ok: false,
            }),
            None,
            None,
            &d,
        );
        assert_eq!(score.value, QUIET_ZONE_CAP);
        assert!(hints.contains(&Hint::RestoreQuietZone));
    }

    #[test]
    fn hint_thresholds_fire_exactly_at_the_published_boundaries() {
        let d = detection_with(Some(EcLevel::H));

        // contrast survival 40% fires, 60% does not
        let (_, hints) = compose_published(
            axes_with(&[(StressAxis::Contrast, 2, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert!(hints.contains(&Hint::IncreaseContrast), "{hints:?}");
        let (_, hints) = compose_published(
            axes_with(&[(StressAxis::Contrast, 3, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert!(!hints.contains(&Hint::IncreaseContrast), "{hints:?}");

        // resolution likewise → EnlargeModules
        let (_, hints) = compose_published(
            axes_with(&[(StressAxis::Resolution, 2, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert!(hints.contains(&Hint::EnlargeModules), "{hints:?}");
        let (_, hints) = compose_published(
            axes_with(&[(StressAxis::Resolution, 3, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert!(!hints.contains(&Hint::EnlargeModules), "{hints:?}");

        // blur partial survival (1/5) is NOT the texture hint (only 0/5 is)
        let (_, hints) =
            compose_published(axes_with(&[(StressAxis::Blur, 1, 5)]), None, None, None, &d);
        assert!(!hints.contains(&Hint::ReduceArtTexture), "{hints:?}");
    }

    #[test]
    fn raise_ec_hint_value_and_uec_paths() {
        use crate::report::{UecGrade, UecReport};
        let d = detection_with(Some(EcLevel::Q));

        // value 94 (rotation 2/5) + EC<H + healthy margin → no hint
        let (_, hints) = compose_published(
            axes_with(&[(StressAxis::Rotation, 2, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert!(
            !hints
                .iter()
                .any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
            "{hints:?}"
        );

        // value < 70 → fires (blur 0/5 + perspective 0/5: 82-20=62)
        let (score, hints) = compose_published(
            axes_with(&[(StressAxis::Blur, 0, 5), (StressAxis::Perspective, 0, 5)]),
            None,
            None,
            None,
            &d,
        );
        assert!(score.value < 70, "{}", score.value);
        assert!(
            hints.iter().any(|h| matches!(
                h,
                Hint::RaiseErrorCorrection {
                    current: EcLevel::Q
                }
            )),
            "{hints:?}"
        );

        // thin UEC margin (grade D) fires even when every axis passes — and
        // since the margin cap (2026-08-06) the value SAYS the melt too
        // (0.30/0.5 × 60 + 40 = 76, no longer a flat 100 over a thin budget)
        let thin = UecReport {
            margin: 0.30,
            grade: UecGrade::D,
            worst_block_errors: 6,
            worst_block_capacity: 18,
        };
        let (score, hints) = compose_published(axes_with(&[]), None, Some(thin), None, &d);
        assert_eq!(score.value, 76);
        assert!(
            hints
                .iter()
                .any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
            "{hints:?}"
        );

        // margin exactly ZERO → miscorrection-risk hint, with the block stats
        let limit = UecReport {
            margin: 0.0,
            grade: UecGrade::F,
            worst_block_errors: 12,
            worst_block_capacity: 24,
        };
        let (_, hints) = compose_published(axes_with(&[]), None, Some(limit), None, &d);
        assert!(
            hints.contains(&Hint::LowCorrectionMargin {
                errors: 12,
                capacity: 24
            }),
            "{hints:?}"
        );
        // thin-but-nonzero margin does NOT fire the miscorrection hint
        let (_, hints) = compose_published(axes_with(&[]), None, Some(thin), None, &d);
        assert!(
            !hints
                .iter()
                .any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
            "{hints:?}"
        );

        // EC already H → never fires
        let dh = detection_with(Some(EcLevel::H));
        let (_, hints) = compose_published(
            axes_with(&[(StressAxis::Blur, 0, 5)]),
            None,
            Some(thin),
            None,
            &dh,
        );
        assert!(
            !hints
                .iter()
                .any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
            "{hints:?}"
        );
    }

    /// The occlusion cliff (door-admin probe 2026-08-05): a center logo eats
    /// the RS budget while every stress axis keeps passing — the composite
    /// sat at 88 from `logo_scale` 12→18 then fell to no-decode at 24 with no
    /// warning (at EC=H the raise-EC hint can never fire). The margin IS the
    /// distance to that cliff, so it must SHAPE the value: flat while the
    /// budget is healthy, a continuous slope below the half-budget line.
    #[test]
    fn uec_margin_caps_the_composite_continuously() {
        use crate::report::{UecGrade, UecReport};
        let d = detection_with(Some(EcLevel::H));
        let at = |margin: f32| UecReport {
            margin,
            grade: UecGrade::from_margin(margin),
            worst_block_errors: 6,
            worst_block_capacity: 24,
        };
        let value = |uec: Option<UecReport>| {
            compose_published(axes_with(&[]), None, uec, None, &d)
                .0
                .value
        };

        // healthy budget (≥ half) — the cap is a no-op, including the seam
        assert_eq!(value(None), 100, "no measurement → no penalty");
        assert_eq!(value(Some(at(1.0))), 100);
        assert_eq!(
            value(Some(at(0.5))),
            100,
            "continuous seam at the threshold"
        );

        // below half-budget the value slopes down — the cliff gets a warning
        let v37 = value(Some(at(0.37))); // ISO C
        let v25 = value(Some(at(0.25))); // ISO D
        let v10 = value(Some(at(0.10)));
        let v0 = value(Some(at(0.0))); // ISO F — at the RS limit
        assert!(
            v37 < 100 && v25 < v37 && v10 < v25 && v0 < v10,
            "monotone slope: {v37} {v25} {v10} {v0}"
        );
        assert_eq!(v25, 70, "ISO D lands at 70 — visibly below the far band");
        assert_eq!(v0, 40, "RS limit = the finder-damage floor, never a pass");

        // the cap CAPS — it never raises a value the axes already sank
        let sunk = compose_published(
            axes_with(&[(StressAxis::Blur, 0, 5), (StressAxis::Perspective, 0, 5)]),
            None,
            Some(at(0.45)),
            None,
            &d,
        )
        .0
        .value;
        assert!(sunk < 94, "axes verdict survives under a mild cap: {sunk}");
    }

    #[test]
    fn depth_index_sets_pinned() {
        assert_eq!(depth_indices(ScoreDepth::Off), &[] as &[usize]);
        assert_eq!(depth_indices(ScoreDepth::Reduced), &[1, 3]);
        assert_eq!(depth_indices(ScoreDepth::Full), &[0, 1, 2, 3, 4]);
        assert_eq!(lighting_indices(ScoreDepth::Off), &[] as &[usize]);
        assert_eq!(lighting_indices(ScoreDepth::Reduced), &[1, 2]);
        assert_eq!(lighting_indices(ScoreDepth::Full), &[0, 1, 2, 3, 4]);
    }

    /// An axis can legitimately carry `total == 0` (`ScoreDepth::Off`, an empty
    /// ramp). Every `score.total > 0` guard protects a division BY that total,
    /// so a `>`→`>=` swap divides by zero. Under each mutant the matching
    /// compose below panics; under the real guard it yields the exact value.
    #[test]
    fn zero_total_axes_are_skipped_not_divided() {
        let d = detection_with(Some(EcLevel::H));

        // weighted-sum guard (:286) — resolution skipped ⇒ (100−22) = 78
        let (score, _) = compose_published(
            axes_with(&[(StressAxis::Resolution, 0, 0)]),
            None,
            None,
            None,
            &d,
        );
        assert_eq!(score.value, 78);

        // contrast-hint guard (:322) — contrast skipped ⇒ (100−15) = 85, no hint
        let (score, hints) = compose_published(
            axes_with(&[(StressAxis::Contrast, 0, 0)]),
            None,
            None,
            None,
            &d,
        );
        assert_eq!(score.value, 85);
        assert!(!hints.contains(&Hint::IncreaseContrast), "{hints:?}");

        // resolution-hint guard (:328) — a 0/0 axis is not "≤40% survival"
        let (_, hints) = compose_published(
            axes_with(&[(StressAxis::Resolution, 0, 0)]),
            None,
            None,
            None,
            &d,
        );
        assert!(!hints.contains(&Hint::EnlargeModules), "{hints:?}");

        // blur-hint guard (:334) — total==0 must NOT read as "dies at the
        // mildest blur" (that guard is `t > 0`, then `p == 0`)
        let (score, hints) =
            compose_published(axes_with(&[(StressAxis::Blur, 0, 0)]), None, None, None, &d);
        assert_eq!(score.value, 82);
        assert!(!hints.contains(&Hint::ReduceArtTexture), "{hints:?}");
    }

    /// `value < 70` (strict) is the raise-EC gate — the companion test pins the
    /// FIRES side at value 62; this pins the boundary: value EXACTLY 70 with
    /// EC<H and a healthy margin must NOT fire (:350 `<`→`<=`). Perspective 0/5
    /// + Rotation 0/5 drop 20+10 weight ⇒ weighted 7000 ⇒ value 70.
    #[test]
    fn raise_ec_hint_uses_strict_less_than_at_the_value_boundary() {
        let d = detection_with(Some(EcLevel::Q));
        let (score, hints) = compose_published(
            axes_with(&[
                (StressAxis::Perspective, 0, 5),
                (StressAxis::Rotation, 0, 5),
            ]),
            None,
            None,
            None,
            &d,
        );
        assert_eq!(score.value, 70);
        assert!(
            !hints
                .iter()
                .any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
            "value==70 is NOT below the strict-< 70 threshold: {hints:?}"
        );
    }

    /// The content of a plain byte-mode symbol of the `qrcode` encoder: its
    /// bytes, no ECI declaration, no FNC1 — what both engines read of it.
    fn plain_key(payload: &[u8]) -> ContentKey {
        ContentKey {
            raw: payload.to_vec(),
            eci: crate::engine::content::EciEvidence::NoEci,
            fnc1: crate::engine::content::Fnc1::None,
        }
    }

    fn render_qr_candidate(payload: &[u8], version: i16, module: u32, white: u8) -> LumaImage {
        let code = qrcode::QrCode::with_version(
            payload,
            qrcode::Version::Normal(version),
            qrcode::EcLevel::Q,
        )
        .unwrap();
        let rendered = code
            .render::<image::Luma<u8>>()
            .module_dimensions(module, module)
            .dark_color(image::Luma([0]))
            .light_color(image::Luma([white]))
            .build();
        let (width, height) = rendered.dimensions();
        LumaImage::new(rendered.into_raw(), width, height)
    }

    fn score_base_fingerprint(base: &LumaImage) -> u64 {
        // FNV-1a over little-endian dimensions followed by the exact score pixels.
        base.width()
            .to_le_bytes()
            .into_iter()
            .chain(base.height().to_le_bytes())
            .chain(base.data().iter().copied())
            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
            })
    }

    fn assert_measured_axis(
        base: &LumaImage,
        payload: &[u8],
        expected: AxisScore,
        expected_units: u32,
    ) {
        let key = plain_key(payload);
        let cancel = CancelToken::new();
        let mut calibration = Bound::new(&cancel, None).with_quota(16);
        let Calibrated::Class(probe) = CellProbe::calibrate_within(
            base,
            &key,
            crate::report::Symbology::QrCode,
            &mut calibration,
        )
        .unwrap() else {
            panic!("the measured QR witness must calibrate");
        };
        assert_eq!(
            (calibration.spent(), calibration.cut(), calibration.panics()),
            (1, false, 0)
        );
        assert!(probe.rung.is_none());
        assert_eq!(probe.symbology, crate::report::Symbology::QrCode);

        let skip: Vec<_> = WEIGHTS
            .iter()
            .map(|&(other, _)| other)
            .filter(|&other| other != expected.axis)
            .collect();
        let mut bound = Bound::new(&cancel, None).with_quota(6);
        let axes = run_axes(base, &key, ScoreDepth::Full, &skip, &mut bound, probe).unwrap();
        assert_eq!(axes, Some(vec![expected]));
        assert_eq!(
            (bound.spent(), bound.cut(), bound.panics()),
            (expected_units, false, 0)
        );
    }

    #[test]
    fn low_luma_qr_fails_only_the_underexposure_cell() {
        let payload = b"https://qrcode-ai.com/c/v5q";
        let image = render_qr_candidate(payload, 5, 4, 60);
        let base = transform::downscale_to(&image, STRESS_BASE_SIDE);
        assert_eq!((base.width(), base.height()), (180, 180));
        assert_eq!(score_base_fingerprint(&base), 0x09ca_6527_c122_72e5);
        assert_measured_axis(
            &base,
            payload,
            AxisScore {
                axis: StressAxis::Lighting,
                passed: 4,
                total: 5,
                failed_at: Some("underexposure".to_owned()),
                refined_failed_at: None,
            },
            5,
        );
    }

    #[test]
    fn qr_blur_knee_refines_to_the_measured_failing_midpoint() {
        let payload = b"refine knee pin";
        let image = render_qr_candidate(payload, 5, 3, 255);
        let base = transform::downscale_to(&image, STRESS_BASE_SIDE);
        assert_eq!((base.width(), base.height()), (135, 135));
        assert_eq!(score_base_fingerprint(&base), 0x9b0a_eeab_5c72_e34c);
        assert_measured_axis(
            &base,
            payload,
            AxisScore {
                axis: StressAxis::Blur,
                passed: 3,
                total: 5,
                failed_at: Some("blur 2.0".to_owned()),
                refined_failed_at: Some("blur 1.75".to_owned()),
            },
            5,
        );
    }

    #[test]
    fn qr_resolution_knee_refines_to_the_measured_failing_midpoint() {
        let payload = b"https://qrcode-ai.com/c/v5q";
        let image = render_qr_candidate(payload, 13, 3, 255);
        assert_eq!((image.width(), image.height()), (231, 231));
        let base = transform::downscale_to(&image, STRESS_BASE_SIDE);
        assert_eq!((base.width(), base.height()), (231, 231));
        assert_eq!(score_base_fingerprint(&base), 0x54d9_83f4_4539_6ebc);
        assert_measured_axis(
            &base,
            payload,
            AxisScore {
                axis: StressAxis::Resolution,
                passed: 4,
                total: 5,
                failed_at: Some("90px".to_owned()),
                refined_failed_at: Some("109px".to_owned()),
            },
            6,
        );
    }

    /// The primary detection of an unbounded Full walk and its content.
    fn primary_of(planes: &crate::transform::SourcePlanes) -> (MergedDetection, ContentKey) {
        let outcome = ladder::run(planes, &ScanConfig::full(), &CancelToken::new(), None).unwrap();
        (outcome.merged[0].clone(), outcome.contents[0].0.clone())
    }

    /// Decode a pristine QR and hand back the calibrated stress base + probe,
    /// so the private `run_axes` can be driven directly (its internals never
    /// had a value-level test — the lighting accumulator and deadline break
    /// only surface here).
    fn clean_base_and_probe() -> (LumaImage, ContentKey, CellProbe) {
        let code =
            qrcode::QrCode::with_error_correction_level(b"stress-axis pin", qrcode::EcLevel::Q)
                .unwrap();
        let img = code
            .render::<image::Luma<u8>>()
            .module_dimensions(8, 8)
            .build();
        let mut png = Vec::new();
        image::DynamicImage::ImageLuma8(img)
            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
            .unwrap();
        let planes = normalize(&ImageInput::encoded(&png), &Limits::default()).unwrap();
        let (d, key) = primary_of(&planes);
        let base = transform::downscale_to(&planes.luma, STRESS_BASE_SIDE);
        let probe = CellProbe::calibrate(&base, &key, d.symbology).unwrap();
        (base, key, probe)
    }

    /// Every COMPLETE judgment's axes are honest: `passed == total` exactly
    /// when nothing failed, `failed_at` names one of the axis's PLANNED
    /// cells, and a ramp's knee sits right after its survivors.
    fn assert_honest_axes(axes: &[AxisScore], depth: ScoreDepth) {
        for a in axes {
            let picks = if a.axis == StressAxis::Lighting {
                lighting_indices(depth)
            } else {
                depth_indices(depth)
            };
            assert_eq!(usize::from(a.total), picks.len(), "planned cells: {a:?}");
            assert_eq!(
                a.passed == a.total,
                a.failed_at.is_none(),
                "passed == total iff nothing failed: {a:?}"
            );
            if let Some(label) = a.failed_at.as_deref() {
                let at = picks.iter().position(|&i| cell_label(a.axis, i) == label);
                assert!(at.is_some(), "failed_at names a planned cell: {a:?}");
                if a.axis != StressAxis::Lighting {
                    assert_eq!(
                        at,
                        Some(usize::from(a.passed)),
                        "a ramp's knee follows its survivors: {a:?}"
                    );
                }
            }
        }
    }

    /// `run_axes` with no deadline and no quota — never cut.
    fn unbounded_axes(
        base: &LumaImage,
        key: &ContentKey,
        skip: &[StressAxis],
        probe: CellProbe,
    ) -> Vec<AxisScore> {
        let cancel = CancelToken::new();
        let axes = run_axes(
            base,
            key,
            ScoreDepth::Full,
            skip,
            &mut Bound::new(&cancel, None),
            probe,
        )
        .unwrap()
        .expect("an unbounded run is never cut");
        assert_honest_axes(&axes, ScoreDepth::Full);
        axes
    }

    /// `evaluate` with no deadline — a complete judgment.
    fn judged(
        luma: &LumaImage,
        detection: &MergedDetection,
        key: &ContentKey,
        depth: ScoreDepth,
        skip: &[StressAxis],
        checks: &[crate::ladder::ScoreCheck],
    ) -> (Score, Vec<Hint>) {
        let cancel = CancelToken::new();
        let mut bound = Bound::new(&cancel, None);
        let judged = evaluate(luma, detection, key, depth, skip, checks, &mut bound).unwrap();
        assert!(!bound.cut(), "an unbounded judgment is never cut");
        let (score, hints) = judged.expect("an unbounded judgment with axes completes");
        assert_honest_axes(&score.axes, depth);
        (score, hints)
    }

    /// THE 100-IS-REACHABLE INVARIANT (operator lock 2026-07-10). A pristine
    /// full-frame symbol survives ALL five lighting cells — the glare blob
    /// lands on the DATA region (symbol centre), where the error-correction
    /// budget absorbs it. The old (0.3w, 0.3h) placement saturated the
    /// top-left finder: a structural kill NO design survives, capping every
    /// perfect render at 4/5 lighting (the 95-ceiling class — the axis
    /// measured the instrument, not the symbol; same class as the W8
    /// rotation-cropping fix). This pin also catches the flood-mutant
    /// (`radius/0.18` whites the whole frame → the cell fails → 4/5 here).
    #[test]
    fn pristine_symbol_survives_all_lighting_cells() {
        let (base, key, probe) = clean_base_and_probe();
        let axes = unbounded_axes(&base, &key, &[], probe);
        let lighting = axes
            .iter()
            .find(|a| a.axis == StressAxis::Lighting)
            .unwrap();
        assert_eq!(
            lighting.passed, 5,
            "a pristine full-frame symbol must survive every lighting cell \
             (glare sits on the data region, not a finder): {lighting:?}"
        );
        assert!(
            lighting.failed_at.is_none(),
            "all-passed carries no failed_at: {lighting:?}"
        );
    }

    /// THE PRODUCT PINS — the builder's real rendered pixels, committed as
    /// fixtures. (a) The default render (black rounded modules on white,
    /// ECC M) reaches the full 100: every lost point below this is caused by
    /// the USER's design, never by the instrument. (b) A real styled
    /// template (pale-pink hearts + centre logo) loses lighting cells and
    /// the wire NAMES the first failed cell — the explainability contract
    /// the panel renders ("Light 3/5 · hard shadow"). Also the guard for
    /// glare placement/radius mutants: an off-canvas or flooding blob flips
    /// (a) or (b).
    #[test]
    fn builder_default_render_reaches_100_and_styled_explains_its_losses() {
        let score_of = |rel: &str| {
            let path = format!("{}/../../{rel}", env!("CARGO_MANIFEST_DIR"));
            let bytes = std::fs::read(&path).expect("builder fixture present");
            let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
            let (detection, key) = primary_of(&planes);
            judged(&planes.luma, &detection, &key, ScoreDepth::Full, &[], &[])
        };

        // (a) the default render: a perfect score is REACHABLE.
        let (default_score, _) = score_of("fixtures/clean/builder-default-rounded-1024.png");
        assert_eq!(
            default_score.value, 100,
            "the pristine default render must reach 100 — a ceiling below that \
             measures the instrument, not the design: {:?}",
            default_score.axes
        );

        // (b) the styled template: losses exist AND name their cell.
        let (styled_score, _) = score_of("fixtures/artistic/builder-template-hearts-web-1024.png");
        assert!(
            styled_score.value < 100,
            "the pale styled template keeps real, explained losses: {}",
            styled_score.value
        );
        let lighting = styled_score
            .axes
            .iter()
            .find(|a| a.axis == StressAxis::Lighting)
            .unwrap();
        assert!(
            lighting.passed < lighting.total,
            "the styled template loses lighting cells: {lighting:?}"
        );
        assert_eq!(
            lighting.failed_at.as_deref(),
            Some("hard shadow"),
            "the first failed cell is named on the wire: {lighting:?}"
        );
    }

    /// A flawless high-version symbol with the renderer's standard 4-module
    /// quiet zone. Engines are rotation-invariant on clean symbols (finder
    /// geometry is angle-free), so every death on this ramp is a PROBE
    /// artifact. The same-canvas rotate amputated the corners — a v10's
    /// corner radius (≈0.62·w) leaves the frame at the very first 10° step —
    /// and the axis read "fragile at 10°" for a symbol any phone rotates
    /// through happily: the probe measured the frame, not the engine.
    #[test]
    fn rotation_ramp_measures_engine_tolerance_not_frame_cropping() {
        let code = qrcode::QrCode::with_version(
            b"rotation probe: the frame must never eat the finders",
            qrcode::Version::Normal(10),
            qrcode::EcLevel::Q,
        )
        .unwrap();
        let img = code
            .render::<image::Luma<u8>>()
            .module_dimensions(4, 4)
            .build();
        let (w, h) = (img.width(), img.height());
        let base = LumaImage::new(img.into_raw(), w, h);
        let key = plain_key(b"rotation probe: the frame must never eat the finders");
        let probe = CellProbe::calibrate(&base, &key, crate::report::Symbology::QrCode)
            .expect("flawless base calibrates");
        let axes = unbounded_axes(&base, &key, &[], probe);
        let rotation = axes
            .iter()
            .find(|a| a.axis == StressAxis::Rotation)
            .unwrap();
        assert_eq!(
            rotation.passed, 5,
            "a flawless v10 died on the rotation ramp — the probe is measuring \
             frame cropping, not engine tolerance: {rotation:?}"
        );
    }

    /// Integration skip: skipped axes never run (their cells are never
    /// built), the report self-describes (axes[] omits them), the composite
    /// renormalizes over the run weights, and axis-derived hints from
    /// skipped axes structurally cannot fire. The builder case: a generated
    /// preview has no capture angle — perspective + rotation are noise there.
    #[test]
    fn skipped_axes_never_run_and_the_composite_renormalizes() {
        let (base, key, probe) = clean_base_and_probe();
        let full = unbounded_axes(&base, &key, &[], probe);
        let skipped = unbounded_axes(
            &base,
            &key,
            &[StressAxis::Perspective, StressAxis::Rotation],
            probe,
        );
        assert_eq!(skipped.len(), 4, "six axes minus the two skipped");
        assert!(
            skipped
                .iter()
                .all(|a| a.axis != StressAxis::Perspective && a.axis != StressAxis::Rotation),
            "skipped axes are absent from the report: {skipped:?}"
        );
        // The four surviving axes measure identically to the full run —
        // skipping is subtraction, never a change to what still runs.
        for a in &skipped {
            let twin = full.iter().find(|f| f.axis == a.axis).unwrap();
            assert_eq!((a.passed, a.total), (twin.passed, twin.total));
        }
        // Renormalized arithmetic on this pristine fixture (every cell
        // passes since the glare cell moved onto the data region — the
        // 100-is-reachable invariant, pinned by the sibling tests): both
        // sums are all-100s, so full AND skip read exactly 100. The divisor
        // truth (Σ run weights, not the constant 100) is pinned just below
        // by the lone half-passed lighting axis reading 50, never 7.
        let d = detection_with(Some(EcLevel::H));
        let (score_full, _) = compose_published(full, None, None, None, &d);
        let (score_skip, _) = compose_published(skipped, None, None, None, &d);
        assert_eq!(score_full.value, 100, "full six-axis composite");
        assert_eq!(score_skip.value, 100, "renormalized four-axis composite");
        // And the renormalization actually renormalizes: a half-passed
        // lighting axis alone must read 50, not 7 (its weight over 100).
        let lone = vec![AxisScore {
            axis: StressAxis::Lighting,
            passed: 1,
            total: 2,
            failed_at: None,
            refined_failed_at: None,
        }];
        let (score_lone, _) = compose_published(lone, None, None, None, &d);
        assert_eq!(score_lone.value, 50, "weights re-span the run set");
    }

    /// The glare cell ACTS — the anti-no-op / placement / radius guard. A
    /// symbol parked in the bottom-right quadrant of a 2× canvas puts the
    /// canvas centre exactly on its top-left finder: the centred blob kills
    /// it (4/5 + `failed_at` "glare"). Mutants all flip this: a no-op glare
    /// reads 5/5; an off-canvas centre (`0.5`→`/0.5`) reads 5/5; a flooding
    /// radius (`/0.18`) takes more cells down (≤3). The pristine-full-frame
    /// sibling pins the other side: centred glare on the DATA region is
    /// survivable — together they hold the cell to "lethal exactly where a
    /// finder sits, absorbable where the ECC budget rules".
    #[test]
    fn glare_cell_stays_lethal_on_a_finder_and_names_itself() {
        let code =
            qrcode::QrCode::with_error_correction_level(b"canvas glare pin", qrcode::EcLevel::H)
                .unwrap();
        let qr = code
            .render::<image::Luma<u8>>()
            .module_dimensions(6, 6)
            .build();
        let (qw, qh) = (qr.width(), qr.height());
        let (cw, ch) = (qw * 2, qh * 2);
        let mut canvas = vec![255u8; (cw * ch) as usize];
        for yy in 0..qh {
            for xx in 0..qw {
                canvas[((yy + qh) * cw + (xx + qw)) as usize] = qr.get_pixel(xx, yy).0[0];
            }
        }
        let base = LumaImage::new(canvas, cw, ch);
        let key = plain_key(b"canvas glare pin");
        let probe = CellProbe::calibrate(&base, &key, crate::report::Symbology::QrCode)
            .expect("corner symbol calibrates");
        let axes = unbounded_axes(&base, &key, &[], probe);
        let lighting = axes
            .iter()
            .find(|a| a.axis == StressAxis::Lighting)
            .unwrap();
        assert_eq!(
            lighting.passed, 4,
            "the canvas-centre blob sits on the corner symbol's TL finder and \
             must kill exactly the glare cell: {lighting:?}"
        );
        assert_eq!(
            lighting.failed_at.as_deref(),
            Some("glare"),
            "the kill names itself on the wire: {lighting:?}"
        );
    }

    /// The lighting set counts survivors with `lighting_passed += 1`; a
    /// `+=`→`*=` swap (:261) would multiply the zero seed forever. A pristine
    /// symbol survives ≥1 of the five lighting cells, so the count must move.
    #[test]
    fn lighting_pass_count_accumulates() {
        let (base, key, probe) = clean_base_and_probe();
        let axes = unbounded_axes(&base, &key, &[], probe);
        let lighting = axes
            .iter()
            .find(|a| a.axis == StressAxis::Lighting)
            .unwrap();
        assert!(
            lighting.passed >= 1,
            "clean symbol must survive ≥1 lighting cell: {lighting:?}"
        );
    }

    /// A deadline already in the past stops the lighting set before any cell
    /// runs (`Instant::now() >= d`) — and the set is then INTERRUPTED, not a
    /// fabricated 0/5. The mutant `<` never fires on a past deadline, so it
    /// would run the set and report survivors.
    #[test]
    fn a_past_deadline_stops_the_lighting_set() {
        let (base, key, probe) = clean_base_and_probe();
        let cancel = CancelToken::new();
        let mut bound = Bound::new(&cancel, Some(Instant::now()));
        let lighting = run_lighting(&base, &key, ScoreDepth::Full, &mut bound, probe).unwrap();
        assert!(
            lighting.is_none(),
            "a past deadline interrupts the set: {lighting:?}"
        );
        assert_eq!(bound.spent(), 0, "no lighting cell ran");
    }

    /// Kanji-mode regression for the SCORING path (the ladder-side fix has
    /// its own test): stress cells match by content — both engines read the
    /// original Shift JIS bytes, so an rxing-only survival counts. Keyed on
    /// rxing's re-encoded bytes, cells silently failed every such survival
    /// on Kanji symbols.
    #[test]
    fn kanji_symbol_scores_with_content_keyed_cells() {
        let sjis: &[u8] = &[0x82, 0xB1, 0x82, 0xF1, 0x82, 0xC9, 0x82, 0xBF, 0x82, 0xCD];
        let code = qrcode::QrCode::with_error_correction_level(sjis, qrcode::EcLevel::Q).unwrap();
        let img = code
            .render::<image::Luma<u8>>()
            .module_dimensions(8, 8)
            .build();
        let mut png = Vec::new();
        image::DynamicImage::ImageLuma8(img)
            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
            .unwrap();
        let planes = normalize(&ImageInput::encoded(&png), &Limits::default()).unwrap();
        let (detection, key) = primary_of(&planes);
        assert_eq!(detection.text, "こんにちは");

        let (score, _) = judged(&planes.luma, &detection, &key, ScoreDepth::Full, &[], &[]);
        // a pristine 8px/module symbol survives the early cells of every
        // axis — keyed on rxing's re-encoded bytes, its rxing-only cells
        // scored ZERO
        let total_passed: u32 = score.axes.iter().map(|a| u32::from(a.passed)).sum();
        assert!(
            total_passed >= 12,
            "kanji symbol must survive stress cells: {:?}",
            score.axes
        );
        assert!(score.value >= 50, "score {}", score.value);
    }

    /// The section-skip seam: `score_skip_checks` nulls exactly the skipped
    /// blocks, silences the UEC-driven hints with them, and leaves the
    /// composite untouched — while the empty default stays byte-identical
    /// (uec + iso present on a clean rqrr decode).
    #[test]
    fn skip_checks_null_their_sections_and_leave_value_alone() {
        use crate::ladder::ScoreCheck;
        let (luma, detection, key) = pristine_q_example();
        let run =
            |checks: &[ScoreCheck]| judged(&luma, &detection, &key, ScoreDepth::Full, &[], checks);

        // Default: every section present on a clean bitstream decode.
        let (full, _) = run(&[]);
        assert!(full.uec.is_some(), "clean rqrr decode must measure UEC");
        assert!(full.iso15415.is_some(), "corners + version must yield ISO");

        // Both skipped: sections null, hints silent, composite unchanged.
        let (skipped, hints) = run(&[ScoreCheck::Uec, ScoreCheck::Iso15415]);
        assert!(skipped.uec.is_none());
        assert!(skipped.iso15415.is_none());
        assert!(
            !hints
                .iter()
                .any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
            "no uec → its miscorrection hint cannot fire"
        );
        assert_eq!(
            skipped.value, full.value,
            "checks are surface truth — the axis composite never moves"
        );

        // UEC alone: ISO still present, its UEC parameter honestly null.
        let (uec_only, _) = run(&[ScoreCheck::Uec]);
        assert!(uec_only.uec.is_none());
        let iso = uec_only.iso15415.expect("iso block still runs");
        assert!(
            iso.unused_error_correction.is_none(),
            "no uec input → the ISO parameter reads null, never faked"
        );
    }

    /// A v2-Q symbol — ONE RS block, 22 EC codewords — with one module
    /// toggled in each of its first `k` codewords (the MSB of codeword `i`
    /// sits at zigzag bit `8·i`): exactly `k` corrected errors in the worst
    /// block, so the margin reads `1 − 2k/22`, while every module boundary
    /// stays crisp and the stress cells keep decoding. 10 px modules on the
    /// standard 4-module quiet zone, decoded by the unbounded Full ladder.
    fn thin_margin_v2q(k: u8) -> (LumaImage, MergedDetection, ContentKey) {
        const MODULE: usize = 10;
        const QUIET: usize = 4;
        let code = qrcode::QrCode::with_version(
            b"thin margin pin",
            qrcode::Version::Normal(2),
            qrcode::EcLevel::Q,
        )
        .unwrap();
        let width = code.width();
        let mut dark: Vec<bool> = code
            .into_colors()
            .into_iter()
            .map(|c| c == qrcode::Color::Dark)
            .collect();
        for &(y, x) in crate::matrix::zigzag::zigzag_positions(2)
            .iter()
            .step_by(8)
            .take(usize::from(k))
        {
            dark[y * width + x] ^= true;
        }
        let side = (width + 2 * QUIET) * MODULE;
        let mut pixels = vec![255u8; side * side];
        for (i, _) in dark.iter().enumerate().filter(|(_, is_dark)| **is_dark) {
            let (my, mx) = (i / width + QUIET, i % width + QUIET);
            for row in pixels.chunks_mut(side).skip(my * MODULE).take(MODULE) {
                row[mx * MODULE..(mx + 1) * MODULE].fill(0);
            }
        }
        let side = u32::try_from(side).unwrap();
        let planes =
            normalize(&ImageInput::luma8(&pixels, side, side), &Limits::default()).unwrap();
        let (detection, key) = primary_of(&planes);
        (planes.luma, detection, key)
    }

    /// Skip invariance on the case the margin-1.0 sibling cannot see: a
    /// thin margin, where the UEC cap is ACTIVE. Skipping the `uec` section
    /// withholds the why (section + the two hints it drives) — never the
    /// verdict: value, grade, `weights_run` and axes are identical.
    #[test]
    fn skipping_uec_never_moves_a_thin_margin_composite() {
        use crate::ladder::ScoreCheck;
        use crate::report::UecGrade;
        const K: u8 = 8;
        let (luma, detection, key) = thin_margin_v2q(K);
        assert!(
            detection.masked_stream.is_some(),
            "precondition: the rqrr stream is present — the margin is measurable"
        );
        // contrast alone: one axis that survives the damage end to end, so
        // the uncapped composite is exactly 100 and every lost point is the cap's
        let only_contrast = [
            StressAxis::Resolution,
            StressAxis::Blur,
            StressAxis::Perspective,
            StressAxis::Rotation,
            StressAxis::Lighting,
        ];
        let run = |checks: &[ScoreCheck]| {
            judged(
                &luma,
                &detection,
                &key,
                ScoreDepth::Full,
                &only_contrast,
                checks,
            )
        };

        let (shown, shown_hints) = run(&[]);
        let uec = shown.uec.expect("the default checks publish the margin");
        assert_eq!(
            (uec.worst_block_errors, uec.worst_block_capacity),
            (K, 22),
            "precondition: exactly K errors in the one v2-Q block: {uec:?}"
        );
        let expected_margin = 1.0 - 2.0 * f32::from(K) / 22.0;
        assert!(
            (uec.margin - expected_margin).abs() < 1e-6,
            "precondition: margin {} vs 1 − 2·{K}/22",
            uec.margin
        );
        assert_eq!(uec.grade, UecGrade::D);
        assert_eq!(
            shown
                .axes
                .iter()
                .map(|a| (a.axis, a.passed, a.total))
                .collect::<Vec<_>>(),
            vec![(StressAxis::Contrast, 5, 5)],
            "precondition: the uncapped composite is 100"
        );
        assert_eq!(shown.value, uec_margin_cap(uec.margin));
        assert_eq!(shown.value, 73, "0.2727/0.5 × 60 + 40 = 72.7 → 73");
        assert!(
            shown_hints.contains(&Hint::RaiseErrorCorrection {
                current: EcLevel::Q
            }),
            "a published grade-D margin drives the raise-EC hint: {shown_hints:?}"
        );

        let (hidden, hidden_hints) = run(&[ScoreCheck::Uec]);
        assert_eq!(
            (hidden.value, hidden.grade, hidden.weights_run),
            (shown.value, shown.grade, shown.weights_run),
            "skipping a check never moves the composite"
        );
        assert_eq!(hidden.axes, shown.axes);
        assert!(hidden.uec.is_none(), "the skipped section stays withheld");
        let shown_iso = shown.iso15415.expect("the ISO block runs");
        let hidden_iso = hidden.iso15415.expect("the ISO block still runs");
        assert!(
            hidden_iso.unused_error_correction.is_none(),
            "the ISO UEC parameter follows the published section"
        );
        // the ISO verdict is the minimum over every MEASURED parameter: the
        // grade-D margin keeps setting it while its parameter is withheld
        let margin_grade = shown_iso
            .unused_error_correction
            .expect("published by default")
            .grade;
        assert_eq!(shown_iso.overall, margin_grade, "{shown_iso:?}");
        assert_eq!(
            hidden_iso.overall, shown_iso.overall,
            "skipping a check never moves the ISO overall"
        );
        assert!(
            !hidden_hints.iter().any(|h| matches!(
                h,
                Hint::RaiseErrorCorrection { .. } | Hint::LowCorrectionMargin { .. }
            )),
            "UEC-driven hints follow the published section: {hidden_hints:?}"
        );
    }

    /// A fixed-mask v1-L render with exact codeword errors, publicly scanned
    /// without a budget. Contrast alone exposes the correction-margin cap.
    fn scan_v1l_codeword_damage(
        corrupt: &[usize],
        checks: &[crate::ladder::ScoreCheck],
    ) -> crate::report::ScanReport {
        use crate::rescue::test_symbols::{drawn_v1l, v1l_codewords};

        let mut codewords = v1l_codewords(b"abc");
        assert_eq!(codewords.len(), 26, "19 data + 7 parity codewords");
        for &index in corrupt {
            codewords[index] ^= 0xFF;
        }
        // Fixed mask and geometry make the refused twin differ only in one
        // additional corrupt codeword, never in the encoder's mask choice.
        let luma = drawn_v1l(&codewords);
        let mut config = ScanConfig::full();
        config.budget_ms = None;
        config.score_skip_axes = vec![
            StressAxis::Resolution,
            StressAxis::Blur,
            StressAxis::Perspective,
            StressAxis::Rotation,
            StressAxis::Lighting,
        ];
        config.score_skip_checks = checks.to_vec();
        crate::Scanner::builder()
            .profile(crate::ScanProfile::Custom(config))
            .build()
            .scan(ImageInput::luma8(luma.data(), luma.width(), luma.height()))
            .unwrap()
    }

    /// v1-L acceptance reserves three of its seven parity codewords: two
    /// errors reach that limit, while synthetic UEC deliberately reports
    /// `1 - 2t/d = 3/7`, grade C. The ISO-informed parameter repeats that
    /// synthetic margin; it is not an ISO-conformant correction margin.
    #[test]
    fn v1l_acceptance_limit_keeps_synthetic_uec_and_skipped_check_caps() {
        use crate::ladder::ScoreCheck;
        use crate::report::{Charset, IsoGrade, IsoParameter, Symbology, UecGrade};

        let shown = scan_v1l_codeword_damage(&[0, 2], &[]);
        assert_eq!(shown.trace.budget_exhausted, Some(false));
        assert_eq!(shown.trace.engine_panics, 0);
        assert_eq!(shown.detections.len(), 1, "{shown:?}");
        let detection = &shown.detections[0];
        assert_eq!(detection.symbology, Symbology::QrCode);
        assert_eq!(detection.content.raw, b"abc");
        assert_eq!(detection.content.text, "abc");
        assert_eq!(detection.content.charset, Charset::Utf8);
        assert_eq!(detection.content.eci, None);
        assert_eq!(detection.content.fnc1, None);
        let meta = detection.meta;
        assert_eq!(
            (meta.version, meta.ec_level, meta.modules, meta.mask),
            (Some(1), Some(EcLevel::L), Some(21), Some(3))
        );

        let score = shown.score.as_ref().expect("unbounded complete judgment");
        let uec = score.uec.expect("the two errors are measurable");
        assert_eq!(
            (uec.worst_block_errors, uec.worst_block_capacity, uec.grade),
            (2, 7, UecGrade::C)
        );
        assert!((uec.margin - 3.0 / 7.0).abs() < 1e-6, "{uec:?}");
        assert_eq!(
            score.axes,
            vec![AxisScore {
                axis: StressAxis::Contrast,
                passed: 5,
                total: 5,
                failed_at: None,
                refined_failed_at: None,
            }],
            "precondition: the uncapped composite is 100"
        );
        assert_eq!(score.weights_run, 15);
        assert_eq!((score.value, score.grade), (91, Grade::Excellent));
        let iso = score.iso15415.expect("the ISO-informed card is measured");
        assert_eq!(
            iso.unused_error_correction,
            Some(IsoParameter {
                value: uec.margin,
                grade: IsoGrade::C,
            })
        );
        // Acceptance margin zero does not imply synthetic margin zero, and
        // grade C drives neither of the UEC hints on this rendered symbol.
        assert!(!shown.hints.iter().any(|hint| matches!(
            hint,
            Hint::LowCorrectionMargin { .. } | Hint::RaiseErrorCorrection { .. }
        )));

        for checks in [
            &[ScoreCheck::Uec][..],
            &[ScoreCheck::Iso15415][..],
            &[ScoreCheck::Uec, ScoreCheck::Iso15415][..],
        ] {
            let hidden = scan_v1l_codeword_damage(&[0, 2], checks);
            assert_eq!(hidden.trace.budget_exhausted, Some(false));
            assert_eq!(hidden.trace.engine_panics, 0);
            assert_eq!(hidden.detections, shown.detections, "{checks:?}");
            let mut expected = score.clone();
            if checks.contains(&ScoreCheck::Uec) {
                expected.uec = None;
                if let Some(card) = &mut expected.iso15415 {
                    card.unused_error_correction = None;
                }
            }
            if checks.contains(&ScoreCheck::Iso15415) {
                expected.iso15415 = None;
            }
            // Equality pins value, grade, axes, weights, structural checks
            // and the retained ISO overall, allowing only section visibility.
            assert_eq!(hidden.score, Some(expected), "{checks:?}");
            assert_eq!(hidden.hints, shown.hints, "{checks:?}");
        }

        // Plain RS still corrects three errors, but 2*3 + p=3 > d=7:
        // every read of this stream is past the reserve and must be refused.
        let refused = scan_v1l_codeword_damage(&[0, 2, 4], &[]);
        assert_eq!(refused.trace.budget_exhausted, Some(false));
        assert_eq!(refused.trace.engine_panics, 0);
        assert_eq!(refused.detections, Vec::new(), "{refused:?}");
        assert_eq!(refused.score, None);
        assert_eq!(refused.hints, Vec::new());
    }

    /// The pristine EC-Q symbol of the section-skip seam — a clean rqrr
    /// decode whose every stress cell survives.
    fn pristine_q_example() -> (LumaImage, MergedDetection, ContentKey) {
        let code =
            qrcode::QrCode::with_error_correction_level(b"https://example.com", qrcode::EcLevel::Q)
                .unwrap();
        let img = code
            .render::<image::Luma<u8>>()
            .module_dimensions(8, 8)
            .build();
        let mut png = Vec::new();
        image::DynamicImage::ImageLuma8(img)
            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
            .unwrap();
        let planes = normalize(&ImageInput::encoded(&png), &Limits::default()).unwrap();
        let (detection, key) = primary_of(&planes);
        (planes.luma, detection, key)
    }

    /// A deadline that expired before scoring judged NOTHING — so the report
    /// says nothing. The pre-fix pipeline read every unrun cell as a failure:
    /// a pristine symbol came back 0/poor with four fabricated hints.
    #[test]
    fn an_expired_deadline_yields_no_judgment() {
        let (luma, detection, key) = pristine_q_example();
        let cancel = CancelToken::new();
        for depth in [ScoreDepth::Full, ScoreDepth::Reduced] {
            let mut expired = Bound::new(&cancel, Some(Instant::now()));
            let judged = evaluate(&luma, &detection, &key, depth, &[], &[], &mut expired).unwrap();
            assert!(
                judged.is_none(),
                "{depth:?}: an expired deadline must yield no judgment, got {judged:?}"
            );
            assert!(expired.cut(), "{depth:?}: and says the deadline cut it");
            // not even calibration ran: the deadline is checked before every step
            let mut bound = Bound::new(&cancel, Some(Instant::now()));
            let outcome = judge(&luma, &detection, &key, depth, &[], &[], &mut bound).unwrap();
            assert!(
                matches!(outcome, Judgment::Interrupted),
                "{depth:?}: {outcome:?}"
            );
            assert_eq!(bound.spent(), 0, "{depth:?}: no calibration step, no cell");
        }
    }

    /// A judgment the bound refuses at its first step builds nothing — not
    /// even the stress base: the deadline is checked before any pixel work.
    #[test]
    fn a_judgment_refused_at_its_first_step_builds_nothing() {
        let (luma, detection, key) = pristine_q_example();
        let cancel = CancelToken::new();
        let built = || STRESS_BASES.with(std::cell::Cell::get);
        let before = built();
        let mut bound = Bound::new(&cancel, None).with_quota(0);
        let outcome = judge(
            &luma,
            &detection,
            &key,
            ScoreDepth::Full,
            &[],
            &[],
            &mut bound,
        )
        .unwrap();
        assert!(matches!(outcome, Judgment::Interrupted), "{outcome:?}");
        assert_eq!(bound.spent(), 0);
        assert_eq!(built() - before, 0, "no stress base for a refused judgment");
        // one admitted step builds the base once
        let mut bound = Bound::new(&cancel, None).with_quota(1);
        let outcome = judge(
            &luma,
            &detection,
            &key,
            ScoreDepth::Full,
            &[],
            &[],
            &mut bound,
        )
        .unwrap();
        assert!(matches!(outcome, Judgment::Interrupted), "{outcome:?}");
        assert_eq!(built() - before, 1);
    }

    /// A knee bisection the bound refuses drops only its label: the score
    /// stands, and the evaluation reports the cut (the report's flag).
    #[test]
    fn a_cut_bisection_keeps_the_score_and_reports_the_cut() {
        let (luma, detection, key) = kneed_example();
        let cancel = CancelToken::new();
        let mut free = Bound::new(&cancel, None);
        let Judgment::Complete(reference, _) = judge(
            &luma,
            &detection,
            &key,
            ScoreDepth::Full,
            &[],
            &[],
            &mut free,
        )
        .unwrap() else {
            panic!("an unbounded judgment completes");
        };
        assert!(!free.cut(), "an unbounded judgment is never cut");
        let complete = complete_units(&luma, &detection, &key, &reference);
        assert!(
            free.spent() > complete,
            "precondition: knees to bisect after the cells"
        );
        let mut bound = Bound::new(&cancel, None).with_quota(complete);
        let Judgment::Complete(score, _) = judge(
            &luma,
            &detection,
            &key,
            ScoreDepth::Full,
            &[],
            &[],
            &mut bound,
        )
        .unwrap() else {
            panic!("every planned cell fits the quota");
        };
        assert_eq!(
            (score.value, score.grade),
            (reference.value, reference.grade)
        );
        assert!(score.axes.iter().all(|a| a.refined_failed_at.is_none()));
        assert!(bound.cut(), "the refused bisections are a cut");
    }

    /// `ScanConfig::computes_score` and `Judgment::NoAxes` are one rule:
    /// whatever the depth and the skipped axes, a configuration judges
    /// nothing exactly when it computes no score.
    #[test]
    fn judge_no_axes_iff_config_computes_no_score() {
        let (luma, detection, key) = pristine_q_example();
        let cancel = CancelToken::new();
        let every: Vec<StressAxis> = WEIGHTS.iter().map(|&(axis, _)| axis).collect();
        let skips: [&[StressAxis]; 4] = [
            &[],
            &[StressAxis::Lighting],
            &every[..every.len() - 1],
            &every,
        ];
        for depth in [ScoreDepth::Off, ScoreDepth::Reduced, ScoreDepth::Full] {
            for skip in skips {
                let mut config = ScanConfig::full();
                config.score_depth = depth;
                config.score_skip_axes = skip.to_vec();
                // a quota of 0: a planned judgment is interrupted at its first
                // step, so the rule is read without running a cell
                let mut bound = Bound::new(&cancel, None).with_quota(0);
                let outcome = judge(&luma, &detection, &key, depth, skip, &[], &mut bound).unwrap();
                assert_eq!(
                    matches!(outcome, Judgment::NoAxes),
                    !config.computes_score(),
                    "{depth:?} skipping {skip:?}: {outcome:?}"
                );
            }
        }
        assert!(ScanConfig::full().computes_score() && ScanConfig::fast().computes_score());
        assert!(!ScanConfig::frame().computes_score());
    }

    /// No planned cell, no judgment — every axis skipped (an axis-less
    /// composite would be fiction) and depth `Off` (the frame posture) both
    /// judge nothing and spend nothing.
    #[test]
    fn no_planned_cell_judges_nothing() {
        let (luma, detection, key) = pristine_q_example();
        let cancel = CancelToken::new();
        let every_axis: Vec<StressAxis> = WEIGHTS.iter().map(|&(axis, _)| axis).collect();
        for (depth, skip) in [
            (ScoreDepth::Full, every_axis.as_slice()),
            (ScoreDepth::Reduced, every_axis.as_slice()),
            (ScoreDepth::Off, &[][..]),
        ] {
            let mut bound = Bound::new(&cancel, None);
            let outcome = judge(&luma, &detection, &key, depth, skip, &[], &mut bound).unwrap();
            assert!(
                matches!(outcome, Judgment::NoAxes),
                "{depth:?}: {outcome:?}"
            );
            assert_eq!(bound.spent(), 0);
            let mut free = Bound::new(&cancel, None);
            let judged = evaluate(&luma, &detection, &key, depth, skip, &[], &mut free).unwrap();
            assert!(
                judged.is_none() && !free.cut(),
                "{depth:?}: nothing planned, nothing cut: {judged:?}"
            );
        }
    }

    /// Cancellation is QRS-005 at the very first step — calibration
    /// included (its walk used to run up to 17 decodes deaf to the token).
    #[test]
    fn cancellation_reaches_calibration() {
        let (luma, detection, key) = pristine_q_example();
        let cancel = CancelToken::new();
        cancel.cancel();
        let mut bound = Bound::new(&cancel, None);
        let outcome = judge(
            &luma,
            &detection,
            &key,
            ScoreDepth::Full,
            &[],
            &[],
            &mut bound,
        );
        assert!(
            matches!(outcome, Err(crate::error::ScanError::Cancelled)),
            "{outcome:?}"
        );
        assert_eq!(bound.spent(), 0);
    }

    /// A committed fixture decoded by the unbounded Full ladder.
    fn fixture_example(rel: &str) -> (LumaImage, MergedDetection, ContentKey) {
        let path = format!("{}/../../fixtures/{rel}", env!("CARGO_MANIFEST_DIR"));
        let bytes = std::fs::read(&path).expect("fixture present");
        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
        let (detection, key) = primary_of(&planes);
        (planes.luma, detection, key)
    }

    /// The blob-style production template: it decodes only through a morph
    /// rung and its ramps knee.
    fn kneed_example() -> (LumaImage, MergedDetection, ContentKey) {
        fixture_example("artistic/blob-style-monkey-logo.webp")
    }

    /// The logo-occluded v5-H symbol only the S5 rescue decodes (errors and
    /// erasures): no stress-cell decode class reads its base — the
    /// Undecodable boundary, still a complete judgment.
    fn rescue_example() -> (LumaImage, MergedDetection, ContentKey) {
        let (luma, detection, key) = fixture_example("degraded/logo-occluded-rescue.png");
        assert_eq!(
            detection.engines,
            vec![crate::report::EngineKind::Rescue],
            "precondition: a rescue-only decode"
        );
        (luma, detection, key)
    }

    /// The unbounded calibration walk: how it ended and the steps it took.
    fn calibration_walk(
        luma: &LumaImage,
        detection: &MergedDetection,
        key: &ContentKey,
    ) -> (Calibrated, u32) {
        let base = transform::downscale_to(luma, STRESS_BASE_SIDE);
        let cancel = CancelToken::new();
        let mut walk = Bound::new(&cancel, None);
        let calibrated =
            CellProbe::calibrate_within(&base, key, detection.symbology, &mut walk).unwrap();
        (calibrated, walk.spent())
    }

    /// A walk that ends on a deep rung remembers the pass that read the
    /// rung's image as the rung's own: the pairs of the cell as built and of
    /// its binarization read the base alone, which no class reads here.
    #[test]
    fn a_walk_that_ends_on_a_rung_remembers_the_rungs_own_pairs() {
        let (luma, detection, key) = kneed_example();
        let base = transform::downscale_to(&luma, STRESS_BASE_SIDE);
        let cancel = CancelToken::new();
        let mut walk = Bound::new(&cancel, None);
        let calibrated =
            CellProbe::calibrate_within(&base, &key, detection.symbology, &mut walk).unwrap();
        assert!(
            matches!(
                calibrated,
                Calibrated::Class(CellProbe { rung: Some(_), .. })
            ),
            "precondition: only a rung reads the base"
        );
        let read = |variant: Variant| {
            engine::probe_readers(detection.symbology)
                .iter()
                .filter_map(|reader| {
                    let pair = Pair {
                        variant,
                        reader: *reader,
                    };
                    walk.schedule.trials[pair.slot()]
                })
                .map(|trial| trial.read)
                .collect::<Vec<bool>>()
        };
        assert!(read(Variant::Rung).contains(&true), "the rung's pass");
        for variant in [Variant::Otsu, Variant::Plain] {
            let passes = read(variant);
            assert!(!passes.is_empty(), "{variant:?}: the base was tried");
            assert!(!passes.contains(&true), "{variant:?}: the base reads");
        }
    }

    /// The probe steps a complete judgment needs, derived independently of
    /// `judge`: the calibration walk (to a class, or through every class when
    /// none reads the base), then every PLANNED cell — a ramp runs through
    /// its knee, the lighting set runs whole.
    fn complete_units(
        luma: &LumaImage,
        detection: &MergedDetection,
        key: &ContentKey,
        score: &Score,
    ) -> u32 {
        let (calibrated, walk) = calibration_walk(luma, detection, key);
        assert!(
            !matches!(calibrated, Calibrated::Interrupted),
            "an unbounded walk ends"
        );
        let cells: u32 = score
            .axes
            .iter()
            .map(|a| {
                if a.axis == StressAxis::Lighting {
                    u32::from(a.total)
                } else {
                    u32::from(a.passed) + u32::from(a.failed_at.is_some())
                }
            })
            .sum();
        walk + cells
    }

    /// Fixture-specific preconditions of the quota sweep: the kneed symbol
    /// has knees to bisect; the rescue-only one sits on the Undecodable
    /// boundary — its walk tries EVERY decode class and finds none, yet the
    /// judgment completes (every cell judged, value 0).
    fn assert_sweep_preconditions(
        name: &str,
        luma: &LumaImage,
        detection: &MergedDetection,
        key: &ContentKey,
        reference: &Score,
        bisections: usize,
    ) {
        match name {
            "kneed" => assert!(bisections > 0, "precondition: knees to bisect"),
            "undecodable" => {
                let (calibrated, walk) = calibration_walk(luma, detection, key);
                assert!(matches!(calibrated, Calibrated::Undecodable));
                let every_class = u32::try_from(crate::ladder::DEEP_RUNGS.len()).unwrap() + 1;
                assert_eq!(walk, every_class, "shallow class + every deep rung tried");
                assert_eq!(reference.value, 0, "{:?}", reference.axes);
            }
            _ => {}
        }
    }

    /// The deterministic stand-in for a wall-clock cut, landed on EVERY step
    /// in turn: below the complete unit count there is no score at all; at
    /// or above it the judgment is the unbounded one — value, grade,
    /// weights, axes and hints — and only a knee bisection the quota could
    /// not reach may be absent (bisections run last, so at exactly the
    /// complete count none ran). Three shapes: a pristine symbol, a kneed
    /// one, and a rescue-only decode no stress cell can read.
    #[test]
    fn work_quota_cuts_are_absent_never_partial() {
        let cancel = CancelToken::new();
        for (name, (luma, detection, key)) in [
            ("pristine", pristine_q_example()),
            ("kneed", kneed_example()),
            ("undecodable", rescue_example()),
        ] {
            let mut free = Bound::new(&cancel, None);
            let Judgment::Complete(reference, reference_hints) = judge(
                &luma,
                &detection,
                &key,
                ScoreDepth::Full,
                &[],
                &[],
                &mut free,
            )
            .unwrap() else {
                panic!("{name}: an unbounded judgment completes");
            };
            assert_honest_axes(&reference.axes, ScoreDepth::Full);
            let complete = complete_units(&luma, &detection, &key, &reference);
            let bisections = reference
                .axes
                .iter()
                .filter(|a| a.refined_failed_at.is_some())
                .count();
            let total = complete + u32::try_from(bisections).unwrap();
            assert_eq!(free.spent(), total, "{name}: no hidden step");
            assert_sweep_preconditions(name, &luma, &detection, &key, &reference, bisections);
            for quota in 0..=total + 1 {
                let mut bound = Bound::new(&cancel, None).with_quota(quota);
                let outcome = judge(
                    &luma,
                    &detection,
                    &key,
                    ScoreDepth::Full,
                    &[],
                    &[],
                    &mut bound,
                );
                assert!(bound.spent() <= quota, "{name}: the quota bounds the spend");
                assert_eq!(
                    bound.cut(),
                    quota < total,
                    "{name}: quota {quota} of {total}: the bound reports a refused step"
                );
                let (score, hints) = match outcome.unwrap() {
                    Judgment::Complete(score, hints) => (score, hints),
                    Judgment::Interrupted => {
                        assert!(
                            quota < complete,
                            "{name}: quota {quota} ≥ {complete} completes"
                        );
                        continue;
                    }
                    Judgment::NoAxes => panic!("{name}: every axis is planned"),
                };
                assert!(
                    quota >= complete,
                    "{name}: quota {quota} < {complete} judged"
                );
                assert_honest_axes(&score.axes, ScoreDepth::Full);
                assert_eq!(
                    (score.value, score.grade, score.weights_run),
                    (reference.value, reference.grade, reference.weights_run),
                    "{name}: quota {quota}"
                );
                assert_eq!(hints, reference_hints, "{name}: quota {quota}");
                assert_eq!(
                    (score.structural, score.uec, score.iso15415),
                    (reference.structural, reference.uec, reference.iso15415)
                );
                assert_eq!(score.axes.len(), reference.axes.len());
                for (a, r) in score.axes.iter().zip(&reference.axes) {
                    assert_eq!(
                        (a.axis, a.passed, a.total, &a.failed_at),
                        (r.axis, r.passed, r.total, &r.failed_at),
                        "{name}: quota {quota}"
                    );
                    let refined_ok = if quota >= total {
                        a.refined_failed_at == r.refined_failed_at
                    } else if quota == complete {
                        a.refined_failed_at.is_none()
                    } else {
                        a.refined_failed_at.is_none() || a.refined_failed_at == r.refined_failed_at
                    };
                    assert!(refined_ok, "{name}: quota {quota}: {a:?} vs {r:?}");
                }
            }
        }
    }

    /// The grid rqrr detects in `luma`, read as sampled — unmirrored — with
    /// the format word it decodes that way: the still-masked stream, version,
    /// EC level and mask.
    fn as_sampled(luma: &LumaImage) -> (crate::engine::MaskedStream, u8, EcLevel, u8) {
        let width = luma.width() as usize;
        let data = luma.data();
        let mut prepared =
            rqrr::PreparedImage::prepare_from_greyscale(width, luma.height() as usize, |x, y| {
                data[y * width + x]
            });
        let grid = prepared.detect_grids().remove(0);
        let (meta, raw) = grid.get_raw_data().expect("the sampled format decodes");
        // rqrr's ecc_level is the format word's two-bit field
        let ec = [EcLevel::M, EcLevel::L, EcLevel::H, EcLevel::Q][usize::from(meta.ecc_level)];
        let stream = crate::engine::MaskedStream {
            bits: raw.data[..raw.len.div_ceil(8)].to_vec(),
            bit_len: raw.len,
        };
        (
            stream,
            u8::try_from(meta.version.0).unwrap(),
            ec,
            u8::try_from(meta.mask).unwrap(),
        )
    }

    /// A stream that does not error-correct errors-only under the format it
    /// was read with measures no margin: no `uec` section, no cap, no margin
    /// hint. The case: a mirrored symbol read unmirrored, whose format word
    /// decodes to another EC level and mask while its stream holds the wrong
    /// orientation's bits — the zero margin such a stream read once capped a
    /// clean mirrored code at 40. The S5 rescue's stream, which needed
    /// erasures, keeps its margin.
    #[test]
    fn a_stream_that_does_not_verify_has_no_uec_and_no_cap() {
        use crate::rescue::{Acceptance, Rederived, Unverified};
        let luma = crate::rescue::test_symbols::from_segments_mirrored(
            qrcode::Version::Normal(3),
            qrcode::EcLevel::M,
            |b| b.push_byte_data(b"https://qrc-ai.com/mirrored"),
        );
        let planes = normalize(
            &ImageInput::luma8(luma.data(), luma.width(), luma.height()),
            &Limits::default(),
        )
        .unwrap();
        let (detection, key) = primary_of(&planes);
        let (verified, _) = judged(&planes.luma, &detection, &key, ScoreDepth::Full, &[], &[]);
        let (stream, version, ec, mask) = as_sampled(&planes.luma);
        assert!(
            matches!(
                crate::rescue::rederive(&stream, version, ec, mask, Acceptance::Engine),
                Rederived::Unverified(Unverified::NothingVerifies)
            ),
            "precondition: the as-sampled stream does not error-correct"
        );
        assert_ne!(
            (Some(ec), Some(mask)),
            (detection.ec, detection.mask),
            "precondition: as sampled, the format word reads another EC level and mask"
        );
        let misread = MergedDetection {
            masked_stream: Some(stream),
            version: Some(version),
            ec: Some(ec),
            mask: Some(mask),
            ..detection.clone()
        };
        let (score, hints) = judged(&planes.luma, &misread, &key, ScoreDepth::Full, &[], &[]);
        assert!(score.uec.is_none(), "no margin from it: {:?}", score.uec);
        assert!(
            score
                .iso15415
                .is_some_and(|iso| iso.unused_error_correction.is_none()),
            "{:?}",
            score.iso15415
        );
        assert_eq!(
            (score.value, score.grade),
            (verified.value, verified.grade),
            "no margin, no cap"
        );
        assert!(
            !hints
                .iter()
                .any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
            "{hints:?}"
        );
        // the S5 rescue's stream keeps its errors-only count and its hint
        let (luma, detection, key) = rescue_example();
        let (score, hints) = judged(&luma, &detection, &key, ScoreDepth::Full, &[], &[]);
        let uec = score.uec.expect("the rescued stream keeps its margin");
        assert_eq!(
            (uec.margin, uec.worst_block_errors, uec.worst_block_capacity),
            (0.0, 11, 22)
        );
        assert!(hints.contains(&Hint::LowCorrectionMargin {
            errors: 11,
            capacity: 22
        }));
    }

    /// The unbounded Full scan of an in-memory render.
    fn scan_luma(luma: &LumaImage) -> crate::report::ScanReport {
        let mut config = ScanConfig::full();
        config.budget_ms = None;
        crate::Scanner::builder()
            .profile(crate::ScanProfile::Custom(config))
            .build()
            .scan(ImageInput::luma8(luma.data(), luma.width(), luma.height()))
            .unwrap()
    }

    /// A clean code scores the same mirrored as upright: the score measures
    /// the stream of the orientation the decode verified, with that
    /// orientation's EC level and mask — margin 1.0, no margin hint, no
    /// cap. Twins of a no-ECI URL (a pristine 100) and of an ECI 26 URL; and
    /// a symbol whose format word is EC L, mask 0, which reads as another
    /// word when sampled unmirrored: mirrored, it publishes L / 0 and the
    /// full margin. (Its stress cells may differ from its upright twin's:
    /// mirrored, the centred glare lands on other data modules, and EC L
    /// leaves little to spare.)
    #[test]
    fn a_mirrored_symbol_scores_like_its_upright_twin() {
        use crate::report::UecGrade;
        use crate::rescue::test_symbols::{
            from_segments, from_segments_mirrored, masked_colors, mirror, render,
        };
        let url = |b: &mut qrcode::bits::Bits| b.push_byte_data(b"https://qrc-ai.com/x03");
        let eci26 = |b: &mut qrcode::bits::Bits| {
            b.push_eci_designator(26)?;
            b.push_byte_data(b"https://qrc-ai.com/x02")
        };
        let (v3, m) = (qrcode::Version::Normal(3), qrcode::EcLevel::M);
        let (l0, width) = masked_colors(
            qrcode::Version::Normal(2),
            qrcode::EcLevel::L,
            qrcode::canvas::MaskPattern::Checkerboard,
            |b| b.push_byte_data(b"https://qrc-ai.com/x5"),
        );
        let twins = [
            (
                "no-ECI URL",
                from_segments(v3, m, url),
                from_segments_mirrored(v3, m, url),
            ),
            (
                "ECI 26 URL",
                from_segments(v3, m, eci26),
                from_segments_mirrored(v3, m, eci26),
            ),
            (
                "format word L0",
                render(&l0, width),
                render(&mirror(&l0, width), width),
            ),
        ];
        for (name, upright, mirrored) in twins {
            let (up, down) = (scan_luma(&upright), scan_luma(&mirrored));
            let whole = up.score.expect("the upright twin is judged");
            let score = down.score.expect("the mirrored twin is judged");
            let uec = score.uec.expect("the verified stream measures a margin");
            assert_eq!((uec.margin, uec.grade), (1.0, UecGrade::A), "{name}");
            if name == "format word L0" {
                let meta = &down.detections[0].meta;
                assert_eq!((meta.ec_level, meta.mask), (Some(EcLevel::L), Some(0)));
                assert_eq!(score.uec, whole.uec, "{name}");
                assert!(
                    !down
                        .hints
                        .iter()
                        .any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
                    "{name}: {:?}",
                    down.hints
                );
                continue;
            }
            assert_eq!(
                (score.value, score.grade, &score.axes),
                (whole.value, whole.grade, &whole.axes),
                "{name}"
            );
            assert_eq!(
                (score.uec, score.structural, score.iso15415),
                (whole.uec, whole.structural, whole.iso15415),
                "{name}"
            );
            assert!(
                !down.hints.iter().any(|h| matches!(
                    h,
                    Hint::RaiseErrorCorrection { .. } | Hint::LowCorrectionMargin { .. }
                )),
                "{name}: {:?}",
                down.hints
            );
            assert_eq!(down.hints, up.hints, "{name}");
            if name == "no-ECI URL" {
                assert_eq!((score.value, score.grade), (100, Grade::Excellent));
            }
        }
    }

    /// The margin cap reads the MEASURED margin, published or not: the skip
    /// seam withholds the section and its two hints — never the cap, so
    /// `score_skip_checks` cannot move the value. The published pins
    /// (0.30 → 76 · 0.25 → 70 · 0.0 → 40) hold withheld too.
    #[test]
    fn uec_cap_reads_the_measured_margin_published_or_not() {
        use crate::report::{UecGrade, UecReport};
        let d = detection_with(Some(EcLevel::Q));
        let at = |margin: f32| UecReport {
            margin,
            grade: UecGrade::from_margin(margin),
            worst_block_errors: 12,
            worst_block_capacity: 24,
        };
        for margin in [1.0, 0.5, 0.45, 0.37, 0.30, 0.25, 0.2458, 0.10, 0.0] {
            let (shown, _) = compose(axes_with(&[]), None, Some(at(margin)), true, None, &d);
            let (withheld, hints) =
                compose(axes_with(&[]), None, Some(at(margin)), false, None, &d);
            assert_eq!(
                (withheld.value, withheld.grade, withheld.weights_run),
                (shown.value, shown.grade, shown.weights_run),
                "margin {margin}"
            );
            assert_eq!(withheld.value, uec_margin_cap(margin), "margin {margin}");
            assert!(shown.uec.is_some() && withheld.uec.is_none());
            assert!(
                !hints.iter().any(|h| matches!(
                    h,
                    Hint::RaiseErrorCorrection { .. } | Hint::LowCorrectionMargin { .. }
                )),
                "a withheld margin drives no hint (margin {margin}): {hints:?}"
            );
        }
        let value = |margin: f32| {
            compose(axes_with(&[]), None, Some(at(margin)), false, None, &d)
                .0
                .value
        };
        assert_eq!((value(0.30), value(0.25), value(0.0)), (76, 70, 40));
        // published at the RS limit, both margin hints speak
        let (_, hints) = compose(axes_with(&[]), None, Some(at(0.0)), true, None, &d);
        assert!(
            hints.contains(&Hint::LowCorrectionMargin {
                errors: 12,
                capacity: 24
            }) && hints.contains(&Hint::RaiseErrorCorrection {
                current: EcLevel::Q
            }),
            "{hints:?}"
        );
        // no measurement → no cap, published or not
        for publish in [true, false] {
            let (score, _) = compose(axes_with(&[]), None, None, publish, None, &d);
            assert_eq!(score.value, 100);
        }
    }

    /// Band edges of the cap and the raise-EC gate, for EC Q (the hint can
    /// fire) and EC H (it never can): margin 0.25 caps at exactly 70 (good),
    /// 0.2458 at 69 (acceptable). The `value < 70` gate reads the composite
    /// BEFORE the cap — a withheld margin's 69 drives no hint, while the
    /// published grade (D at 0.25 · F at 0.2458) does.
    #[test]
    fn uec_cap_band_edges_and_the_pre_cap_gate() {
        use crate::report::{UecGrade, UecReport};
        let raised = |hints: &[Hint]| {
            hints
                .iter()
                .any(|h| matches!(h, Hint::RaiseErrorCorrection { .. }))
        };
        let at = |margin: f32| UecReport {
            margin,
            grade: UecGrade::from_margin(margin),
            worst_block_errors: 0,
            worst_block_capacity: 0,
        };
        for ec in [EcLevel::Q, EcLevel::H] {
            let d = detection_with(Some(ec));
            for (margin, cap, grade, band) in [
                (0.25, 70, Grade::Good, UecGrade::D),
                (0.2458, 69, Grade::Acceptable, UecGrade::F),
            ] {
                assert_eq!(at(margin).grade, band);
                for publish in [true, false] {
                    let (score, hints) =
                        compose(axes_with(&[]), None, Some(at(margin)), publish, None, &d);
                    let case = format!("{ec:?} margin {margin} publish {publish}");
                    assert_eq!((score.value, score.grade), (cap, grade), "{case}");
                    assert_eq!(
                        raised(&hints),
                        publish && ec < EcLevel::H,
                        "{case}: {hints:?}"
                    );
                }
            }
        }
        // strict on the PRE-cap value: perspective + rotation 0/5 put the
        // composite at exactly 70 — the withheld 0.2458 margin caps it to 69,
        // which is no reason to raise EC on its own
        let d = detection_with(Some(EcLevel::Q));
        let edge = axes_with(&[
            (StressAxis::Perspective, 0, 5),
            (StressAxis::Rotation, 0, 5),
        ]);
        let (score, hints) = compose(edge, None, Some(at(0.2458)), false, None, &d);
        assert_eq!(score.value, 69);
        assert!(!raised(&hints), "{hints:?}");
        // a pre-cap value below 70 still fires with the margin withheld
        let sunk = axes_with(&[(StressAxis::Blur, 0, 5), (StressAxis::Perspective, 0, 5)]);
        let (score, hints) = compose(sunk, None, Some(at(0.2458)), false, None, &d);
        assert_eq!(score.value, 62);
        assert!(raised(&hints), "{hints:?}");
    }

    /// Dev diagnostic — `cargo nextest run -p qrcode-barcode-scanner --run-ignored
    /// only --no-capture -E 'test(pdf417_stress_cells_repeatability)'`.
    /// Re-decodes the SAME pixels of every resolution cell of the PDF417
    /// fixture in one process, with the scoring filter: a pure function of
    /// the pixels prints 0 or RUNS everywhere. rxing's PDF417 decoder breaks
    /// codeword-confidence ties in `HashMap` iteration order (randomized per
    /// map), so the near-knee 256px cell lands in between; then the same
    /// pixels are walked as a published input. Prints, never asserts a rate.
    #[test]
    #[ignore = "dev diagnostic"]
    fn pdf417_stress_cells_repeatability() {
        const RUNS: usize = 100;
        let path = format!(
            "{}/../../fixtures/symbology/pdf417.png",
            env!("CARGO_MANIFEST_DIR")
        );
        let bytes = std::fs::read(&path).expect("fixture present");
        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
        let (d, key) = primary_of(&planes);
        assert_eq!(d.symbology, crate::report::Symbology::Pdf417);
        let base = transform::downscale_to(&planes.luma, STRESS_BASE_SIDE);
        let probe = CellProbe::calibrate(&base, &key, d.symbology).expect("base decodes");
        let survives = |img: &LumaImage| {
            (0..RUNS)
                .filter(|_| detections_match(&cell_decode(img, d.symbology).detections, &key))
                .count()
        };
        let cancel = CancelToken::new();
        for side in [358u32, 256, 179, 128, 90] {
            let cell = transform::downscale_to(&base, side);
            let judged = (0..RUNS)
                .filter(|_| cell_passes(&cell, &key, probe, &mut Bound::new(&cancel, None)))
                .count();
            println!(
                "{side}px cell ({}x{}): direct {}/{RUNS} · otsu {}/{RUNS} · cell_passes {judged}/{RUNS}",
                cell.width(),
                cell.height(),
                survives(&cell),
                survives(&transform::otsu_threshold(&cell)),
            );
        }
        // the published side: the ladder's verdict over the full frame, then
        // over the 256px pixels handed in as an input of their own
        let walk = |planes: &crate::transform::SourcePlanes| {
            let mut seen = std::collections::BTreeMap::new();
            for _ in 0..RUNS {
                let o =
                    ladder::run(planes, &ScanConfig::full(), &CancelToken::new(), None).unwrap();
                let texts: Vec<_> = o.merged.iter().map(|m| m.text.clone()).collect();
                let stages: Vec<_> = o
                    .trace
                    .stages
                    .iter()
                    .map(|s| (s.stage.clone(), s.transforms_tried, s.detections_found))
                    .collect();
                *seen.entry(format!("{texts:?} via {stages:?}")).or_insert(0) += 1;
            }
            seen
        };
        println!("full frame, {RUNS} ladder walks: {:#?}", walk(&planes));
        let cell = transform::downscale_to(&base, 256);
        let cell_input = ImageInput::luma8(cell.data(), cell.width(), cell.height());
        let cell_planes = normalize(&cell_input, &Limits::default()).unwrap();
        println!(
            "256px pixels as an input, {RUNS} ladder walks: {:#?}",
            walk(&cell_planes)
        );
    }

    // ---- probe schedule ----

    use crate::report::EngineKind as Reader;

    fn qr_class(rung: bool) -> CellProbe {
        CellProbe {
            rung: rung.then_some(crate::ladder::DEEP_RUNGS[0]),
            symbology: crate::report::Symbology::QrCode,
        }
    }

    fn pair(variant: Variant, reader: Reader) -> Pair {
        Pair { variant, reader }
    }

    fn micros(micros: u64) -> std::time::Duration {
        std::time::Duration::from_micros(micros)
    }

    #[test]
    fn a_fresh_schedule_tries_the_binarized_cell_first_under_the_detections_reader() {
        let cancel = CancelToken::new();
        let mut bound = Bound::new(&cancel, None);
        bound.lead_with(&[Reader::Rxing]);
        assert_eq!(
            bound.schedule.order(qr_class(false)),
            vec![
                pair(Variant::Otsu, Reader::Rxing),
                pair(Variant::Otsu, Reader::Rqrr),
                pair(Variant::Plain, Reader::Rxing),
                pair(Variant::Plain, Reader::Rqrr),
            ]
        );
        bound.lead_with(&[Reader::Rxing, Reader::Rqrr]);
        assert_eq!(
            bound.schedule.order(qr_class(true)),
            vec![
                pair(Variant::Otsu, Reader::Rqrr),
                pair(Variant::Otsu, Reader::Rxing),
                pair(Variant::Plain, Reader::Rqrr),
                pair(Variant::Plain, Reader::Rxing),
                pair(Variant::Rung, Reader::Rqrr),
                pair(Variant::Rung, Reader::Rxing),
            ]
        );
        // a symbology only rxing reads has one pair per image, whatever
        // read the detection
        let linear = CellProbe {
            rung: None,
            symbology: crate::report::Symbology::Code128,
        };
        assert_eq!(
            bound.schedule.order(linear),
            vec![
                pair(Variant::Otsu, Reader::Rxing),
                pair(Variant::Plain, Reader::Rxing),
            ]
        );
    }

    #[test]
    fn a_schedule_tries_the_cheapest_expected_pair_first() {
        let class = qr_class(false);
        let otsu_x = pair(Variant::Otsu, Reader::Rxing);
        let otsu_q = pair(Variant::Otsu, Reader::Rqrr);
        let plain_x = pair(Variant::Plain, Reader::Rxing);
        let plain_q = pair(Variant::Plain, Reader::Rqrr);
        let mut schedule = Schedule::new();
        // a read leads; the pairs not yet tried sit one class above the
        // cheapest read, in their first order
        schedule.record(plain_q, true, micros(900));
        assert_eq!(
            schedule.order(class),
            vec![plain_q, otsu_x, otsu_q, plain_x]
        );
        // … so before a read two classes dearer
        schedule.record(otsu_q, true, micros(3_000));
        assert_eq!(
            schedule.order(class),
            vec![plain_q, otsu_x, plain_x, otsu_q]
        );
        // a pass that failed counts two classes dearer: after a read four
        // times slower (the read first when level), before one eight times
        schedule.record(otsu_x, false, micros(900));
        schedule.record(plain_x, true, micros(5_000));
        assert_eq!(
            schedule.order(class),
            vec![plain_q, otsu_q, otsu_x, plain_x]
        );
        // a failure that cost little is tried again before a dear read
        schedule.record(otsu_x, false, micros(100));
        assert_eq!(
            schedule.order(class),
            vec![otsu_x, plain_q, otsu_q, plain_x]
        );
        // and a failure never moves the floor the untried are held to
        assert_eq!(schedule.floor, Some(Schedule::class_of(micros(900))));
    }

    #[test]
    fn a_wall_time_classes_by_its_doublings() {
        for (elapsed, class) in [
            (0, 0),
            (1, 1),
            (2, 2),
            (3, 2),
            (4, 3),
            (1_000, 10),
            (1_023, 10),
            (1_024, 11),
            (1_000_000, 20),
        ] {
            assert_eq!(Schedule::class_of(micros(elapsed)), class, "{elapsed} µs");
        }
        assert_eq!(Schedule::class_of(std::time::Duration::MAX), 84);
    }

    #[test]
    fn every_history_orders_every_pair_of_the_step_exactly_once() {
        let class = qr_class(true);
        let fresh = Schedule::new().order(class);
        let mut slots: Vec<usize> = fresh.iter().map(|pair| pair.slot()).collect();
        slots.sort_unstable();
        assert_eq!(slots, [0, 1, 2, 3, 4, 5], "one slot per pair");
        let outcomes = [
            None,
            Some((true, 5)),
            Some((true, 9_000)),
            Some((false, 5)),
            Some((false, 9_000)),
        ];
        for history in 0..outcomes.len().pow(6) {
            let mut schedule = Schedule::new();
            let mut rest = history;
            for pair in &fresh {
                if let Some((read, elapsed)) = outcomes[rest % outcomes.len()] {
                    schedule.record(*pair, read, micros(elapsed));
                }
                rest /= outcomes.len();
            }
            let mut order = schedule.order(class);
            order.sort_by_key(|pair| pair.slot());
            let mut every = fresh.clone();
            every.sort_by_key(|pair| pair.slot());
            assert_eq!(order, every, "history {history}");
        }
    }

    /// What a probe step answers for, read in full: every image of the
    /// class under every reader of the symbology, every read.
    fn whole_pass_reads(img: &LumaImage, key: &ContentKey, probe: CellProbe) -> bool {
        let reads =
            |img: &LumaImage| detections_match(&cell_decode(img, probe.symbology).detections, key);
        reads(img)
            || reads(&transform::otsu_threshold(img))
            || probe.rung.is_some_and(|rung| reads(&rung.apply(img)))
    }

    #[test]
    fn a_step_passes_exactly_when_the_whole_pass_reads_whatever_the_history() {
        let cancel = CancelToken::new();
        let (base, key, probe) = clean_base_and_probe();
        let mut examples = vec![("clean".to_owned(), base, key, probe)];
        for rel in [
            "artistic/blob-style-monkey-logo.webp",
            "symbology/code128.png",
            "symbology/datamatrix.png",
            "symbology/microqr.png",
        ] {
            let (luma, detection, key) = fixture_example(rel);
            let base = transform::downscale_to(&luma, STRESS_BASE_SIDE);
            let probe = CellProbe::calibrate(&base, &key, detection.symbology)
                .unwrap_or_else(|| panic!("{rel}: the base decodes"));
            examples.push((rel.to_owned(), base, key, probe));
        }
        let (mut passed, mut failed) = (0, 0);
        for (name, base, key, probe) in &examples {
            let mut cells = vec![base.clone()];
            cells.extend([256u32, 128, 72].map(|side| transform::downscale_to(base, side)));
            cells.extend([2.0f32, 6.0].map(|sigma| transform::gaussian_blur(base, sigma)));
            cells.extend([0.3f32, 0.02].map(|gain| transform::contrast_boost(base, gain, 1.0)));
            // one judgment's schedule carried across its cells, under each
            // first reader
            let mut carried = [Reader::Rxing, Reader::Rqrr].map(|first| {
                let mut bound = Bound::new(&cancel, None);
                bound.schedule.first = first;
                bound
            });
            for (index, cell) in cells.iter().enumerate() {
                let expected = whole_pass_reads(cell, key, *probe);
                if expected {
                    passed += 1;
                } else {
                    failed += 1;
                }
                for bound in &mut carried {
                    assert_eq!(
                        cell_passes(cell, key, *probe, bound),
                        expected,
                        "{name} cell {index} carried from {:?}",
                        bound.schedule.first
                    );
                }
                // an adverse history: the pairs in reverse order, every
                // one of them last failed, or last read
                for read in [false, true] {
                    let mut adverse = Bound::new(&cancel, None);
                    let reversed = adverse.schedule.order(*probe).into_iter().rev();
                    for (rank, pair) in reversed.enumerate() {
                        adverse.schedule.record(pair, read, micros(1 << (2 * rank)));
                    }
                    assert_eq!(
                        cell_passes(cell, key, *probe, &mut adverse),
                        expected,
                        "{name} cell {index} after every pair {read}"
                    );
                }
            }
        }
        assert!(
            passed >= 12 && failed >= 8,
            "the witness needs both outcomes: {passed} passed, {failed} failed"
        );
    }
}