shikumi 0.1.222

Shikumi (仕組み) — config discovery, hot-reload, and ArcSwap store for Nix-managed desktop apps
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
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
//! Tiered configuration — **the shikumi configuration prime directive**.
//!
//! Every typed configuration shikumi loads MUST implement
//! [`TieredConfig`]. The bare/discovered/prescribed-default tier
//! model is as load-bearing as shikumi's existing YAML+env+nix
//! discovery — the two compose, they don't replace each other.
//!
//! # Operator workflow (the contract every app exposes)
//!
//! ```text
//! <app> config-show bare          # zero-opinion floor
//! <app> config-show discovered    # bare + runtime auto-detect
//! <app> config-show default       # bare + prescribed defaults + discovered
//! diff <(<app> config-show bare) <(<app> config-show default)
//! ```
//!
//! The same env-var convention applies fleet-wide:
//!
//! ```text
//! MADO_TIER=bare mado             # explicit tier override at launch
//! FROST_TIER=discovered frost     # autodetect-only, no prescribed opinions
//! ```
//!
//! # The runtime path
//!
//! ```rust,ignore
//! use shikumi::{ConfigStore, ConfigTier, TieredConfig};
//!
//! // Resolve the tier from env (defaults to Default if unset/invalid).
//! let tier = ConfigTier::from_env("MADO_TIER");
//! let store = ConfigStore::for_app("mado");
//! let cfg: MadoConfig = store.load_tier(tier)?;
//! ```
//!
//! `load_tier` composes the right tier:
//! * `Bare`       → `T::bare()`
//! * `Discovered` → `T::discovered()`
//! * `Default`    → `T::prescribed_default()` (then overlay the
//!                   operator's YAML if present — the standard
//!                   shikumi YAML+env+nix path layers on top)
//! * `Custom`     → load explicit path, layered on `prescribed_default()`
//!
//! # The model
//!
//! Every operator-facing config in the pleme-io fleet has **four
//! discrete tiers** an operator can ask about:
//!
//! 1. **`bare()`** — zero-opinion floor. Every field at empty / zero /
//!    None / least-surprising variant. The deliberate minimum-viable
//!    config. Documented + diffable; rarely used directly.
//!
//! 2. **`discovered()`** — `bare()` + runtime auto-detect outputs
//!    (display dims, system theme, available fonts, GPU class, etc.).
//!    The "what would this app look like with only detection, no
//!    developer opinions?" answer. Default impl returns `bare()` —
//!    consumers override when they have detect helpers.
//!
//! 3. **`prescribed_default()`** — the developer-prescribed default
//!    layered on top of `discovered()`. "App as the developers
//!    believe it should be used." This is what `Default::default()`
//!    returns for the typed config; ~90% of operators land here on
//!    first launch.
//!
//! 4. **`extend(base)`** — operator-supplied overlay on any prior
//!    tier. Sourced from `~/.config/<app>/<app>.yaml` via the
//!    standard shikumi `ConfigStore` discovery chain.
//!
//! # Diff
//!
//! `diff_against(baseline)` computes a structural diff between two
//! values of the same tiered type — typically `bare()` vs
//! `prescribed_default()` so operators can SEE knob-by-knob what
//! defaults bought them. Default impl uses serde-yaml structural
//! diff; consumers can override for a richer presentation.
//!
//! # Operator CLI contract
//!
//! Every app that consumes a `TieredConfig`-implementing type SHOULD
//! ship a subcommand (`<app> config-show <tier>` + `<app> config-diff
//! <from> <to>`) so the contract is discoverable from the terminal,
//! not just code-reading.
//!
//! # Implementor responsibilities
//!
//! 1. `bare()` enumerates **every field** explicitly (no
//!    `..Default::default()`). The function is the operator's
//!    answer to "what does bare mean for this knob?".
//! 2. `prescribed_default()` typically uses `bare()` + per-field
//!    overrides for the prescribed values, OR a hand-written full
//!    enumeration if it's clearer.
//! 3. Tests pin every field of `bare()` (contract). Adding a new
//!    config field without thinking about its bare value fails the
//!    test.

use crate::discovered::{DiscoveryLayer, compose, deep_merge, deep_merge_attributed};
use crate::source::ConfigSource;
use figment::value::Dict;
use figment::{Figment, providers::Serialized};
use serde::{Serialize, de::DeserializeOwned};
use std::collections::BTreeMap;
use std::env;
use std::path::PathBuf;

// ── ConfigTierKind — variant-tag projection of ConfigTier

/// Typed variant tag of [`ConfigTier`] — `Bare | Discovered | Default
/// | Custom` lifted into a [`crate::ClosedAxis`] primitive without
/// the `Custom` variant's [`std::path::PathBuf`] payload.
///
/// Stands in the same relation to [`ConfigTier`] as
/// [`crate::PartitionFace`] does to [`crate::PartitionOrdinal`]: the
/// variant tag carried as its own [`Copy`] + [`Hash`] typescape
/// primitive, projectable from the full enum through one named
/// accessor ([`ConfigTier::kind`]).
///
/// **Single source of truth for the four operator-facing tier
/// names.** Both [`as_str`][Self::as_str] (rendering) and
/// [`from_str`][Self::from_str] (parsing) route through this enum,
/// so the strings `"bare"`, `"discovered"`, `"default"`, `"custom"`
/// appear at exactly one site — adding a fifth tier (if the model
/// grows) extends the strings in lockstep with the variants instead
/// of touching three duplicated `match` blocks.
///
/// Consumers that only need "which tier did the operator ask for?"
/// without the `Custom` path (telemetry counters, dashboards keyed by
/// tier, structured-log fields) carry a [`ConfigTierKind`] (one byte,
/// [`Copy`]) rather than the full [`ConfigTier`] (variant tag plus a
/// heap-allocated [`std::path::PathBuf`]). Reaches every closed-axis
/// discipline the typescape closes uniformly — [`crate::axis_iter`],
/// [`crate::axis_cardinality`], [`crate::axis_ordinal`],
/// [`crate::axis_at`] — at the trait impl declaration.
#[non_exhaustive]
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    gen_platform::TypedDispatcher,
    gen_platform::Discriminant,
    gen_platform::IsVariant,
    gen_platform::FromStrKind,
)]
#[discriminant(also_display)]
pub enum ConfigTierKind {
    /// Zero-opinion floor.
    Bare,
    /// `bare()` + runtime auto-detect outputs.
    Discovered,
    /// `bare()` + discovered + `prescribed_default()` — the ~90%
    /// case.
    #[allow(clippy::module_name_repetitions)]
    Default,
    /// YAML overlay at a caller-supplied path on top of
    /// `prescribed_default()`.
    Custom,
}

// Fleet-wide dispatcher-catalog registration. TWELFTH consumer
// class adopting gen-platform's typed-dispatcher catamorphism
// (after gen / caixa / wasm-platform / cofre / shigoto / engenho /
// magma / kura / pangea / tatara / hanshi). See
// theory/UNIFIED-COMPUTING-MODEL.md §VI.
gen_platform::register_dispatcher!("shikumi.config-tier-kind", ConfigTierKind);

impl ConfigTierKind {
    /// Every [`ConfigTierKind`] value, in declaration order — the
    /// inherent mirror of [`crate::ClosedAxis::ALL`].
    pub const ALL: &'static [Self] = &[Self::Bare, Self::Discovered, Self::Default, Self::Custom];

    /// Canonical operator-facing lowercase name of the tier kind.
    ///
    /// The single source of truth for the four tier names; both
    /// [`ConfigTier::name`] (rendering) and
    /// [`ConfigTier::from_str_or_default`] / [`ConfigTier::from_env`]
    /// (parsing) route through this method via [`Self::from_str`].
    /// `as_str` round-trips with [`from_str`][Self::from_str] on
    /// every variant — pinned by
    /// [`tests::config_tier_kind_from_str_round_trips_with_as_str`].
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Bare => "bare",
            Self::Discovered => "discovered",
            Self::Default => "default",
            Self::Custom => "custom",
        }
    }

    /// Case-insensitive parse of the four canonical tier-kind
    /// strings. Returns [`None`] for any other input — the caller
    /// decides what to do with unrecognized strings (e.g.
    /// [`ConfigTier::from_str_or_default`] treats them as
    /// path-shaped `Custom(PathBuf)` payloads).
    ///
    /// The trim discipline is the caller's responsibility; this
    /// method matches on the input verbatim after ASCII-lowercasing
    /// so `"Bare"`, `"BARE"`, `"bare"` all parse to [`Self::Bare`].
    /// Empty string returns [`None`] (it's neither a canonical tag
    /// nor a valid path).
    ///
    /// `from_str` returns [`Option`] rather than implementing
    /// [`std::str::FromStr`] (which would force a `Result<_, Err>`
    /// shape and an error-type ceremony for the no-error case where
    /// "not a canonical name" is the only failure mode the caller
    /// cares about).
    ///
    /// Inherent mirror of [`crate::ClosedAxisLabel::from_canonical_str`];
    /// delegates to the trait default so the parse body lives at one
    /// site (the trait default impl in [`crate::cube`]) and the
    /// trait-uniform round-trip law reaches `ConfigTierKind` through
    /// the [`crate::ClosedAxisLabel`] discipline.
    #[allow(clippy::should_implement_trait)]
    #[must_use]
    pub fn from_str(s: &str) -> Option<Self> {
        <Self as crate::ClosedAxisLabel>::from_canonical_str(s)
    }
}

impl crate::ClosedAxis for ConfigTierKind {
    const ALL: &'static [Self] = Self::ALL;
}

impl crate::ClosedAxisLabel for ConfigTierKind {
    fn as_str(self) -> &'static str {
        Self::as_str(self)
    }
}

// ── ConfigTier — operator-facing enum picking which baseline to load

/// Which tier of a `TieredConfig` to materialize at app startup.
///
/// Apps resolve via [`ConfigTier::from_env`] (default convention:
/// `<APP>_TIER` env var) or via an explicit CLI flag. The four
/// variants mirror the `TieredConfig` trait methods:
///
/// * `Bare`       — zero-opinion floor (every field at empty/zero).
/// * `Discovered` — bare + runtime auto-detect outputs.
/// * `Default`    — bare + discovered + prescribed_default (the
///                  ~90% case; what `Default::default()` returns).
/// * `Custom(path)` — load YAML from `path` overlaid on
///                  `prescribed_default()`. Equivalent to the
///                  standard shikumi YAML discovery path.
///
/// The variant-tag projection — "which tier kind did the operator
/// ask for, ignoring any `Custom` path payload?" — is exposed as the
/// typed [`ConfigTierKind`] primitive through [`Self::kind`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigTier {
    Bare,
    Discovered,
    #[allow(clippy::module_name_repetitions)]
    Default,
    Custom(std::path::PathBuf),
}

impl Default for ConfigTier {
    fn default() -> Self {
        Self::Default
    }
}

impl ConfigTier {
    /// Resolve the tier from an env var, falling back to
    /// `ConfigTier::Default` when unset / unparseable.
    ///
    /// Recognized values (case-insensitive):
    ///   * `"bare"` → Bare
    ///   * `"discovered"` → Discovered
    ///   * `"default"` → Default
    ///   * any other non-empty string → Custom(value as path)
    #[must_use]
    pub fn from_env(env_var: &str) -> Self {
        // Missing var → default. Present var goes through the same
        // parse path as the explicit-string entry point, so the two
        // helpers stay in lockstep at one site.
        env::var(env_var)
            .map(|raw| Self::from_str_or_default(&raw))
            .unwrap_or_default()
    }

    /// Resolve from an explicit string (e.g. a CLI flag value).
    /// Same matching rules as [`ConfigTier::from_env`].
    #[must_use]
    pub fn from_str_or_default(s: &str) -> Self {
        // Trim + lowercase once; dispatch through ConfigTierKind so
        // the four canonical tier-name strings live at one site
        // (ConfigTierKind::as_str). The `Custom` kind is encoded
        // here with a string payload — when the operator types the
        // literal word "custom" with no path, it still falls into
        // the path-shaped Custom arm to match prior behavior.
        let normalized = s.trim().to_ascii_lowercase();
        if normalized.is_empty() {
            return Self::default();
        }
        match ConfigTierKind::from_str(&normalized) {
            Some(ConfigTierKind::Bare) => Self::Bare,
            Some(ConfigTierKind::Discovered) => Self::Discovered,
            Some(ConfigTierKind::Default) => Self::Default,
            Some(ConfigTierKind::Custom) | None => {
                Self::Custom(std::path::PathBuf::from(normalized))
            }
        }
    }

    /// Operator-facing tier name (`"bare"` / `"discovered"` /
    /// `"default"` / `"custom"`) — used in logs + telemetry.
    ///
    /// Delegates to [`ConfigTierKind::as_str`] via [`Self::kind`],
    /// keeping the four tier names at one source of truth.
    #[must_use]
    pub fn name(&self) -> &'static str {
        self.kind().as_str()
    }

    /// Typed variant-tag projection — every [`ConfigTier`] value
    /// lands on exactly one [`ConfigTierKind`], with the `Custom`
    /// path payload forgotten.
    ///
    /// The cube-axis analog of [`crate::PartitionOrdinal::face`] for
    /// [`crate::PartitionFace`]: a consumer that only needs "which
    /// tier kind did the operator ask for?" — without the
    /// `Custom(PathBuf)` payload — carries one byte via this
    /// projection rather than re-pattern-matching the enum at every
    /// site. Pinned in lockstep with [`Self::name`] by
    /// [`tests::config_tier_kind_matches_config_tier_name`].
    #[must_use]
    pub const fn kind(&self) -> ConfigTierKind {
        match self {
            Self::Bare => ConfigTierKind::Bare,
            Self::Discovered => ConfigTierKind::Discovered,
            Self::Default => ConfigTierKind::Default,
            Self::Custom(_) => ConfigTierKind::Custom,
        }
    }
}

/// Trait every shikumi-typed config implements to participate in the
/// fleet-wide tier model. See module docs for the full operator
/// contract.
pub trait TieredConfig: Sized + Clone + Serialize + DeserializeOwned {
    /// Tier 0 — the documented floor. Every field at zero-opinion.
    fn bare() -> Self;

    /// Tier 1 — `bare()` overlaid with runtime auto-detect outputs.
    /// Default: returns `bare()` unchanged. Consumers with detect
    /// helpers override.
    fn discovered() -> Self {
        Self::bare()
    }

    /// Tier 2 — `bare()` + curated defaults + `discovered()`. The
    /// prescribed first-launch experience. `Default::default()` on
    /// the implementing type typically delegates here so the standard
    /// idiom (`MyConfig::default()`) Just Works.
    fn prescribed_default() -> Self;

    /// Tier 3 — overlay this config on top of `base`. Default impl
    /// returns `self.clone()` (full replacement). Consumers with
    /// finer-grained per-field merge semantics override.
    fn extend(self, _base: &Self) -> Self {
        self
    }

    /// Materialize `self` from a tier selector — the operator-facing
    /// entry point. Wraps the tier methods + env-var resolution +
    /// optional YAML overlay into one call site every fleet app
    /// uses identically.
    ///
    /// `Bare`/`Discovered`/`Default` resolve to the corresponding
    /// trait method. `Custom(path)` attempts to deserialize YAML
    /// at `path` and overlay it on `prescribed_default()`; falls
    /// back to `prescribed_default()` if the file is missing or
    /// malformed (warns via tracing).
    fn resolve_tier(tier: ConfigTier) -> Self {
        match tier {
            ConfigTier::Bare => Self::bare(),
            ConfigTier::Discovered => Self::discovered(),
            ConfigTier::Default => Self::prescribed_default(),
            ConfigTier::Custom(path) => {
                let base = Self::prescribed_default();
                match std::fs::read_to_string(&path) {
                    Ok(s) => match serde_yaml::from_str::<Self>(&s) {
                        Ok(overlay) => overlay.extend(&base),
                        Err(e) => {
                            tracing::warn!(
                                target: "shikumi::tiered",
                                error = %e,
                                path = %path.display(),
                                "custom tier YAML failed to deserialize — falling back to prescribed_default"
                            );
                            base
                        }
                    },
                    Err(e) => {
                        tracing::warn!(
                            target: "shikumi::tiered",
                            error = %e,
                            path = %path.display(),
                            "custom tier YAML not readable — falling back to prescribed_default"
                        );
                        base
                    }
                }
            }
        }
    }

    /// Convenience: resolve the tier from an env var (default
    /// `<APP>_TIER`) AND materialize the config in one call.
    /// The fleet-wide canonical entry point at app startup.
    fn resolve_from_env(env_var: &str) -> Self {
        Self::resolve_tier(ConfigTier::from_env(env_var))
    }

    /// **The sealed progressive fold — the first-class default resolution.**
    ///
    /// Folds every tier in [`ConfigTier`] precedence order —
    /// `bare() → discovered() → prescribed_default()` — into ONE resolved
    /// config, stamping each effective leaf with the typed [`Provenance`]
    /// of the tier that produced it. This is the entry point the ~90%
    /// "default" path should reach for: unlike
    /// [`Self::resolve_tier`]`(`[`ConfigTier::Default`]`)` — which returns
    /// `prescribed_default()` *alone* and so silently skips discovery — the
    /// fold composes the [`Self::discovered`] auto-detect tier *underneath*
    /// the curated defaults, so a value the environment detected shows
    /// through wherever `prescribed_default()` doesn't override it.
    ///
    /// [`Self::resolve_tier`] / [`Self::resolve_from_env`] are unchanged:
    /// they pick ONE baseline tier (legacy single-tier semantics preserved).
    /// This method is the additive, provenance-carrying FOLD across all
    /// tiers — the (value, provenance) pair is co-constructed here and
    /// returned together, so a progressively-resolved value is never
    /// separable from its provenance.
    #[must_use]
    fn resolve_progressive() -> ProgressiveResolution<Self> {
        Self::resolve_progressive_with(&[])
    }

    /// [`Self::resolve_progressive`] with operator `overlays` (file / env /
    /// runtime override) appended above the three trait tiers.
    ///
    /// Each [`ProgressiveLayer`] carries its own [`Provenance`]; the fold
    /// **stable-sorts the whole layer stack by the const [`ConfigTierKind`]
    /// [`crate::ClosedAxis`] precedence ordinal BEFORE merging**, so no
    /// input ordering can let a lower tier beat a higher one — the
    /// precedence IS the ordering, structurally (a mis-ordered overlay is
    /// re-sorted to its tier's rank; same-tier overlays keep caller order).
    ///
    /// Attribution is **last-changer**: a leaf is credited to the highest
    /// tier that set it to its final value, so a `prescribed_default()`
    /// built on `discovered()` that re-emits a detected value unchanged
    /// leaves that leaf credited to `Discovered`, not `Default`.
    #[must_use]
    fn resolve_progressive_with(overlays: &[ProgressiveLayer]) -> ProgressiveResolution<Self> {
        // 1. Assemble the three trait tiers, each serialized to a dict and
        //    tagged with its computed-defaults provenance.
        let mut layers: Vec<(Provenance, Dict)> = vec![
            (
                Provenance::computed(ConfigTierKind::Bare),
                tiered_to_dict(&Self::bare()),
            ),
            (
                Provenance::computed(ConfigTierKind::Discovered),
                tiered_to_dict(&Self::discovered()),
            ),
            (
                Provenance::computed(ConfigTierKind::Default),
                tiered_to_dict(&Self::prescribed_default()),
            ),
        ];
        layers.extend(
            overlays
                .iter()
                .map(|ov| (ov.provenance().clone(), ov.dict().clone())),
        );
        // 2. Order by the const ConfigTierKind ClosedAxis ordinal. A stable
        //    sort keeps same-tier overlays (e.g. two files) in caller order.
        layers.sort_by_key(|(prov, _)| prov.tier_ordinal());

        // 3. Fold with per-leaf, change-aware provenance attribution — the
        //    ONLY construction path for a progressively-resolved provenance
        //    map, so "a lower tier silently beats a higher one" has no path.
        let mut merged = Dict::new();
        let mut attribution: BTreeMap<Vec<String>, Provenance> = BTreeMap::new();
        for (prov, dict) in layers {
            deep_merge_attributed(&mut merged, dict, &[], &prov, &mut attribution, true);
        }

        // 4. Materialize `Self` from the folded dict. Every input is a valid
        //    `Self` serialization (or an operator overlay merged over one),
        //    so extraction succeeds; the defensive fallback keeps totality.
        let value = Figment::new()
            .merge(Serialized::defaults(&merged))
            .extract::<Self>()
            .unwrap_or_else(|_| Self::prescribed_default());
        ProgressiveResolution {
            value,
            provenance: ProvenanceMap { inner: attribution },
        }
    }

    /// Low-ceremony standard seam for wiring the [`Self::discovered`] tier
    /// from a declarative stack of [`DiscoveryLayer`]s (typically one per
    /// `kanchi` axis-group) instead of hand-rolling a struct literal.
    ///
    /// `bare()` is the floor; the [`compose`]d discovery dict deep-merges
    /// over it per leaf, so an undetectable axis (empty dict) degenerates
    /// cleanly to the bare value — **discovery totality by construction**
    /// (`kanchi`'s `Option<T>` + `_or_fallback` never panics, and an
    /// empty-dict layer is a no-op here). A consumer's whole `discovered()`
    /// collapses to:
    ///
    /// ```ignore
    /// fn discovered() -> Self {
    ///     Self::discovered_from_layers(&[&WindowLayer, &FontLayer])
    /// }
    /// ```
    ///
    /// where each layer's [`DiscoveryLayer::discover`] returns a partial
    /// dict built from `kanchi::detect_*_or_fallback()` — no per-consumer
    /// merge code, and the same [`compose`] machinery that already powers
    /// [`crate::ProviderChain::with_discovery_layers`].
    #[must_use]
    fn discovered_from_layers(layers: &[&dyn DiscoveryLayer]) -> Self {
        let mut merged = tiered_to_dict(&Self::bare());
        deep_merge(&mut merged, compose(layers));
        Figment::new()
            .merge(Serialized::defaults(&merged))
            .extract::<Self>()
            .unwrap_or_else(|_| Self::bare())
    }

    /// Diff `self` against `baseline`. Default: serialize both to
    /// YAML and produce a line-oriented diff.
    fn diff_against(&self, baseline: &Self) -> ConfigDiff {
        let a = serde_yaml::to_string(baseline).unwrap_or_default();
        let b = serde_yaml::to_string(self).unwrap_or_default();
        ConfigDiff::from_yaml_pair(&a, &b)
    }
}

/// Serialize a tiered value into a figment [`Dict`] for the progressive
/// fold. A value that serializes to a non-dict shape (no struct-shaped
/// config does) yields an empty dict — the fold then treats that tier as
/// contributing nothing, never panicking. This is the exact
/// `Serialized::defaults(_)` mechanism [`crate::ProviderChain::with_discovered`]
/// already uses, run in the extract direction.
fn tiered_to_dict<T: Serialize>(value: &T) -> Dict {
    Figment::new()
        .merge(Serialized::defaults(value))
        .extract::<Dict>()
        .unwrap_or_default()
}

// ── Provenance — the typed (tier, source) origin of an effective value ──

/// The typed origin of one effective configuration value: **which
/// [`ConfigTier`] and which [`ConfigSource`]** produced it.
///
/// A [`Provenance`] composes the two provenance primitives shikumi already
/// owns — the [`ConfigTierKind`] closed axis (which conceptual tier) and
/// the [`ConfigSource`] closed enum (which provider kind, with its file
/// path / env prefix payload) — into the pair the progressive fold stamps
/// per leaf. The three computed tiers (`bare` / `discovered` / `prescribed`)
/// carry [`ConfigSource::Defaults`] — the same layer-kind
/// [`crate::ProviderChain::with_discovered`] records for machine-derived
/// layers; operator overlays carry [`ConfigSource::File`] /
/// [`ConfigSource::Env`].
///
/// Precedence — "which tier outranks which" — is read from the const
/// [`ConfigTierKind`] [`crate::ClosedAxis`] declaration order via
/// [`Self::tier_ordinal`]; it is never re-minted here.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Provenance {
    tier: ConfigTierKind,
    source: ConfigSource,
}

impl Provenance {
    /// Construct a provenance from an explicit `(tier, source)` pair.
    #[must_use]
    pub fn new(tier: ConfigTierKind, source: ConfigSource) -> Self {
        Self { tier, source }
    }

    /// A computed-defaults tier (`bare` / `discovered` / `prescribed`):
    /// source is [`ConfigSource::Defaults`] — machine-derived, not
    /// operator-supplied.
    #[must_use]
    pub fn computed(tier: ConfigTierKind) -> Self {
        Self {
            tier,
            source: ConfigSource::Defaults,
        }
    }

    /// An operator FILE overlay — tier [`ConfigTierKind::Custom`], source
    /// [`ConfigSource::File`].
    #[must_use]
    pub fn file(path: impl Into<PathBuf>) -> Self {
        Self {
            tier: ConfigTierKind::Custom,
            source: ConfigSource::File(path.into()),
        }
    }

    /// An operator ENV overlay — tier [`ConfigTierKind::Custom`], source
    /// [`ConfigSource::Env`] with the given prefix.
    #[must_use]
    pub fn env(prefix: impl Into<String>) -> Self {
        Self {
            tier: ConfigTierKind::Custom,
            source: ConfigSource::Env(prefix.into()),
        }
    }

    /// The conceptual tier that produced the value.
    #[must_use]
    pub fn tier(&self) -> ConfigTierKind {
        self.tier
    }

    /// The provider source that produced the value.
    #[must_use]
    pub fn source(&self) -> &ConfigSource {
        &self.source
    }

    /// The const [`crate::ClosedAxis`] precedence ordinal of this
    /// provenance's tier — the single source of truth for "which tier
    /// outranks which" (reused from [`ConfigTierKind`]'s declaration order,
    /// never re-minted). A higher ordinal wins in the progressive fold.
    #[must_use]
    pub fn tier_ordinal(&self) -> usize {
        crate::axis_ordinal(self.tier)
    }
}

impl std::fmt::Display for Provenance {
    /// Typed emission: the tier label ([`ConfigTierKind::as_str`]) plus the
    /// source detail (env prefix / file path) rendered through the typed
    /// [`ConfigSource`] — no free-form string composition.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.tier.as_str())?;
        match &self.source {
            ConfigSource::Defaults => Ok(()),
            ConfigSource::Env(prefix) => write!(f, " (env: {prefix})"),
            ConfigSource::File(path) => write!(f, " (file: {})", path.display()),
        }
    }
}

// ── ProvenanceMap — per-leaf provenance of a resolved config ──

/// Per-leaf provenance for a progressively-resolved config: the
/// [`Provenance`] of the tier that produced every effective leaf.
///
/// Keys are dotted-path components (`Vec<String>`) so keys containing `.`
/// round-trip unambiguously; ordered lexicographically ([`BTreeMap`]
/// iteration) for deterministic dumps. The tier-level peer of
/// [`crate::discovered::LayerAttribution`] (which attributes discovery-layer
/// leaves to a `&'static str` layer name) — both are produced by the one
/// generic [`deep_merge_attributed`] fold, differing only in the
/// attribution codomain.
///
/// Constructed **only** by [`TieredConfig::resolve_progressive`] /
/// [`TieredConfig::resolve_progressive_with`]; seeded from `bare()` (which
/// enumerates every field), so every leaf of the resolved config has a
/// provenance entry by construction.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProvenanceMap {
    inner: BTreeMap<Vec<String>, Provenance>,
}

impl ProvenanceMap {
    /// Number of leaves attributed. Equal to the leaf count of the
    /// resolved config (`bare()` seeds every leaf).
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// True iff no leaves are attributed.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// [`Provenance`] of the effective leaf named by dotted `path`, or
    /// [`None`] if `path` names no leaf in the resolved config.
    #[must_use]
    pub fn provenance_of(&self, path: &[&str]) -> Option<&Provenance> {
        self.provenance_of_owned(&path.iter().map(|&s| s.to_owned()).collect::<Vec<String>>())
    }

    /// Allocation-free variant of [`Self::provenance_of`] for callers that
    /// already carry an owned path.
    #[must_use]
    pub fn provenance_of_owned(&self, path: &[String]) -> Option<&Provenance> {
        self.inner.get(path)
    }

    /// Sorted `(path, provenance)` entries, lexicographic by path.
    ///
    /// Naming the return type at the API boundary (rather than
    /// `impl Iterator<Item = ...> + '_`) exposes the full trait algebra
    /// the underlying [`BTreeMap::iter`][std::collections::BTreeMap::iter]
    /// walker structurally carries — [`DoubleEndedIterator`],
    /// [`ExactSizeIterator`], [`std::iter::FusedIterator`], and
    /// [`Clone`] — and lets consumers hold the handle in a struct field
    /// or return it up through their own API without smuggling an
    /// unnameable [`impl Trait`][impl-trait] across every seam. The
    /// tier-level peer of the concrete-typed
    /// [`crate::discovered::LayerAttribution::iter`] on the discovered
    /// altitude: both walkers project the same
    /// `(&[String], &Attribution)` pair shape, and both spell their
    /// concrete return type at the API boundary.
    ///
    /// [impl-trait]: https://doc.rust-lang.org/reference/types/impl-trait.html
    #[must_use]
    pub fn entries(&self) -> ProvenanceMapEntries<'_> {
        ProvenanceMapEntries {
            inner: self.inner.iter(),
        }
    }

    /// Idiomatic Rust `iter()` alias for [`Self::entries`] — one seam every
    /// std keyed collection (`BTreeMap::iter`, `HashMap::iter`,
    /// `Vec::iter`) surfaces on its `&Self` reference. The tier-level peer
    /// of [`crate::discovered::LayerAttribution::iter`] on the discovered
    /// altitude: both walkers project the same `(&[String], &Attribution)`
    /// pair shape and both name the same concrete iterator type
    /// ([`ProvenanceMapEntries`] here, [`crate::LayerAttributionIter`]
    /// there) at the API boundary. The seam clippy's
    /// `into_iter_without_iter` lint expects to accompany
    /// [`IntoIterator for &ProvenanceMap`].
    #[must_use]
    pub fn iter(&self) -> ProvenanceMapEntries<'_> {
        self.entries()
    }

    /// Per-tier leaf-count histogram — the shikumi cube-native
    /// [`AxisHistogram<ConfigTierKind>`][crate::AxisHistogram] view over
    /// the tier attribution of each resolved leaf. Every leaf's
    /// [`Provenance::tier`] is one observation on the
    /// [`ConfigTierKind`] closed axis, so the histogram bucketizes the
    /// full [`ProvenanceMap`] over the four tier cells (`Bare |
    /// Discovered | Default | Custom`) in one pass.
    ///
    /// One named site closes the "per-tier leaf shape" summary every
    /// operator-facing consumer previously re-derived inline as
    /// `let mut n = [0usize; 4]; for prov in map.entries() { n[prov.1
    /// .tier_ordinal()] += 1; }` at every render/attestation/dashboard
    /// call site. The tier-level peer of
    /// [`crate::discovered::LayerAttribution::leaf_counts_by_layer`] on
    /// the discovered altitude and of
    /// [`ConfigDiff::kind_histogram`] on the diff altitude — both
    /// project a per-cell histogram off the underlying attribution over
    /// their local closed axis, both name the [`crate::AxisHistogram`]
    /// return type at the API boundary.
    ///
    /// # Full [`crate::AxisHistogram`] surface, for free
    ///
    /// Because [`ConfigTierKind`] is a [`crate::ClosedAxis`], the
    /// returned histogram carries the full per-cell / per-axis surface
    /// [`crate::AxisHistogram`] provides at trait-uniform altitude:
    /// [`count`][crate::AxisHistogram::count] /
    /// [`total`][crate::AxisHistogram::total] /
    /// [`distinct_cells`][crate::AxisHistogram::distinct_cells] /
    /// [`is_full_cover`][crate::AxisHistogram::is_full_cover] (per-tier
    /// shape), [`dominant_cell`][crate::AxisHistogram::dominant_cell] /
    /// [`recessive_cell`][crate::AxisHistogram::recessive_cell] /
    /// [`peak_count`][crate::AxisHistogram::peak_count] /
    /// [`trough_count`][crate::AxisHistogram::trough_count]
    /// (argmax/argmin), [`observed`][crate::AxisHistogram::observed] /
    /// [`unobserved`][crate::AxisHistogram::unobserved] (support /
    /// coverage-gap partition),
    /// [`modality_class`][crate::AxisHistogram::modality_class]
    /// (multiplicity classification). Operators asking "which tier
    /// contributed the most surviving leaves?", "was every tier heard
    /// from?", or "is the surviving-leaf distribution tied at the top?"
    /// route through the shikumi-native primitive without a per-consumer
    /// tally.
    ///
    /// # Invariants
    ///
    /// - `tier_histogram().total() == self.len()` — every leaf projects
    ///   to exactly one tier, so summing the histogram cells recovers
    ///   the total leaf count.
    /// - `tier_histogram().count(t) == self.entries().filter(|(_, p)|
    ///   p.tier() == t).count()` — the per-tier bucket equals the
    ///   entries walk restricted to that tier.
    /// - `tier_histogram().observed().collect::<Vec<_>>() ==
    ///   self.contributing_tiers()` — the observed-cells iter over the
    ///   closed axis in declaration order matches
    ///   [`Self::contributing_tiers`] pointwise (both project the same
    ///   distinct-tier set in `ConfigTier` precedence order). This is
    ///   the pin that lets [`Self::contributing_tiers`] route through
    ///   the histogram without a hand-rolled `Vec::contains` + sort.
    /// - `tier_histogram().is_empty() == self.is_empty()` — the empty
    ///   histogram / empty map boundary agrees at both sites.
    ///
    /// # Cost
    ///
    /// `O(n)` — one pass over `self.inner.values()`, one closed-axis
    /// ordinal increment per leaf. The backing store is a fixed
    /// `axis_cardinality::<ConfigTierKind>()`-sized `Vec<usize>` (four
    /// cells today), so there is no per-leaf allocation and the
    /// histogram size is constant in the axis cardinality regardless of
    /// leaf count.
    #[must_use]
    pub fn tier_histogram(&self) -> crate::AxisHistogram<ConfigTierKind> {
        crate::axis_histogram(self.inner.values().map(|prov| prov.tier))
    }

    /// The distinct tiers that produced ≥1 surviving effective leaf, in
    /// [`ConfigTier`] precedence order — the post-fold dual of "which tiers'
    /// opinions survived".
    ///
    /// Routes through [`Self::tier_histogram`]:
    /// [`crate::AxisHistogram::observed`] iterates the histogram's
    /// support (the closed-axis cells with nonzero count) in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`ConfigTier`] precedence order by construction — the closed-
    /// axis discipline provides the sort + dedup automatically, so this
    /// method reads directly off the shikumi cube-native primitive
    /// instead of hand-rolling `Vec::contains` (`O(n·k)`) + explicit
    /// `sort_by_key(axis_ordinal)`. Pinned by
    /// `contributing_tiers_matches_tier_histogram_observed` in this
    /// module's test cohort.
    #[must_use]
    pub fn contributing_tiers(&self) -> Vec<ConfigTierKind> {
        self.tier_histogram().observed().collect()
    }

    /// The distinct tiers that produced **zero** surviving effective
    /// leaves, in [`ConfigTier`] precedence order — the post-fold dual
    /// of [`Self::contributing_tiers`] and the coverage-gap peer of
    /// [`Self::tier_histogram`] on the tier altitude.
    ///
    /// Routes through [`Self::tier_histogram`]:
    /// [`crate::AxisHistogram::unobserved`] iterates the histogram's
    /// **coverage gap** (the closed-axis cells with zero count) in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`ConfigTier`] precedence order by construction — the closed-
    /// axis discipline provides the sort + dedup automatically, so this
    /// method reads directly off the shikumi cube-native primitive
    /// instead of hand-rolling `ConfigTierKind::ALL.iter().filter(|t|
    /// !self.contributing_tiers().contains(t))` (`O(k·k)` in
    /// axis-cardinality, quadratic on the observed side, plus a
    /// `sort_by_key(axis_ordinal)`) at every operator-facing consumer
    /// asking *"which tiers were never heard from on this resolution?"*
    /// — the fleet dashboard flagging "no operator overlay in play", the
    /// attestation manifest recording the tier coverage gap of a
    /// resolved fold, the diagnostic dump reading *"tiers absent:
    /// [Custom]"* to explain why a hot-reload had no runtime signal.
    ///
    /// The observed-cells peer ([`Self::contributing_tiers`]) and the
    /// coverage-gap peer ([`Self::absent_tiers`]) together form the
    /// **support / coverage-gap partition** on the tier altitude — every
    /// cell of [`ConfigTierKind::ALL`] lies in exactly one of the two,
    /// and the two `Vec<ConfigTierKind>` lengths sum to
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality].
    /// The tier-altitude dual of the diff-altitude
    /// [`ConfigDiff::present_kinds`] observed-cells peer (whose absent-
    /// cells peer is the natural next lift on the diff altitude) and of
    /// the chain-altitude [`ConfigSourceChain::present_layer_kinds`] /
    /// [`ConfigSourceChain::present_file_formats`] /
    /// [`ConfigSourceChain::present_env_prefix_kinds`] observed-cells
    /// peers.
    ///
    /// # Invariants
    ///
    /// - `absent_tiers().len() == tier_histogram().unobserved_cells()` —
    ///   both project the same coverage-gap cardinality off the
    ///   histogram.
    /// - `contributing_tiers().len() + absent_tiers().len() ==
    ///   crate::axis_cardinality::<ConfigTierKind>()` — the two peers
    ///   partition the closed axis without remainder (every cell is
    ///   either observed or unobserved, never both).
    /// - `contributing_tiers()` and `absent_tiers()` are disjoint: no
    ///   [`ConfigTierKind`] appears in both.
    /// - `absent_tiers().is_empty() == tier_histogram().is_full_cover()`
    ///   — the coverage-gap is empty iff every tier contributed ≥1 leaf.
    /// - `absent_tiers()` on an empty [`ProvenanceMap`] equals
    ///   [`ConfigTierKind::ALL`] (every tier is absent when no leaf
    ///   contributed) — the empty-map / full-coverage-gap boundary.
    /// - `absent_tiers()` is sorted strictly ascending by
    ///   [`crate::axis_ordinal`] on [`ConfigTierKind`] — dedup + sort
    ///   for free from the closed-axis discipline.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build)
    /// and `k = crate::axis_cardinality::<ConfigTierKind>()` (the
    /// coverage-gap scan). Both are `O(n)` in practice since the tier
    /// axis carries a fixed four-cell cardinality; the returned
    /// `Vec<ConfigTierKind>` is at most four elements long regardless
    /// of leaf count.
    #[must_use]
    pub fn absent_tiers(&self) -> Vec<ConfigTierKind> {
        self.tier_histogram().unobserved().collect()
    }

    /// The **support size** — the number of distinct tiers that produced
    /// ≥1 surviving effective leaf on this resolved fold. Returns `0`
    /// exactly when the map is empty, `1` on a singleton-support fold
    /// (every leaf attributed to one tier), and
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality]
    /// on a full-cover fold (every tier heard from at least once).
    ///
    /// The **scalar-count peer** of [`Self::contributing_tiers`] on the
    /// support-size projection: [`Self::contributing_tiers`] materializes
    /// the observed-cells `Vec<ConfigTierKind>`, this method returns its
    /// cardinality as a `usize` scalar, and both project the same axis
    /// support off the shared [`Self::tier_histogram`] primitive. Every
    /// operator-facing consumer answering *"how many tiers contributed to
    /// this resolved fold?"* — the fleet dashboard summary line *"3 of 4
    /// tiers contributed this rebuild window"* (where 3 is this scalar
    /// and 4 is the axis cardinality), the attestation manifest
    /// recording the tier-support cardinality between two resolved-fold
    /// snapshots, the alerting policy reading *"support size = 1"* to
    /// flag a rebuild window where only one tier surfaced — now route
    /// through this named seam instead of the previous
    /// `contributing_tiers().len()` idiom, which paid for a
    /// `Vec<ConfigTierKind>` allocation of length ≤
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality]
    /// on every call site and walked the histogram's support twice (once
    /// through [`crate::AxisHistogram::observed`] to build the vector,
    /// once through [`Vec::len`] to read its length back). Routes through
    /// [`Self::tier_histogram`]:
    /// [`crate::AxisHistogram::distinct_cells`] reads the nonzero-cell
    /// count in a single pass over the fixed-cardinality counts vector,
    /// so this method returns the size of the support without
    /// materializing the observed-cells `Vec` — one histogram build
    /// followed by one nonzero-count walk instead of the full
    /// `.observed().collect::<Vec<_>>().len()` chain the prior idiom
    /// paid.
    ///
    /// The tier-altitude **support-size** scalar projection — the first
    /// histogram-shape scalar orthogonal to the [`crate::AxisHistogram`]
    /// modal / anti-modal `(dominant, recessive) × (cell, count)` 2×2
    /// grid closed on this altitude by [`Self::dominant_tier`],
    /// [`Self::peak_tier_count`], [`Self::recessive_tier`], and
    /// [`Self::trough_tier_count`]. The support-size scalar is
    /// **orthogonal** to that grid: it references *how many* tiers
    /// contributed, without naming *which* tier is modal or anti-modal
    /// or *how many leaves* landed on either — a shape scalar that
    /// closes over the coverage partition
    /// ([`Self::contributing_tiers`] together with
    /// [`Self::absent_tiers`]) instead of the observation-count
    /// distribution the modal / anti-modal quad projects. Peer to the
    /// [`crate::AxisHistogram::distinct_cells`] primitive one altitude
    /// down, whose per-altitude scalar-count peer at each of the chain
    /// altitude's three sub-axes (layer-kind, file-format,
    /// env-prefix-kind) and at the diff altitude's diff-line kind
    /// altitude is the natural next lift the closed 2×2 grid on those
    /// altitudes compounds against.
    ///
    /// **Empty-map convention** — returns `0` (not `Option<usize>`)
    /// matching the [`Self::len`], [`Self::peak_tier_count`], and
    /// [`Self::trough_tier_count`] empty conventions on the same
    /// altitude, and the [`crate::AxisHistogram::distinct_cells`]
    /// convention one altitude down. The support-size scalar is
    /// well-defined as zero on the empty map: the observed-cells set is
    /// empty, its cardinality is zero, and the coverage-gap sum
    /// [`Self::contributing_tiers_count`] + `absent_tiers().len()` still
    /// balances the axis cardinality (`0 + axis_cardinality::<ConfigTierKind>()
    /// == axis_cardinality::<ConfigTierKind>()`).
    ///
    /// # Invariants
    ///
    /// - `contributing_tiers_count() == tier_histogram().distinct_cells()`
    ///   — both project the same nonzero-cell count off the same
    ///   primitive; the named seam is the cube-native routing of the
    ///   histogram surface. Pinned by
    ///   [`tests::contributing_tiers_count_matches_tier_histogram_distinct_cells_pointwise`].
    /// - `contributing_tiers_count() == contributing_tiers().len()` —
    ///   the scalar-count peer of the observed-cells `Vec` peer; both
    ///   name the same support cardinality without materializing the
    ///   vector. Pinned by
    ///   [`tests::contributing_tiers_count_equals_contributing_tiers_len_pointwise`].
    /// - `contributing_tiers_count() + absent_tiers().len() ==
    ///   crate::axis_cardinality::<ConfigTierKind>()` — the observed /
    ///   coverage-gap partition on the tier axis without remainder, the
    ///   scalar dual of the
    ///   [`tests::absent_tiers_and_contributing_tiers_partition_axis`]
    ///   set-level partition law. Pinned by
    ///   [`tests::contributing_tiers_count_and_absent_tiers_len_partition_axis_cardinality`].
    /// - `contributing_tiers_count() == 0` ⇔ [`Self::is_empty`] is
    ///   `true` — the empty-map / empty-support boundary equivalence
    ///   (every leaf projects to one tier, so a zero-support fold has
    ///   zero leaves and vice versa). Pinned by
    ///   [`tests::contributing_tiers_count_is_zero_iff_map_is_empty`].
    /// - `contributing_tiers_count() >= 1` whenever `!is_empty()` — the
    ///   support of a non-empty map is at least the singleton of the
    ///   first-leaf tier. Pinned by
    ///   [`tests::contributing_tiers_count_is_at_least_one_on_nonempty_map`].
    /// - `contributing_tiers_count() <=
    ///   crate::axis_cardinality::<ConfigTierKind>()` — the support of a
    ///   histogram over a closed axis is bounded above by the axis
    ///   cardinality (the observed-cells set is a subset of
    ///   [`ConfigTierKind::ALL`]). Pinned by
    ///   [`tests::contributing_tiers_count_is_bounded_by_axis_cardinality`].
    /// - `contributing_tiers_count() <= tier_histogram().total()` — the
    ///   support of a histogram is bounded above by the total
    ///   observation count (every distinct cell contributes at least one
    ///   observation to the total). Pinned by
    ///   [`tests::contributing_tiers_count_is_bounded_by_tier_histogram_total`].
    /// - `contributing_tiers_count() ==
    ///   crate::axis_cardinality::<ConfigTierKind>()` ⇔
    ///   `absent_tiers().is_empty()` ⇔
    ///   `tier_histogram().is_full_cover()` — the full-cover boundary
    ///   equivalence on the support-size scalar, the tier-altitude peer
    ///   of the [`crate::AxisHistogram::is_full_cover`] boundary law.
    ///   Pinned by
    ///   [`tests::contributing_tiers_count_equals_axis_cardinality_iff_is_full_cover`].
    /// - `contributing_tiers_count() == 1` ⇔
    ///   `tier_histogram().has_singular_support()` — the singleton-
    ///   support boundary equivalence, the tier-altitude peer of the
    ///   [`crate::AxisHistogram::has_singular_support`] boundary law.
    ///   Pinned by
    ///   [`tests::contributing_tiers_count_is_one_iff_has_singular_support`].
    /// - `contributing_tiers_count() == 1` ⇒ `dominant_tier() ==
    ///   recessive_tier()` — a singleton-support fold has the modal and
    ///   anti-modal cells coincide on the sole observed tier (the
    ///   support-size scalar witnesses the [`crate::AxisHistogram`]
    ///   support-collapse degenerate). Pinned by
    ///   [`tests::contributing_tiers_count_of_one_implies_dominant_equals_recessive`].
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the
    /// nonzero-cell scan). Both are `O(n)` in practice since the tier
    /// axis carries a fixed four-cell cardinality; the returned `usize`
    /// reads one scalar. Halves the wall-cost of the previous
    /// `contributing_tiers().len()` idiom by eliding the
    /// `Vec<ConfigTierKind>` allocation the observed-cells collect paid
    /// on every call site.
    #[must_use]
    pub fn contributing_tiers_count(&self) -> usize {
        self.tier_histogram().distinct_cells()
    }

    /// The **coverage-gap size** — the number of distinct tiers that
    /// produced **zero** surviving effective leaves on this resolved
    /// fold. Returns
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality]
    /// exactly when the map is empty (every tier absent),
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality]
    /// `- 1` on a singleton-support fold (every leaf attributed to one
    /// tier, three tiers absent), and `0` on a full-cover fold (every
    /// tier heard from at least once, no coverage gap).
    ///
    /// The **scalar-count peer** of [`Self::absent_tiers`] on the
    /// coverage-gap projection: [`Self::absent_tiers`] materializes the
    /// unobserved-cells `Vec<ConfigTierKind>`, this method returns its
    /// cardinality as a `usize` scalar, and both project the same axis
    /// coverage-gap off the shared [`Self::tier_histogram`] primitive.
    /// Every operator-facing consumer answering *"how many tiers were
    /// never heard from on this resolved fold?"* — the fleet dashboard
    /// summary line *"1 of 4 tiers absent this rebuild window"* (where 1
    /// is this scalar and 4 is the axis cardinality), the attestation
    /// manifest recording the tier coverage-gap size between two
    /// resolved-fold snapshots, the alerting policy reading *"coverage-
    /// gap size = 3"* to flag a rebuild window where only one tier
    /// surfaced — now route through this named seam instead of the
    /// previous `absent_tiers().len()` idiom, which paid for a
    /// `Vec<ConfigTierKind>` allocation of length ≤
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality]
    /// on every call site and walked the histogram's coverage gap twice
    /// (once through [`crate::AxisHistogram::unobserved`] to build the
    /// vector, once through [`Vec::len`] to read its length back).
    /// Routes through [`Self::tier_histogram`]:
    /// [`crate::AxisHistogram::unobserved_cells`] reads the zero-cell
    /// count in a single pass over the fixed-cardinality counts vector,
    /// so this method returns the size of the coverage gap without
    /// materializing the unobserved-cells `Vec` — one histogram build
    /// followed by one zero-count walk instead of the full
    /// `.unobserved().collect::<Vec<_>>().len()` chain the prior idiom
    /// paid.
    ///
    /// The tier-altitude scalar-count coverage-gap peer. Together with
    /// [`Self::contributing_tiers`], [`Self::absent_tiers`], and
    /// [`Self::contributing_tiers_count`], this seam closes the
    /// `(observed, unobserved) × (cells, count)` 2×2 support / coverage-
    /// gap grid on the tier altitude explicitly — every quadrant of the
    /// grid is now a named seam on the tier altitude:
    ///
    /// | | cells (Vec) | count (usize) |
    /// |---|---|---|
    /// | observed | [`Self::contributing_tiers`] | [`Self::contributing_tiers_count`] |
    /// | unobserved | [`Self::absent_tiers`] | **`absent_tiers_count`** |
    ///
    /// Peer of the diff-altitude [`ConfigDiff::absent_kinds_count`]
    /// scalar-count coverage-gap seam, extending the "coverage-gap-size
    /// across altitudes" projection sideways to the tier altitude. The
    /// natural next lift is the chain altitude's per-sub-axis scalar-
    /// count coverage-gap trio: `ConfigSourceChain::absent_layer_kinds_count`,
    /// `absent_file_formats_count`, `absent_env_prefix_kinds_count`.
    ///
    /// **Empty-map convention** — returns
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality]
    /// (not `Option<usize>`) matching the [`Self::absent_tiers`]
    /// full-axis convention and the
    /// [`crate::AxisHistogram::unobserved_cells`] convention one altitude
    /// down. The coverage-gap-size scalar is well-defined as the axis
    /// cardinality on the empty map: the unobserved-cells set is the
    /// entire axis, its cardinality is
    /// [`crate::axis_cardinality::<ConfigTierKind>()`][crate::axis_cardinality],
    /// and the coverage-partition sum
    /// [`Self::contributing_tiers_count`] + `absent_tiers_count()` still
    /// balances the axis cardinality (`0 +
    /// axis_cardinality::<ConfigTierKind>() ==
    /// axis_cardinality::<ConfigTierKind>()`).
    ///
    /// # Invariants
    ///
    /// - `absent_tiers_count() == tier_histogram().unobserved_cells()` —
    ///   both project the same coverage-gap cardinality off the same
    ///   primitive; the named seam is the cube-native routing of the
    ///   histogram surface. Pinned by
    ///   [`tests::absent_tiers_count_matches_tier_histogram_unobserved_cells_pointwise`].
    /// - `absent_tiers_count() == absent_tiers().len()` — the scalar-
    ///   count peer of the coverage-gap `Vec` peer; both name the same
    ///   coverage-gap cardinality without materialising the vector.
    ///   Pinned by
    ///   [`tests::absent_tiers_count_equals_absent_tiers_len_pointwise`].
    /// - `contributing_tiers_count() + absent_tiers_count() ==
    ///   crate::axis_cardinality::<ConfigTierKind>()` — the observed /
    ///   coverage-gap partition on the tier axis without remainder, the
    ///   fully-scalar dual of
    ///   [`tests::absent_tiers_and_contributing_tiers_partition_axis`]
    ///   (both sides now scalar, no `.len()` on either). Pinned by
    ///   [`tests::contributing_tiers_count_and_absent_tiers_count_partition_axis_cardinality`].
    /// - `absent_tiers_count() ==
    ///   crate::axis_cardinality::<ConfigTierKind>() -
    ///   contributing_tiers_count()` — the algebraic rearrangement of the
    ///   partition, useful for consumers that already hold the support-
    ///   size scalar. Pinned by
    ///   [`tests::absent_tiers_count_equals_axis_cardinality_minus_contributing_tiers_count`].
    /// - `absent_tiers_count() ==
    ///   crate::axis_cardinality::<ConfigTierKind>()` ⇔ [`Self::is_empty`]
    ///   is `true` — the empty-map / full-coverage-gap boundary, the
    ///   scalar peer of `absent_tiers() == ConfigTierKind::ALL`. Pinned
    ///   by [`tests::absent_tiers_count_is_axis_cardinality_iff_map_is_empty`].
    /// - `absent_tiers_count() == 0` ⇔
    ///   `tier_histogram().is_full_cover()` — the full-cover boundary
    ///   equivalence, the tier-altitude scalar-count coverage-gap peer of
    ///   the [`crate::AxisHistogram::is_full_cover`] boundary law and the
    ///   coverage-gap dual of `contributing_tiers_count() ==
    ///   crate::axis_cardinality::<ConfigTierKind>()`. Pinned by
    ///   [`tests::absent_tiers_count_is_zero_iff_is_full_cover`].
    /// - `absent_tiers_count() <=
    ///   crate::axis_cardinality::<ConfigTierKind>()` — the coverage gap
    ///   of a histogram over a closed axis is bounded above by the axis
    ///   cardinality (the unobserved-cells set is a subset of
    ///   [`ConfigTierKind::ALL`]). Pinned by
    ///   [`tests::absent_tiers_count_is_bounded_by_axis_cardinality`].
    /// - `absent_tiers_count() >= 1` whenever
    ///   `!tier_histogram().is_full_cover()` — a non-full-cover fold
    ///   carries at least one absent tier. Pinned by
    ///   [`tests::absent_tiers_count_is_at_least_one_when_not_full_cover`].
    /// - `absent_tiers_count() ==
    ///   crate::axis_cardinality::<ConfigTierKind>() - 1` ⇔
    ///   `tier_histogram().has_singular_support()` — the singleton-
    ///   support boundary in coverage-gap form: when exactly one tier is
    ///   observed, exactly `axis_cardinality - 1` are absent. Pinned by
    ///   [`tests::absent_tiers_count_is_axis_cardinality_minus_one_iff_has_singular_support`].
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the coverage-
    /// gap scan). Both are `O(n)` in practice since the tier axis carries
    /// a fixed four-cell cardinality; the returned `usize` reads one
    /// scalar. Halves the wall-cost of the previous `absent_tiers().len()`
    /// idiom by eliding the `Vec<ConfigTierKind>` allocation the
    /// coverage-gap collect paid on every call site.
    #[must_use]
    pub fn absent_tiers_count(&self) -> usize {
        self.tier_histogram().unobserved_cells()
    }

    /// The tier whose overlay produced the greatest number of surviving
    /// effective leaves on this resolved fold — the modal cell of
    /// [`Self::tier_histogram`] on the tier altitude. `None` exactly
    /// when the map is empty (no leaf contributed).
    ///
    /// Routes through [`Self::tier_histogram`]:
    /// [`crate::AxisHistogram::dominant_cell`] picks the argmax cell in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`ConfigTier`] precedence order by construction — the closed-
    /// axis discipline provides deterministic tie-breaking automatically,
    /// so this method reads directly off the shikumi cube-native
    /// primitive instead of hand-rolling
    /// `hist.iter().filter(|&(_, c)| c > 0).max_by_key(|&(_, c)| c).map(|(v, _)| v)`
    /// — the inline `max_by_key` form silently picks the *last* tied
    /// cell (per [`Iterator::max_by_key`]'s contract), so two consumers
    /// reading "the dominant tier" off the same fold would disagree
    /// under ties unless every one carefully reversed the comparison.
    /// The lift names the scalar at one site with a documented
    /// tie-breaking rule.
    ///
    /// The tier-altitude scalar-mode peer of [`Self::contributing_tiers`]
    /// (the observed-cells vector peer) and [`Self::absent_tiers`] (the
    /// coverage-gap vector peer): the histogram surface now carries the
    /// natural triple of "*which* tiers surfaced" / "*which* tiers
    /// didn't" / "*which single* tier dominated" projections at the tier
    /// altitude, each a named seam over the shared
    /// [`Self::tier_histogram`] primitive. Operator-facing consumers
    /// answering *"which tier dominated this resolved fold?"* — the
    /// fleet dashboard headlining *"Default tier owns 47 of 53 leaves
    /// this rebuild window"*, the attestation manifest recording the
    /// modal tier of a resolved fold, the diagnostic dump reading *"tier
    /// dominance: Discovered"* to explain why a runtime signal is
    /// steering the resolution — now route through this named seam
    /// instead of a per-consumer `max_by_key` walk.
    ///
    /// **Tie-breaking is deterministic by precedence order.** When
    /// multiple tiers share the maximum leaf count, the tier earliest
    /// in [`ConfigTierKind::ALL`] wins — the same [`ConfigTier`]
    /// precedence order [`Self::contributing_tiers`] and
    /// [`Self::absent_tiers`] walk. A uniform-cover fold (each tier
    /// producing the same nonzero leaf count) therefore reports
    /// `Some(ConfigTierKind::Bare)` — the first cell in declaration
    /// order — pointwise stable regardless of the insertion order of
    /// individual leaves into the underlying [`BTreeMap`].
    ///
    /// # Invariants
    ///
    /// - `dominant_tier().is_some() == !is_empty()` — the dominant tier
    ///   is defined exactly when the fold has at least one leaf. Peer
    ///   to the [`Self::is_empty`] boundary [`Self::contributing_tiers`]
    ///   and [`Self::absent_tiers`] both witness.
    /// - `dominant_tier() == tier_histogram().dominant_cell()` — both
    ///   project the same modal cell off the same primitive; the named
    ///   seam is the cube-native routing of the histogram surface.
    /// - When `Some(t)`, `t` is a member of `contributing_tiers()` —
    ///   the modal cell is by definition observed. Pinned by
    ///   `dominant_tier_is_member_of_contributing_tiers`.
    /// - When `Some(t)`, `t` is **not** a member of `absent_tiers()` —
    ///   the observed / coverage-gap partition is disjoint. Pinned by
    ///   `dominant_tier_is_not_member_of_absent_tiers`.
    /// - `tier_histogram().count(dominant_tier().unwrap()) ==
    ///   tier_histogram().peak_count()` whenever the map is non-empty —
    ///   the modal cell carries the peak observation count. Peer to
    ///   the (`dominant_cell`, `peak_count`) modal pair invariant on
    ///   [`crate::AxisHistogram`].
    /// - `dominant_tier()` on a uniform per-tier fold (one leaf per
    ///   tier) equals `Some(ConfigTierKind::Bare)` — declaration-order
    ///   tie-breaking on the four-cell axis picks the first cell.
    /// - `dominant_tier()` on an empty [`ProvenanceMap`] equals `None`
    ///   — the empty-map / empty-histogram boundary.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build)
    /// and `k = crate::axis_cardinality::<ConfigTierKind>()` (the
    /// argmax scan). Both are `O(n)` in practice since the tier axis
    /// carries a fixed four-cell cardinality; the returned
    /// `Option<ConfigTierKind>` reads one cell.
    #[must_use]
    pub fn dominant_tier(&self) -> Option<ConfigTierKind> {
        self.tier_histogram().dominant_cell()
    }

    /// The **peak leaf count** — the number of surviving effective leaves
    /// contributed by the dominant tier on this resolved fold. Returns `0`
    /// exactly when the map is empty; otherwise returns the count carried
    /// by [`Self::dominant_tier`] (pointwise equal to it).
    ///
    /// The **scalar peer** of [`Self::dominant_tier`] on the count side —
    /// the natural typed primitive for diagnostic dumps, dashboards, and
    /// attestation manifests asking *"how many leaves did the dominant
    /// tier collect?"*: the fleet dashboard headline *"Default owns 47 of
    /// 53 leaves"* (where 47 is this scalar), the attestation manifest
    /// recording the peak-tier observation count between two resolved-fold
    /// snapshots, the alerting policy reading *"peak tier count = 12"* to
    /// gate a rebuild window on the modal tier's density. Before this
    /// lift, every such consumer re-derived the projection inline as
    /// `map.tier_histogram().peak_count()` or (equivalently but at twice
    /// the cost) `map.dominant_tier().map_or(0, |t| map.tier_histogram()
    /// .count(t))` — which walked the histogram *twice* (once to argmax,
    /// once to read the count back through
    /// [`crate::AxisHistogram::count`] indexing) and re-built the
    /// histogram at every site. Routes through
    /// [`Self::tier_histogram`]: [`crate::AxisHistogram::peak_count`]
    /// reads a single pass over the fixed-cardinality counts vector.
    ///
    /// The tier-altitude scalar-count peer of [`Self::dominant_tier`] (the
    /// modal-cell scalar peer of [`Self::tier_histogram`]) — the histogram
    /// surface now carries the fused `(dominant_tier, peak_tier_count)`
    /// modal pair on the tier altitude, matching the
    /// ([`crate::AxisHistogram::dominant_cell`],
    /// [`crate::AxisHistogram::peak_count`]) pair on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down. Consumers
    /// answering *"which tier dominated and by how much?"* now read a
    /// single `(dominant_tier(), peak_tier_count())` pair — one method
    /// each, both routing through the same primitive — instead of
    /// re-deriving the count off the modal cell.
    ///
    /// **Empty-map convention** — returns `0` (not `Option<usize>`)
    /// matching the [`Self::len`] empty convention and the
    /// [`crate::AxisHistogram::peak_count`] convention one altitude down;
    /// the scalar `(len, peak_tier_count)` pair reads uniformly `(0, 0)`
    /// on the empty map. The dual-form [`Self::dominant_tier`] carries
    /// `Option<ConfigTierKind>` because the *tier* is undefined when no
    /// leaf contributes; the *count* is well-defined as zero. The
    /// asymmetry is intentional: every scalar projection reads zero on
    /// empty; every cell projection reads `None`.
    ///
    /// # Invariants
    ///
    /// - `peak_tier_count() == 0` ⇔ [`Self::is_empty`] is `true` — peer
    ///   to the empty-map boundary [`Self::dominant_tier`] and
    ///   [`Self::recessive_tier`] both witness on the cell side.
    /// - `peak_tier_count() == tier_histogram().peak_count()` — both
    ///   project the same scalar off the same primitive; the named seam
    ///   is the cube-native routing of the histogram surface.
    /// - `peak_tier_count() == dominant_tier().map_or(0, |t|
    ///   tier_histogram().count(t))` — the count projection of the
    ///   `(dominant_tier, peak_tier_count)` modal pair equals
    ///   [`Self::peak_tier_count`] pointwise on every map (empty:
    ///   `None.map_or(0, …) == 0 == peak_tier_count`; non-empty:
    ///   `Some(t).map_or(0, |t| count(t)) == peak_tier_count`, since
    ///   `count(dominant_tier()) == peak_count()`).
    /// - `peak_tier_count() <= len()` always: the peak is bounded above
    ///   by the total leaf count (every tier contributes at most every
    ///   leaf, and the others contribute zero). Equality holds when
    ///   `contributing_tiers().len() <= 1`.
    /// - `peak_tier_count() == len()` iff `contributing_tiers().len()
    ///   <= 1`: a single observed tier carries every leaf, so the peak
    ///   equals the total. Zero observed tiers (empty) reads 0 == 0;
    ///   one observed tier reads N == N; two or more reads peak < total
    ///   strictly.
    /// - `peak_tier_count() >= 1` whenever `!is_empty()` — a non-empty
    ///   map always has at least one leaf on the dominant tier.
    /// - `peak_tier_count()` on a uniform per-tier fold (one leaf per
    ///   tier) equals `1` — every observed tier collects one leaf,
    ///   dominant included.
    /// - `peak_tier_count()` on a singleton-support fold (every leaf on
    ///   the same tier) equals `len()` — the dominant tier collects
    ///   every leaf. Singleton-support pin.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the argmax
    /// scan). Both are `O(n)` in practice since the tier axis carries a
    /// fixed four-cell cardinality; the returned `usize` reads one
    /// scalar. Halves the cost of the previous
    /// `dominant_tier().map_or(0, |t| tier_histogram().count(t))` idiom
    /// (which walked the histogram twice — once to argmax, once to read
    /// the count back).
    #[must_use]
    pub fn peak_tier_count(&self) -> usize {
        self.tier_histogram().peak_count()
    }

    /// The **trough leaf count** — the number of surviving effective leaves
    /// contributed by the rarest-observed (recessive) tier on this resolved
    /// fold. Returns `0` exactly when the map is empty; otherwise returns
    /// the count carried by [`Self::recessive_tier`] (pointwise equal to
    /// it, and always `>= 1` by the histogram-support definition).
    ///
    /// The **scalar peer** of [`Self::recessive_tier`] on the count side —
    /// the natural typed primitive for diagnostic dumps, dashboards, and
    /// attestation manifests asking *"how many leaves did the runt tier
    /// collect?"*: the fleet dashboard headline *"runt tier: Custom owns
    /// 1 of 47 leaves"* (where 1 is this scalar), the attestation manifest
    /// recording the trough-tier observation count between two
    /// resolved-fold snapshots, the alerting policy reading *"trough tier
    /// count = 1"* to flag a rebuild window where a tier barely
    /// contributed. Before this lift, every such consumer re-derived the
    /// projection inline as `map.tier_histogram().trough_count()` or
    /// (equivalently but at twice the cost) `map.recessive_tier().map_or(0,
    /// |t| map.tier_histogram().count(t))` — which walked the histogram
    /// *twice* (once to argmin over the support, once to read the count
    /// back through [`crate::AxisHistogram::count`] indexing) and re-built
    /// the histogram at every site. Routes through [`Self::tier_histogram`]:
    /// [`crate::AxisHistogram::trough_count`] reads a single pass over the
    /// fixed-cardinality counts vector (filtering the zero-count cells out
    /// of the argmin search).
    ///
    /// The tier-altitude scalar-count peer of [`Self::recessive_tier`] (the
    /// anti-modal-cell scalar peer of [`Self::tier_histogram`]) — the
    /// histogram surface now carries the fused `(recessive_tier,
    /// trough_tier_count)` anti-modal pair on the tier altitude, matching
    /// the ([`crate::AxisHistogram::recessive_cell`],
    /// [`crate::AxisHistogram::trough_count`]) pair on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down. Consumers
    /// answering *"which tier is the runt and by how much?"* now read a
    /// single `(recessive_tier(), trough_tier_count())` pair — one method
    /// each, both routing through the same primitive — instead of
    /// re-deriving the count off the anti-modal cell.
    ///
    /// The 2×2 `(dominant, recessive) × (cell, count)` scalar grid on the
    /// tier altitude closes with this lift: the four seams
    /// ([`Self::dominant_tier`], [`Self::peak_tier_count`],
    /// [`Self::recessive_tier`], [`Self::trough_tier_count`]) now each
    /// route through the same [`Self::tier_histogram`] primitive at one
    /// pass per projection, matching the `(dominant_cell, peak_count,
    /// recessive_cell, trough_count)` quad on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down.
    ///
    /// **Empty-map convention** — returns `0` (not `Option<usize>`)
    /// matching the [`Self::len`] empty convention, the
    /// [`Self::peak_tier_count`] empty convention on the same altitude,
    /// and the [`crate::AxisHistogram::trough_count`] convention one
    /// altitude down; the scalar `(peak_tier_count, trough_tier_count)`
    /// pair reads uniformly `(0, 0)` on the empty map. The dual-form
    /// [`Self::recessive_tier`] carries `Option<ConfigTierKind>` because
    /// the *tier* is undefined when no leaf contributes; the *count* is
    /// well-defined as zero. The asymmetry is intentional: every scalar
    /// projection reads zero on empty; every cell projection reads `None`.
    ///
    /// # Invariants
    ///
    /// - `trough_tier_count() == 0` ⇔ [`Self::is_empty`] is `true` — peer
    ///   to the empty-map boundary [`Self::dominant_tier`],
    ///   [`Self::recessive_tier`], and [`Self::peak_tier_count`] all
    ///   witness on the cell / count sides.
    /// - `trough_tier_count() == tier_histogram().trough_count()` — both
    ///   project the same scalar off the same primitive; the named seam
    ///   is the cube-native routing of the histogram surface.
    /// - `trough_tier_count() == recessive_tier().map_or(0, |t|
    ///   tier_histogram().count(t))` — the count projection of the
    ///   `(recessive_tier, trough_tier_count)` anti-modal pair equals
    ///   [`Self::trough_tier_count`] pointwise on every map (empty:
    ///   `None.map_or(0, …) == 0 == trough_tier_count`; non-empty:
    ///   `Some(t).map_or(0, |t| count(t)) == trough_tier_count`, since
    ///   `count(recessive_tier()) == trough_count()`).
    /// - `trough_tier_count() <= peak_tier_count()` always: the trough is
    ///   bounded above by the peak (lifted from the trait-uniform
    ///   `trough_count() <= peak_count()` law on
    ///   [`crate::AxisHistogram`]). The empty-map case reads `0 <= 0`;
    ///   the non-empty case reads the trough-of-support bounded above by
    ///   the peak-of-support.
    /// - `trough_tier_count() == peak_tier_count()` iff
    ///   `contributing_tiers().len() <= 1`: on the empty map both are 0;
    ///   on a singleton-support fold both equal `len()`; on two or more
    ///   observed tiers with distinct counts the trough is strictly below
    ///   the peak.
    /// - `trough_tier_count() >= 1` whenever `!is_empty()` — the argmin
    ///   is taken over the histogram's *support* (nonzero cells), so the
    ///   trough of a non-empty histogram is always at least one.
    /// - `trough_tier_count()` on a uniform per-tier fold (one leaf per
    ///   tier) equals `1` — every observed tier collects one leaf; the
    ///   trough coincides with the peak on the uniform-cover degenerate
    ///   (the singleton-modality analogue on the count side).
    /// - `trough_tier_count()` on a singleton-support fold (every leaf on
    ///   the same tier) equals `len()` — the sole observed tier is both
    ///   the modal and anti-modal cell, so trough == peak == len.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the argmin
    /// scan over the support). Both are `O(n)` in practice since the
    /// tier axis carries a fixed four-cell cardinality; the returned
    /// `usize` reads one scalar. Halves the cost of the previous
    /// `recessive_tier().map_or(0, |t| tier_histogram().count(t))` idiom
    /// (which walked the histogram twice — once to argmin, once to read
    /// the count back).
    #[must_use]
    pub fn trough_tier_count(&self) -> usize {
        self.tier_histogram().trough_count()
    }

    /// The tier whose overlay produced the fewest (but still ≥1) surviving
    /// effective leaves on this resolved fold — the anti-modal (rarest
    /// observed) cell of [`Self::tier_histogram`] on the tier altitude.
    /// `None` exactly when the map is empty (no leaf contributed).
    ///
    /// Routes through [`Self::tier_histogram`]:
    /// [`crate::AxisHistogram::recessive_cell`] picks the argmin cell over
    /// the histogram's *support* (the nonzero cells) in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`ConfigTier`] precedence order by construction — the closed-axis
    /// discipline provides deterministic tie-breaking automatically, so
    /// this method reads directly off the shikumi cube-native primitive
    /// instead of hand-rolling
    /// `hist.iter().filter(|&(_, c)| c > 0).min_by_key(|&(_, c)| c).map(|(v, _)| v)`
    /// — the inline `min_by_key` form silently picks the *first* tied cell
    /// (per [`Iterator::min_by_key`]'s contract, which reverses
    /// [`Iterator::max_by_key`]'s "last on ties" behavior), so an
    /// open-coded argmin and the open-coded argmax on the dominant side
    /// would disagree on which tied cell to pick. The pair of lifts
    /// ([`Self::dominant_tier`] and [`Self::recessive_tier`]) pins one
    /// consistent tie-breaking rule across both projections.
    ///
    /// **Zero-count tiers are excluded from the search.** The argmin is
    /// taken over the histogram's support, not over the full axis. Tiers
    /// that contributed no surviving leaf are trivially the minimum over
    /// the full axis and would shadow the rarest *observed* tier;
    /// excluding them surfaces the rarest tier some leaf actually
    /// credited — the question the fleet dashboard, attestation manifest,
    /// and diagnostic dump ask when they surface *"the runt tier this
    /// resolved fold saw"*. This matches [`Self::dominant_tier`]'s
    /// symmetry on the maximum side: both projections operate over the
    /// nonzero support, so the empty-map convention is identical (both
    /// return `None`) and the singleton-support case is identical (both
    /// return the sole observed tier).
    ///
    /// The tier-altitude anti-modal peer of [`Self::dominant_tier`] (the
    /// modal-cell scalar peer of the same [`Self::tier_histogram`]
    /// primitive) — the histogram surface now carries the fused
    /// (dominant, recessive) cell pair on the tier altitude, matching
    /// the ([`crate::AxisHistogram::dominant_cell`],
    /// [`crate::AxisHistogram::recessive_cell`]) pair on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down. Operator-facing
    /// consumers answering *"which tier is the runt of this resolved fold?"*
    /// — the fleet dashboard headlining *"runt tier: Custom, 1 of 47 leaves
    /// this rebuild window"*, the attestation manifest recording the
    /// anti-modal tier between two resolved fold snapshots, the alerting
    /// policy reading *"runt tier: Discovered"* to flag a rebuild window
    /// where the kanchi discovery layer contributed almost nothing — now
    /// route through this named seam instead of a per-consumer `min_by_key`
    /// walk.
    ///
    /// **Tie-breaking is deterministic by precedence order.** When
    /// multiple observed tiers share the minimum leaf count, the tier
    /// earliest in [`ConfigTierKind::ALL`] wins — the same
    /// [`ConfigTier`] precedence order [`Self::contributing_tiers`],
    /// [`Self::absent_tiers`], and [`Self::dominant_tier`] walk. A
    /// uniform-cover fold (each tier producing the same nonzero leaf
    /// count) therefore reports `Some(ConfigTierKind::Bare)` — the first
    /// cell in declaration order — pointwise identical to
    /// [`Self::dominant_tier`] on the same input (the singleton-modality
    /// degenerate where the modal and anti-modal cells coincide).
    ///
    /// # Invariants
    ///
    /// - `recessive_tier().is_some() == !is_empty()` — the recessive tier
    ///   is defined exactly when the fold has at least one leaf. Peer to
    ///   the [`Self::is_empty`] boundary [`Self::dominant_tier`],
    ///   [`Self::contributing_tiers`], and [`Self::absent_tiers`] all
    ///   witness.
    /// - `recessive_tier().is_some() == dominant_tier().is_some()` — both
    ///   projections are defined on the same support (`!is_empty()`),
    ///   lifted from the [`crate::AxisHistogram::recessive_cell`] /
    ///   [`crate::AxisHistogram::dominant_cell`] presence-bound law.
    /// - `recessive_tier() == tier_histogram().recessive_cell()` — both
    ///   project the same anti-modal cell off the same primitive; the
    ///   named seam is the cube-native routing of the histogram surface.
    /// - When `Some(t)`, `t` is a member of `contributing_tiers()` —
    ///   the anti-modal cell is by definition observed. Pinned by
    ///   `recessive_tier_is_member_of_contributing_tiers`.
    /// - When `Some(t)`, `t` is **not** a member of `absent_tiers()` —
    ///   the observed / coverage-gap partition is disjoint, and the
    ///   argmin over the *support* never coincides with a zero-count
    ///   cell. Pinned by `recessive_tier_is_not_member_of_absent_tiers`.
    /// - `tier_histogram().count(recessive_tier().unwrap()) ==
    ///   tier_histogram().trough_count()` whenever the map is non-empty —
    ///   the anti-modal cell carries the trough-of-support observation
    ///   count. Peer to the (`dominant_cell`, `peak_count`) modal pair
    ///   invariant on [`crate::AxisHistogram`].
    /// - `tier_histogram().count(recessive_tier().unwrap()) <=
    ///   tier_histogram().count(dominant_tier().unwrap())` whenever the
    ///   map is non-empty — the trough-of-support count is bounded above
    ///   by the peak count. Lifted from the trait-uniform
    ///   `count(recessive_cell) <= count(dominant_cell)` law on
    ///   [`crate::AxisHistogram`].
    /// - `recessive_tier() == dominant_tier()` whenever
    ///   `contributing_tiers().len() == 1` — a single observed tier is
    ///   both the modal and the anti-modal cell (the singleton-support
    ///   degenerate).
    /// - `recessive_tier()` on a uniform per-tier fold (one leaf per
    ///   tier) equals `Some(ConfigTierKind::Bare)` — declaration-order
    ///   tie-breaking on the four-cell axis picks the first cell,
    ///   pointwise identical to `dominant_tier()` on the same input.
    /// - `recessive_tier()` on an empty [`ProvenanceMap`] equals `None`
    ///   — the empty-map / empty-histogram boundary.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the argmin
    /// scan). Both are `O(n)` in practice since the tier axis carries a
    /// fixed four-cell cardinality; the returned `Option<ConfigTierKind>`
    /// reads one cell.
    #[must_use]
    pub fn recessive_tier(&self) -> Option<ConfigTierKind> {
        self.tier_histogram().recessive_cell()
    }

    /// The **scalar dispersion** of the leaf-count distribution across the
    /// observed tiers on this resolved fold — the tier-altitude peer of
    /// [`ConfigDiff::kind_spread`] on the diff altitude. Returns `0`
    /// exactly on every empty map, every singleton-support fold (only one
    /// observed tier, trivially balanced), and every uniform per-tier
    /// fold (each observed tier contributing the same nonzero leaf count,
    /// dominant included).
    ///
    /// The **scalar dispersion peer** of the fused
    /// `(peak_tier_count, trough_tier_count)` modal-count pair on the
    /// tier altitude — the natural typed primitive for fleet dashboards,
    /// attestation manifests, and alerting policies asking *"how
    /// unevenly distributed are the leaves across the observed
    /// tiers?"*: the fleet dashboard headline *"tier skew 46: Default
    /// owns 47 of 53 leaves, Custom 1 of 53"* (where 46 is this
    /// scalar), the attestation manifest recording the tier spread
    /// between two resolved-fold snapshots, the alerting policy reading
    /// *"tier spread = 46"* to flag a rebuild window where one tier
    /// dwarfed the others. Before this lift, every such consumer
    /// re-derived the projection inline as `map.peak_tier_count() -
    /// map.trough_tier_count()` — two method calls plus a subtraction
    /// at every site, each site having to reason independently about
    /// the structural non-negativity of the difference (`peak_count >=
    /// trough_count` holds on every histogram but not on the inline
    /// subtraction surface, so an unwitnessed refactor swapping the
    /// operands would silently underflow). Routes through
    /// [`crate::AxisHistogram::spread`] one altitude down — the
    /// underflow-safe named seam whose docs pin the monotonicity
    /// invariant explicitly.
    ///
    /// The tier-altitude scalar-dispersion peer in the "spread across
    /// altitudes" projection seeded on the diff altitude by
    /// [`ConfigDiff::kind_spread`]. The pattern is the same at every
    /// altitude: fuse the (`peak_count`, `trough_count`) modal-count
    /// pair into a single dispersion scalar named at the surface,
    /// routed through the shared [`crate::AxisHistogram::spread`]
    /// primitive one altitude down. The chain altitude's three
    /// sub-axes (`layer_kind_spread`, `file_format_spread`,
    /// `env_prefix_kind_spread` over the corresponding chain
    /// histograms) are the natural next sideways lifts.
    ///
    /// **Empty-map convention** — returns `0`, matching the
    /// [`crate::AxisHistogram::spread`] empty convention one altitude
    /// down and the [`Self::peak_tier_count`] / [`Self::trough_tier_count`]
    /// empty conventions on the same altitude. The scalar-count triple
    /// `(peak_tier_count, trough_tier_count, tier_spread)` reads
    /// uniformly `(0, 0, 0)` on the empty map — every observation
    /// scalar reads zero on empty; every cell projection
    /// ([`Self::dominant_tier`], [`Self::recessive_tier`]) reads
    /// `None`. The asymmetry is intentional and matches the
    /// [`crate::AxisHistogram`] convention one altitude down.
    ///
    /// **Structural-skew predicate.** `tier_spread() == 0` is the
    /// typed *balanced-tier-counts* predicate at the tier altitude —
    /// every observed [`ConfigTierKind`] contributed the same number of
    /// leaves. Pointwise equivalent to `peak_tier_count() ==
    /// trough_tier_count()` on the scalar-count pair and to
    /// `dominant_tier() == recessive_tier()` on the modal-cell pair
    /// whenever the map is non-empty (both branches reduce to
    /// `Some(first) == Some(first)` on singleton-support and uniform
    /// folds, and to `false` on skewed folds). Together with
    /// [`Self::is_empty`] and the full-cover predicate on
    /// [`Self::tier_histogram`], the tier-altitude scalar surface now
    /// carries the natural boundary triple *"did any tier contribute?"* /
    /// *"did every tier fire?"* / *"did the tiers fire equally?"* — each
    /// a single method call.
    ///
    /// # Invariants
    ///
    /// - `tier_spread() == tier_histogram().spread()` — both project the
    ///   same scalar off the same primitive; the named seam is the
    ///   cube-native routing of the histogram surface.
    /// - `tier_spread() == peak_tier_count() - trough_tier_count()` —
    ///   the fused-pair identity of the scalar-dispersion peer. The
    ///   subtraction is underflow-safe because `peak_tier_count() >=
    ///   trough_tier_count()` holds structurally on every map (lifted
    ///   from the trait-uniform `peak_count() >= trough_count()` law
    ///   on [`crate::AxisHistogram`]).
    /// - `tier_spread() == 0` on the empty map — the vacuous
    ///   uniformity boundary, matching the
    ///   [`crate::AxisHistogram::spread`] empty convention one altitude
    ///   down. The `(peak_tier_count, trough_tier_count, tier_spread)`
    ///   triple reads `(0, 0, 0)` uniformly on the empty map.
    /// - `tier_spread() == 0` whenever `contributing_tiers().len() <= 1`
    ///   — singleton-support folds are trivially balanced (the one
    ///   observed tier's count is both the peak and the trough). Also
    ///   holds on every uniform per-tier fold (each observed tier
    ///   contributing the same nonzero count).
    /// - `tier_spread() <= peak_tier_count()` always — the trough is
    ///   non-negative, so the subtraction is bounded above by the
    ///   minuend. Equality holds iff the trough is zero — i.e. on the
    ///   empty map. Lifted from the trait-uniform
    ///   `spread() <= peak_count()` law on
    ///   [`crate::AxisHistogram`].
    /// - `tier_spread() <= self.len()` always — composition of
    ///   `tier_spread() <= peak_tier_count()` (this method) with
    ///   `peak_tier_count() <= self.len()` (documented on
    ///   [`Self::peak_tier_count`]).
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the peak + trough
    /// scan). Both are `O(n)` in practice since the tier axis carries a
    /// fixed four-cell cardinality; the returned `usize` reads one scalar.
    /// Halves the cost of the previous inline `map.peak_tier_count() -
    /// map.trough_tier_count()` idiom (which walked the counts vector
    /// twice — once for the max, once for the min-over-support — where
    /// [`crate::AxisHistogram::spread`] can fuse both into a single walk
    /// with a running-max/min pair).
    #[must_use]
    pub fn tier_spread(&self) -> usize {
        self.tier_histogram().spread()
    }

    /// The **balanced-tier-counts boolean predicate** at the tier altitude —
    /// `true` exactly when every observed [`ConfigTierKind`] contributed the
    /// same number of leaves. The typed boolean peer of `tier_spread() == 0`
    /// on the scalar-dispersion surface, lifting the same structural-skew
    /// boundary from the scalar surface to a named predicate at the tier
    /// altitude. Routes through
    /// [`crate::AxisHistogram::is_uniform_count`] one altitude down: the
    /// single-pass scan over the fixed-cardinality counts vector that
    /// short-circuits on the first pair of distinct nonzero cells, tighter
    /// than the two-scan [`Self::peak_tier_count`] /
    /// [`Self::trough_tier_count`] fusion the scalar-spread form pays for.
    ///
    /// The **balanced-tier-counts peer** of the fused
    /// `(peak_tier_count, trough_tier_count, tier_spread)` dispersion
    /// triple on the tier altitude — the natural typed boolean primitive
    /// for fleet dashboards, attestation manifests, and alerting policies
    /// asking *"did every observed tier fire equally?"*: the fleet
    /// dashboard headline *"balanced fold: every observed tier owns the
    /// same number of leaves"*, the attestation manifest gate *"rebuild
    /// window balanced across tiers"*, the alerting policy predicate
    /// *"fold balanced"*. Before this lift, every such consumer
    /// re-derived the predicate inline as `map.tier_spread() == 0` (the
    /// scalar-spread form, which routes through a subtraction whose
    /// underflow safety relies on the structural `peak >= trough`
    /// invariant on [`Self::tier_spread`]), or as
    /// `map.peak_tier_count() == map.trough_tier_count()` (the scalar-
    /// pair form, which pays for two count walks and equates two
    /// `usize`s without saying structurally *what* is being equated), or
    /// as `map.dominant_tier() == map.recessive_tier()` (the modal-pair
    /// form, which peers through `Option<ConfigTierKind>` equality across
    /// two argmax/argmin walks). The three forms drifted in subtle ways
    /// at every consumer site. This lift names the balanced-tier-counts
    /// predicate directly at the tier-altitude surface with a single-pass
    /// short-circuiting scan — the typed boolean every operator-facing
    /// "is this fold balanced?" check reads off as a single method call.
    ///
    /// The tier-altitude balanced-predicate peer that climbs the "balanced
    /// across altitudes" projection from the diff altitude seeded by
    /// [`ConfigDiff::kinds_balanced`]. The pattern is the same at every
    /// altitude: fuse the (`peak_count`, `trough_count`, `spread`) scalar
    /// triple's balanced-boundary into a single boolean predicate named at
    /// the surface, routed through the shared
    /// [`crate::AxisHistogram::is_uniform_count`] primitive one altitude
    /// down. Parallels the "spread across altitudes" projection climbed to
    /// the same altitude by [`Self::tier_spread`] and seeded on the diff
    /// altitude by [`ConfigDiff::kind_spread`]. The chain altitude's three
    /// sub-axes (`layer_kinds_balanced`, `file_formats_balanced`,
    /// `env_prefix_kinds_balanced` over the corresponding chain
    /// histograms) are the natural next sideways lifts.
    ///
    /// **Empty-map convention** — returns `true` vacuously: the empty map
    /// has no observed cells, so the universal "every observed cell
    /// carries the same count" reads `true` over the empty support.
    /// Matches [`crate::AxisHistogram::is_uniform_count`]'s empty
    /// convention one altitude down and `tier_spread() == 0` on the empty
    /// case (peak == trough == 0). The empty map is therefore on the
    /// `true` side of the balanced-tier-counts boundary — the vacuous-
    /// uniformity witness.
    ///
    /// **Singleton-support convention** — returns `true` on every map
    /// whose observed support is a single [`ConfigTierKind`] (trivially
    /// balanced: the one observed tier's count is both the peak and the
    /// trough). Includes every fold in which one tier owns every leaf.
    ///
    /// **Uniform per-tier convention** — returns `true` on every uniform
    /// per-tier fold (each observed tier contributing the same nonzero
    /// count), including the k-tier-observed-once-each shape and the
    /// uniform full-cover shape over all four [`ConfigTierKind`] cells.
    ///
    /// # Invariants
    ///
    /// - `tiers_balanced() == tier_histogram().is_uniform_count()` — both
    ///   project the same predicate off the same primitive; the named
    ///   seam is the cube-native routing of the histogram surface.
    /// - `tiers_balanced() == (tier_spread() == 0)` always — the defining
    ///   equivalence on the scalar-spread surface at the tier altitude.
    /// - `tiers_balanced() == (peak_tier_count() == trough_tier_count())`
    ///   always — the structural form on the underlying scalar pair.
    /// - `tiers_balanced() == (dominant_tier() == recessive_tier())`
    ///   always — the modal-pair form; both branches agree on the empty
    ///   map (`None == None`), on every singleton-support fold
    ///   (`Some(t) == Some(t)`), on every uniform per-tier fold
    ///   (`Some(first_tier) == Some(first_tier)` after declaration-order
    ///   tie-break), and on every skewed fold (both sides read `false`).
    /// - `self.is_empty() ⇒ tiers_balanced()` — vacuous uniformity on
    ///   the empty map. Contrapositively, `!tiers_balanced() ⇒
    ///   !self.is_empty()` (a skewed fold has at least two distinct
    ///   positive counts, so the map is non-empty).
    /// - `contributing_tiers().len() <= 1 ⇒ tiers_balanced()` — every
    ///   fold with support size 0 or 1 is trivially balanced.
    ///   Contrapositively, `!tiers_balanced() ⇒
    ///   contributing_tiers().len() >= 2` (a skewed fold observes at
    ///   least two distinct tiers with differing counts).
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the uniform-
    /// count scan). Both are `O(n)` in practice since the tier axis
    /// carries a fixed four-cell cardinality; the returned `bool` reads
    /// one predicate. The scan short-circuits on the first pair of
    /// distinct nonzero cells (bounded at two nonzero cells visited),
    /// strictly tighter than the two-full-scan `peak_tier_count()` /
    /// `trough_tier_count()` fusion the scalar-spread form pays for on
    /// skewed inputs.
    #[must_use]
    pub fn tiers_balanced(&self) -> bool {
        self.tier_histogram().is_uniform_count()
    }

    /// `true` exactly when every [`ConfigTierKind`] cell was observed at
    /// least once on this resolved fold — the **full-cover-tier-counts
    /// predicate** on the tier altitude. Routes through
    /// [`crate::AxisHistogram::is_full_cover`] one altitude down: the
    /// single-pass scan over the fixed-cardinality counts vector that
    /// short-circuits on the first zero cell, tighter than any of the
    /// four coverage-gap equality forms one seam over.
    ///
    /// The **full-cover-tier-counts peer** of the fused
    /// `(contributing_tiers, absent_tiers, contributing_tiers_count,
    /// absent_tiers_count)` support / coverage-gap 2×2 grid on the tier
    /// altitude — the natural typed boolean primitive for fleet
    /// dashboards, attestation manifests, and alerting policies asking
    /// *"did every tier fire at least once on this resolved fold?"*: the
    /// fleet dashboard headline *"full-cover fold: every tier fired at
    /// least once"*, the attestation manifest gate *"rebuild window
    /// full-cover across tiers"*, the alerting policy predicate *"fold
    /// full-cover"*. Before this lift, every such consumer re-derived the
    /// predicate inline as one of four pointwise-equivalent forms:
    /// `map.absent_tiers().is_empty()` (the coverage-gap-`Vec` form,
    /// which allocates a `Vec<ConfigTierKind>` and reads its emptiness),
    /// `map.absent_tiers_count() == 0` (the coverage-gap-scalar form,
    /// which pays for a full-axis scan and equates a `usize` to zero
    /// without saying structurally *what* is being equated),
    /// `map.contributing_tiers_count() ==
    /// crate::axis_cardinality::<ConfigTierKind>()` (the support-scalar
    /// form, which pays for the support scan and pulls in the
    /// [`crate::axis_cardinality`] turbofish at every call site), and
    /// `map.contributing_tiers().len() ==
    /// crate::axis_cardinality::<ConfigTierKind>()` (the support-`Vec`
    /// form, which allocates a `Vec<ConfigTierKind>` and reads its
    /// length back). The four forms drifted in subtle ways at every
    /// consumer site (allocation vs. scalar, turbofish vs. name-only,
    /// coverage-gap side vs. support side). This lift names the
    /// full-cover-tier-counts predicate directly at the tier-altitude
    /// surface with a single-pass short-circuiting scan — the typed
    /// boolean every operator-facing "did every tier fire on this
    /// fold?" check reads off as a single method call.
    ///
    /// The tier-altitude full-cover-predicate peer that **climbs the
    /// "full-cover across altitudes" projection** from the diff altitude
    /// seeded by [`ConfigDiff::kinds_full_cover`]. The pattern is the
    /// same at every altitude: fuse the (`present_cells`, `absent_cells`,
    /// `present_cells_count`, `absent_cells_count`) support / coverage-
    /// gap 2×2 grid's full-cover-boundary into a single boolean
    /// predicate named at the surface, routed through the shared
    /// [`crate::AxisHistogram::is_full_cover`] primitive one altitude
    /// down. Parallels the "balanced across altitudes" projection climbed
    /// to the same altitude by [`Self::tiers_balanced`] and seeded on
    /// the diff altitude by [`ConfigDiff::kinds_balanced`]. The chain
    /// altitude's three sub-axes (`layer_kinds_full_cover`,
    /// `file_formats_full_cover`, `env_prefix_kinds_full_cover` over the
    /// corresponding chain histograms) are the natural next sideways
    /// lifts.
    ///
    /// **Empty-map convention** — returns `false` on the empty map: the
    /// empty map has no observed cells, so the coverage gap equals every
    /// cell of [`ConfigTierKind::ALL`] — the full-cover predicate fails.
    /// Matches [`crate::AxisHistogram::is_full_cover`]'s empty-histogram
    /// convention one altitude down on the non-zero-cardinality
    /// [`ConfigTierKind`] axis (four cells: `Bare`, `Discovered`,
    /// `Default`, `Custom`). The empty map is therefore on the `false`
    /// side of the full-cover-tier-counts boundary — the dual of the
    /// vacuous-uniformity witness on [`Self::tiers_balanced`], which
    /// reads `true` on the empty map.
    ///
    /// **Singleton-support convention** — returns `false` on every fold
    /// whose observed support is a single [`ConfigTierKind`]: one
    /// observed cell out of four leaves at least three cells in the
    /// coverage gap, so the full-cover predicate fails. Every fold with
    /// all leaves attributed to only-`Bare`, only-`Discovered`,
    /// only-`Default`, or only-`Custom` is a witness.
    ///
    /// **Uniform four-tier cover convention** — returns `true` on every
    /// fold where each of the four [`ConfigTierKind`] cells was observed
    /// at least once (regardless of per-tier count). Includes the
    /// k-tier-observed-once-each shape (one leaf per tier) and every
    /// skewed four-tier cover.
    ///
    /// # Invariants
    ///
    /// - `tiers_full_cover() == tier_histogram().is_full_cover()` — both
    ///   project the same predicate off the same primitive; the named
    ///   seam is the cube-native routing of the histogram surface.
    /// - `tiers_full_cover() == absent_tiers().is_empty()` always —
    ///   the defining equivalence on the coverage-gap-`Vec` surface at
    ///   the tier altitude.
    /// - `tiers_full_cover() == (absent_tiers_count() == 0)` always —
    ///   the defining equivalence on the coverage-gap-scalar surface,
    ///   without allocating the `Vec<ConfigTierKind>`.
    /// - `tiers_full_cover() == (contributing_tiers_count() ==
    ///   crate::axis_cardinality::<ConfigTierKind>())` always — the
    ///   support-scalar form, the dual-side surfacing of the same
    ///   boolean across the (observed, unobserved) partition.
    /// - `tiers_full_cover() == (contributing_tiers().len() ==
    ///   crate::axis_cardinality::<ConfigTierKind>())` always — the
    ///   support-`Vec` form, without allocating twice through
    ///   [`Vec::len`].
    /// - `tiers_full_cover() ⇒ !self.is_empty()` — a full-cover fold
    ///   observes at least one leaf per [`ConfigTierKind`], so the map
    ///   is non-empty. Contrapositively, `self.is_empty() ⇒
    ///   !tiers_full_cover()` (the empty-map / full-coverage-gap
    ///   boundary).
    /// - `tiers_full_cover() ⇒ contributing_tiers().len() ==
    ///   crate::axis_cardinality::<ConfigTierKind>()` — a full-cover
    ///   fold observes every tier, so the support size equals the axis
    ///   cardinality. Contrapositively, `contributing_tiers().len() <
    ///   crate::axis_cardinality::<ConfigTierKind>() ⇒
    ///   !tiers_full_cover()`.
    /// - `tiers_full_cover() ⇒ self.len() >=
    ///   crate::axis_cardinality::<ConfigTierKind>()` — a full-cover
    ///   fold observes at least one leaf per tier, so the leaf count is
    ///   bounded below by the axis cardinality.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.inner.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<ConfigTierKind>()` (the full-cover
    /// scan). Both are `O(n)` in practice since the tier axis carries a
    /// fixed four-cell cardinality; the returned `bool` reads one
    /// predicate. The scan short-circuits on the first zero cell
    /// (bounded at one zero cell visited on a non-full-cover fold),
    /// strictly tighter than the four coverage-gap equality forms — no
    /// `Vec<ConfigTierKind>` allocation, no [`crate::axis_cardinality`]
    /// turbofish, no scalar equality against a magic axis-cardinality
    /// constant.
    #[must_use]
    pub fn tiers_full_cover(&self) -> bool {
        self.tier_histogram().is_full_cover()
    }
}

/// Zero-allocation `(&[String], &Provenance)` stream over the sorted
/// leaves of a [`ProvenanceMap`], lexicographic by path.
///
/// The concrete return type of [`ProvenanceMap::entries`]. Naming the
/// handle at the API boundary (rather than
/// `impl Iterator<Item = (&[String], &Provenance)> + '_`) exposes the
/// full trait algebra the underlying [`BTreeMap`]-backed walker
/// structurally carries — [`DoubleEndedIterator`],
/// [`ExactSizeIterator`], [`std::iter::FusedIterator`], and
/// [`Clone`] — and lets consumers hold the handle in a struct field or
/// return it up through their own API without smuggling an unnameable
/// [`impl Trait`][impl-trait] across every seam. Closes the last
/// `impl Iterator`-returning surface on `tiered.rs`, matching the
/// concrete-return invariant every free-function iter dual on
/// `discovered.rs` (whole-layer: [`crate::ContributorNamesIter`],
/// [`crate::LayerNamesIter`], [`crate::SilentLayerNamesIter`],
/// [`crate::NonemptyLayerDictsIter`]; point-restricted:
/// [`crate::ContributorsAtIter`], [`crate::SilencedAtIter`]) already
/// carries.
///
/// [impl-trait]: https://doc.rust-lang.org/reference/types/impl-trait.html
///
/// # Trait algebra
///
/// Impls [`Iterator`] + [`DoubleEndedIterator`] +
/// [`ExactSizeIterator`] + [`std::iter::FusedIterator`] + [`Clone`] +
/// [`Debug`][std::fmt::Debug]. The underlying
/// [`std::collections::btree_map::Iter`] carries the same trait algebra
/// on any `(Vec<String>, Provenance)` map, so this newtype forwards
/// each impl seam-for-seam with the projection
/// `(&Vec<String>, &Provenance) → (&[String], &Provenance)` (via
/// [`Vec::as_slice`]) applied at every `.next()` / `.next_back()`
/// pull. The projection preserves element count, so
/// [`ExactSizeIterator`] survives at the type level — the tier-level
/// peer of [`crate::discovered::LayerAttribution::iter`]'s
/// [`crate::LayerAttributionIter`] concrete handle.
///
/// # Field access
///
/// The struct fields are private — the public surface is the
/// `Iterator` / `DoubleEndedIterator` / `ExactSizeIterator` /
/// `FusedIterator` / `Clone` trait impls plus the
/// [`Debug`][std::fmt::Debug] derive.
#[derive(Clone, Debug)]
pub struct ProvenanceMapEntries<'a> {
    inner: std::collections::btree_map::Iter<'a, Vec<String>, Provenance>,
}

impl<'a> Iterator for ProvenanceMapEntries<'a> {
    type Item = (&'a [String], &'a Provenance);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, v)| (k.as_slice(), v))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl DoubleEndedIterator for ProvenanceMapEntries<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(k, v)| (k.as_slice(), v))
    }
}

impl ExactSizeIterator for ProvenanceMapEntries<'_> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl std::iter::FusedIterator for ProvenanceMapEntries<'_> {}

/// `for entry in &map` (by-reference) iterates the same borrowed
/// `(&[String], &Provenance)` stream as [`ProvenanceMap::entries`], in
/// the same lex order. The idiomatic dual of the inherent
/// [`ProvenanceMap::entries`] getter — one seam every std collection
/// with an `iter()` method surfaces on its `&Self` reference
/// (`&Vec<T>`, `&BTreeMap<K, V>`, `&HashMap<K, V>`, `&[T]`) — closing
/// the shared idiom on the tiered algebra so consumers reach for the
/// `for`-loop form directly instead of the explicit `.entries()` call.
/// Zero-allocation: forwards to [`ProvenanceMap::entries`], which is
/// `O(1)` per element. Tier-level peer of the discovered-altitude
/// [`IntoIterator for &crate::discovered::LayerAttribution`] impl.
impl<'a> IntoIterator for &'a ProvenanceMap {
    type Item = (&'a [String], &'a Provenance);
    type IntoIter = ProvenanceMapEntries<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries()
    }
}

/// Consuming iterator over the owned `(Vec<String>, Provenance)` pairs
/// of a [`ProvenanceMap`], yielded in lex order on the path.
///
/// The concrete return type of
/// [`<ProvenanceMap as IntoIterator>::into_iter`][IntoIterator] and the
/// canonical Rust idiom-peer of
/// [`std::collections::btree_map::IntoIter`] /
/// [`std::vec::IntoIter`] — every stdlib keyed collection exposes a
/// named consuming iterator alongside the named borrowing iterator on
/// its `&Self` reference. The owned-ownership peer of the borrowing
/// [`ProvenanceMapEntries`] on the ownership boundary: where the
/// borrowing iterator yields `(&'a [String], &'a Provenance)` and lets
/// `self` outlive the walk, this consuming iterator yields
/// `(Vec<String>, Provenance)` and takes `self` with it — the natural
/// choice when the caller wants to move each owned key and provenance
/// elsewhere (e.g. `.into_iter().collect::<BTreeMap<_, _>>()`, an owned
/// `Vec<(Vec<String>, Provenance)>` audit dump, per-leaf
/// `FnMut(Vec<String>, Provenance)` visitor callbacks) without paying
/// an `.entries().map(|(p, prov)| (p.to_vec(), prov.clone()))`
/// intermediate clone per key.
///
/// The **consume-side dual** of the collect-side [`FromIterator`] impl:
/// `map.into_iter().collect::<ProvenanceMap>()` roundtrips through the
/// owned `(Vec<String>, Provenance)` shape and equals the source
/// verbatim, closing the ownership pair every std keyed collection
/// carries alongside its `FromIterator` (a `BTreeMap<K, V>` with
/// `IntoIterator` yielding `(K, V)` alongside its `FromIterator<(K,
/// V)>`, a `Vec<T>` with `IntoIterator` yielding `T` alongside its
/// `FromIterator<T>`). The tier-level peer of the discovered-altitude
/// [`crate::discovered::LayerAttributionIntoIter`] on the same
/// ownership boundary.
///
/// # Trait algebra
///
/// Impls [`Iterator`] + [`DoubleEndedIterator`] +
/// [`ExactSizeIterator`] + [`std::iter::FusedIterator`] +
/// [`Debug`][std::fmt::Debug]. [`Clone`] is *not* carried — the
/// underlying [`std::collections::btree_map::IntoIter`] consumes the
/// source [`BTreeMap`] and is not [`Clone`]-able. This matches the same
/// consuming/borrowing asymmetry
/// [`crate::discovered::LayerAttributionIntoIter`] carries on the
/// discovered algebra and every stdlib consuming iterator carries
/// against its borrowing peer.
///
/// # Field access
///
/// The struct field is private — the public surface is the
/// `Iterator` / `DoubleEndedIterator` / `ExactSizeIterator` /
/// `FusedIterator` trait impls plus the [`Debug`][std::fmt::Debug]
/// derive.
#[derive(Debug)]
pub struct ProvenanceMapIntoIter {
    inner: std::collections::btree_map::IntoIter<Vec<String>, Provenance>,
}

impl Iterator for ProvenanceMapIntoIter {
    type Item = (Vec<String>, Provenance);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }

    fn count(self) -> usize {
        self.inner.count()
    }

    fn last(mut self) -> Option<Self::Item> {
        // Override the default forward-walking `.last()` — the
        // DoubleEnded impl on the underlying `BTreeMap::IntoIter` finds
        // the trailing entry in `O(log n)` instead of draining the
        // whole iterator. Matches the same specialization
        // `LayerAttributionIntoIter::last` carries on the discovered
        // algebra's consuming surface.
        self.inner.next_back()
    }
}

impl DoubleEndedIterator for ProvenanceMapIntoIter {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back()
    }
}

impl ExactSizeIterator for ProvenanceMapIntoIter {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl std::iter::FusedIterator for ProvenanceMapIntoIter {}

/// `for entry in map` (by-value) iterates the owned
/// `(Vec<String>, Provenance)` stream in the same lex order on the path
/// as [`ProvenanceMap::entries`] / [`IntoIterator for
/// &ProvenanceMap`][IntoIterator] — the consume-side dual of the
/// borrow-side [`IntoIterator for &ProvenanceMap`] impl above. One seam
/// every std keyed collection surfaces on its owned handle (`Vec<T>`,
/// `BTreeMap<K, V>`, `HashMap<K, V>`, `BTreeSet<T>`), closing the
/// ownership pair on the tiered algebra so consumers reach for the
/// by-value `for`-loop form directly (`for (path, prov) in map { … }`)
/// or `.into_iter().collect::<T>()` chains that move each owned path
/// and provenance into a caller-owned collection without the
/// `.entries().map(|(p, prov)| (p.to_vec(), prov.clone()))`
/// intermediate clone the borrowing form requires.
///
/// # Roundtrip with `FromIterator`
///
/// The pair with [`FromIterator for ProvenanceMap`] roundtrips
/// through the owned `(Vec<String>, Provenance)` shape:
///
/// ```text
/// let map: ProvenanceMap = ...;
/// let round: ProvenanceMap = map.clone().into_iter().collect();
/// assert_eq!(map, round);
/// ```
///
/// # Length
///
/// The returned [`ProvenanceMapIntoIter`] is [`ExactSizeIterator`],
/// so `.len()` returns [`ProvenanceMap::len`] verbatim in `O(1)` —
/// the trait-level parity of the borrowing [`ProvenanceMapEntries`] on
/// the consume-side surface.
impl IntoIterator for ProvenanceMap {
    type Item = (Vec<String>, Provenance);
    type IntoIter = ProvenanceMapIntoIter;

    fn into_iter(self) -> Self::IntoIter {
        ProvenanceMapIntoIter {
            inner: self.inner.into_iter(),
        }
    }
}

/// Build a [`ProvenanceMap`] from a stream of `(path, provenance)`
/// pairs — the construction-side dual of [`IntoIterator for
/// &ProvenanceMap`] on the reading side. Every path–provenance pair
/// emitted by the source iterator becomes one attributed leaf; the
/// composed [`ProvenanceMap`] stores them in lex order on the owned
/// `Vec<String>` key, the same order [`ProvenanceMap::entries`] emits.
///
/// One seam every std keyed collection with an [`IntoIterator for
/// &Self`] getter surfaces on the ownership boundary
/// ([`FromIterator`][std::iter::FromIterator] on
/// [`BTreeMap`][std::collections::BTreeMap] /
/// [`HashMap`][std::collections::HashMap], on [`Vec`], on
/// [`BTreeSet`][std::collections::BTreeSet]) — closing the shared
/// idiom on the tiered algebra so consumers reach for the `.collect()`
/// form directly instead of naming `ProvenanceMap { inner: ... }` at
/// every construction site. [`ProvenanceMap`]'s inner field stays
/// private; this trait is the substrate-owned build path — the
/// tier-level peer of
/// [`FromIterator for crate::discovered::LayerAttribution`] on the
/// discovered algebra.
///
/// # Roundtrip
///
/// The pair with [`IntoIterator for &ProvenanceMap`] roundtrips
/// through the owned `(Vec<String>, Provenance)` shape:
///
/// ```text
/// let map: ProvenanceMap = ...;
/// let round: ProvenanceMap = map.entries()
///     .map(|(p, prov)| (p.to_vec(), prov.clone()))
///     .collect();
/// assert_eq!(map, round);
/// ```
///
/// # Duplicate paths
///
/// The underlying [`BTreeMap`][std::collections::BTreeMap] insertion
/// discipline holds: repeated pairs at the same path resolve
/// *last-write wins*. An empty source produces
/// [`ProvenanceMap::default`][Default::default].
impl FromIterator<(Vec<String>, Provenance)> for ProvenanceMap {
    fn from_iter<I: IntoIterator<Item = (Vec<String>, Provenance)>>(iter: I) -> Self {
        ProvenanceMap {
            inner: iter.into_iter().collect(),
        }
    }
}

/// Extend a [`ProvenanceMap`] with additional `(path, provenance)`
/// pairs — the grow-in-place dual of [`FromIterator for ProvenanceMap`]
/// and the matching `Extend` impl every std keyed collection carries
/// alongside its `FromIterator` (on
/// [`BTreeMap`][std::collections::BTreeMap] /
/// [`HashMap`][std::collections::HashMap], on
/// [`BTreeSet`][std::collections::BTreeSet]). Every pair inserted keeps
/// the same lex order on the owned `Vec<String>` key
/// [`ProvenanceMap::entries`] emits — the tier-level peer of
/// [`Extend for crate::discovered::LayerAttribution`] on the
/// discovered algebra.
///
/// # Duplicate paths
///
/// Same last-write-wins discipline as [`FromIterator`][Self]: a pair at
/// an existing path replaces the prior attribution. An empty source
/// leaves `self` untouched.
///
/// # Cost
///
/// Forwards to [`BTreeMap::extend`][std::collections::BTreeMap], which
/// is `O(m log(n + m))` where `n` is the current leaf count and `m`
/// the pairs supplied — the same amortized insertion cost every
/// consumer pays by constructing a fresh [`ProvenanceMap`] via
/// [`FromIterator`][Self] and merging by hand.
impl Extend<(Vec<String>, Provenance)> for ProvenanceMap {
    fn extend<I: IntoIterator<Item = (Vec<String>, Provenance)>>(&mut self, iter: I) {
        self.inner.extend(iter);
    }
}

// ── ProgressiveLayer — one operator overlay in the progressive fold ──

/// One operator overlay contribution to
/// [`TieredConfig::resolve_progressive_with`]: a partial config [`Dict`]
/// tagged with the [`Provenance`] to stamp on every leaf it wins.
///
/// Typically built from the operator's file / env layer via
/// [`Self::file`] / [`Self::env`]; the fold appends it above the three
/// trait tiers and re-sorts by tier precedence, so a caller cannot place
/// an overlay out of precedence order.
#[derive(Debug, Clone, PartialEq)]
pub struct ProgressiveLayer {
    provenance: Provenance,
    dict: Dict,
}

impl ProgressiveLayer {
    /// Construct an overlay from an explicit provenance + partial dict.
    #[must_use]
    pub fn new(provenance: Provenance, dict: Dict) -> Self {
        Self { provenance, dict }
    }

    /// An operator FILE overlay — [`Provenance::file`].
    #[must_use]
    pub fn file(path: impl Into<PathBuf>, dict: Dict) -> Self {
        Self {
            provenance: Provenance::file(path),
            dict,
        }
    }

    /// An operator ENV overlay — [`Provenance::env`].
    #[must_use]
    pub fn env(prefix: impl Into<String>, dict: Dict) -> Self {
        Self {
            provenance: Provenance::env(prefix),
            dict,
        }
    }

    /// The provenance stamped on every leaf this overlay wins.
    #[must_use]
    pub fn provenance(&self) -> &Provenance {
        &self.provenance
    }

    /// The partial config dict this overlay contributes.
    #[must_use]
    pub fn dict(&self) -> &Dict {
        &self.dict
    }
}

// ── ProgressiveResolution — the (value, provenance) pair the fold returns ──

/// The atomic result of [`TieredConfig::resolve_progressive`]: the resolved
/// config `value` and the [`ProvenanceMap`] naming which tier produced each
/// effective leaf.
///
/// The two are co-constructed by the fold and returned together, so a
/// progressively-resolved value is never handed out without its provenance
/// — the (value, provenance) pair is atomic at this API boundary.
#[derive(Debug, Clone)]
pub struct ProgressiveResolution<T> {
    value: T,
    provenance: ProvenanceMap,
}

impl<T> ProgressiveResolution<T> {
    /// The resolved config value.
    #[must_use]
    pub fn value(&self) -> &T {
        &self.value
    }

    /// The per-leaf provenance map.
    #[must_use]
    pub fn provenance(&self) -> &ProvenanceMap {
        &self.provenance
    }

    /// Consume, yielding the resolved value (dropping provenance).
    #[must_use]
    pub fn into_value(self) -> T {
        self.value
    }

    /// Consume, yielding both the value and its provenance map.
    #[must_use]
    pub fn into_parts(self) -> (T, ProvenanceMap) {
        (self.value, self.provenance)
    }
}

impl<T: PartialEq> PartialEq for ProgressiveResolution<T> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value && self.provenance == other.provenance
    }
}

/// Line-oriented diff between two YAML serializations of a
/// `TieredConfig` value. Designed for operator-facing CLI output
/// (`<app> config-diff <from> <to>`); not a structural patch.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConfigDiff {
    pub lines: Vec<DiffLine>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffLine {
    /// Line present in baseline, absent in candidate.
    Removed(String),
    /// Line absent in baseline, present in candidate.
    Added(String),
    /// Line identical in both (context).
    Context(String),
}

impl DiffLine {
    /// Data-free, `'static` discriminant of this [`DiffLine`]: the kind
    /// of diff cell ([`DiffLineKind::Removed`] / [`DiffLineKind::Added`]
    /// / [`DiffLineKind::Context`]) independent of the inner payload
    /// [`String`].
    ///
    /// One source of truth for the diff-line kind partition over
    /// [`DiffLine`]. Observers that need only the cell-kind axis
    /// (counting added/removed/context lines for stats, filtering for
    /// "show only changes", dispatching per-kind glyph or color at
    /// render time, comparing across thread boundaries without cloning
    /// the borrowed line text) match on this closed enum instead of
    /// pattern-matching against the three payload-carrying variants of
    /// [`DiffLine`].
    ///
    /// Peer of [`ConfigTier::kind`] on the [`ConfigTier`] axis — same
    /// typescape closed-axis discipline (allocation-free,
    /// `Copy + Eq + Hash + #[non_exhaustive]`, exhaustive forward map),
    /// lifted to the diff-line surface so the
    /// `ConfigDiff`-internal partition is named at the type level
    /// rather than lying open-coded in [`ConfigDiff::is_empty_diff`]
    /// and [`ConfigDiff::render_unified`].
    ///
    /// A future [`DiffLine`] variant landing (e.g. a hypothetical
    /// `Header(String)` shape for hunk headers, a `Sep` shape for
    /// inter-hunk separators) forces a corresponding
    /// [`DiffLineKind`] arm through the exhaustive match below.
    #[must_use]
    pub const fn kind(&self) -> DiffLineKind {
        match self {
            Self::Removed(_) => DiffLineKind::Removed,
            Self::Added(_) => DiffLineKind::Added,
            Self::Context(_) => DiffLineKind::Context,
        }
    }

    /// Borrow the inner line text regardless of kind. Companion of
    /// [`Self::kind`]: the (kind, text) pair losslessly reconstructs
    /// the original [`DiffLine`] value, and the two accessors together
    /// replace the three-arm `match` blocks at every renderer site.
    #[must_use]
    pub fn text(&self) -> &str {
        match self {
            Self::Removed(s) | Self::Added(s) | Self::Context(s) => s.as_str(),
        }
    }
}

/// Data-free, `'static` discriminant of [`DiffLine`]: the closed
/// three-way partition over the diff-cell variant space, independent
/// of the inner payload [`String`].
///
/// Returned by [`DiffLine::kind`]. The enum exists so consumers that
/// need only the cell-kind axis (per-kind counters, "only changed
/// lines" filters, per-kind glyph or color rendering at the
/// `ConfigDiff::render_unified` surface, structured-diagnostic
/// legends naming the diff-cell class, comparing across thread
/// boundaries) match on one closed enum instead of pattern-matching
/// against three payload-carrying variants.
///
/// Peer of [`crate::ConfigTierKind`] (variant-tag projection of
/// [`ConfigTier`]), [`crate::WatchEventClass`] (reload-relevance
/// classification of [`notify::EventKind`]), and the other closed-
/// enum kind primitives on the typescape — same discipline (closed,
/// allocation-free, `Copy + Eq + Hash + #[non_exhaustive]`,
/// exhaustive forward map), applied to the diff-cell axis. Before
/// this lift, the three-way kind universe lived only inside
/// [`DiffLine`]'s variant set: every observer wanting the data-free
/// kind class re-pattern-matched against the payload-carrying enum,
/// and the unified-diff glyph (`-`, `+`, ` `) appeared inline at
/// every renderer site rather than at one canonical accessor.
///
/// Adding a future [`DiffLine`] variant (a hypothetical `Header`
/// shape for hunk headers, a `Sep` shape for inter-hunk separators)
/// means adding one [`DiffLineKind`] variant in lockstep — the
/// exhaustive [`DiffLine::kind`] match forces the assignment at
/// compile time.
///
/// `Ord` / `PartialOrd` are declaration-order lex over [`Self::ALL`]
/// (`Removed < Added < Context`): a `BTreeMap<DiffLineKind, T>` keyed
/// on the diff-cell kind (per-cell rebuild-summary histograms keyed
/// over a stable axis, attestation manifests recording the diff-cell
/// cardinality mix of a `ConfigDiff` between two tiers, structured-
/// diagnostic legends bucketing per-cell counters in declaration
/// order) emits rows in that order deterministically without a hand-
/// rolled comparator at the renderer. Idiom-peer of the same derive
/// on [`crate::WatchEventClass`] (commit `94f8a8b`),
/// [`crate::EnvMetadataTagKind`] (commit `b556b75`),
/// [`crate::FigmentNameTagKind`] (commit `64a47e7`),
/// [`crate::FigmentSourceKind`] (commit `5df265c`), and
/// [`crate::ConfigSourceKind`] (commit `e0b96d1`) lifted onto the
/// diff-cell axis closed-enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum DiffLineKind {
    /// Maps to [`DiffLine::Removed`] regardless of inner payload —
    /// a line present in the baseline and absent in the candidate.
    /// Rendered with the canonical unified-diff `-` prefix
    /// ([`Self::glyph`]).
    Removed,
    /// Maps to [`DiffLine::Added`] regardless of inner payload —
    /// a line absent in the baseline and present in the candidate.
    /// Rendered with the canonical unified-diff `+` prefix
    /// ([`Self::glyph`]).
    Added,
    /// Maps to [`DiffLine::Context`] regardless of inner payload —
    /// a line identical in both sides. Rendered with the canonical
    /// unified-diff ` ` (space) prefix ([`Self::glyph`]).
    Context,
}

impl DiffLineKind {
    /// Every [`DiffLineKind`] variant, in declaration order
    /// ([`Self::Removed`], [`Self::Added`], [`Self::Context`]).
    ///
    /// The closed list of diff-line kinds shikumi recognizes. Peer of
    /// [`crate::WatchEventClass::ALL`] (also three-cell) on the
    /// watcher axis and the other closed-axis primitives' `ALL`
    /// constants — same typescape discipline (closed `'static` slice,
    /// in declaration order). Adding a new variant to [`Self`] means
    /// extending this slice in lockstep; the cube-test cardinality
    /// pin (`for_each_closed_axis_primitive!` checksum in
    /// `cube::tests`) catches drift before silent dropouts.
    pub const ALL: &'static [Self] = &[Self::Removed, Self::Added, Self::Context];

    /// Canonical operator-facing lowercase name of the diff-line kind —
    /// `"removed"`, `"added"`, or `"context"`.
    ///
    /// The single source of truth for the diff-cell kind label strings
    /// on the [`DiffLineKind`] axis. Inherent mirror of the
    /// [`crate::ClosedAxisLabel`] trait method; the trait impl
    /// delegates here so the canonical names live at one site instead
    /// of being re-stated at every operator-facing surface (per-kind
    /// counters in a CLI `config-diff` summary, structured-log fields
    /// naming the diff-cell class, attestation manifests recording the
    /// diff-cell kind histogram between two config tiers). The
    /// strings match the variant identifiers in ASCII-lowercase form.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Removed => "removed",
            Self::Added => "added",
            Self::Context => "context",
        }
    }

    /// Canonical unified-diff prefix character — `'-'` for
    /// [`Self::Removed`], `'+'` for [`Self::Added`], `' '` for
    /// [`Self::Context`]. The single source of truth for the per-kind
    /// glyph used by [`ConfigDiff::render_unified`] and every future
    /// renderer that emits the unified-diff line shape.
    ///
    /// Before this lift the three glyph characters lived inline at the
    /// renderer's three-arm `match`; the kind axis names the
    /// (variant → glyph) projection as a typed accessor, so a future
    /// alternative renderer (a Markdown-fenced diff, a color-coded
    /// terminal renderer routing glyph through a palette) reads one
    /// accessor instead of re-stating the three-arm match.
    #[must_use]
    pub const fn glyph(self) -> char {
        match self {
            Self::Removed => '-',
            Self::Added => '+',
            Self::Context => ' ',
        }
    }

    /// Whether this kind represents a structural change between the
    /// two sides (`true` for [`Self::Added`] or [`Self::Removed`],
    /// `false` for [`Self::Context`]).
    ///
    /// Refines [`ConfigDiff::is_empty_diff`]: a diff is empty exactly
    /// when no [`DiffLine`] has a `is_changed` kind. The predicate
    /// previously lived as inline `matches!(l, DiffLine::Added(_) |
    /// DiffLine::Removed(_))` at the call site; the lift names the
    /// (kind → is-it-a-change?) projection at the type level.
    #[must_use]
    pub const fn is_changed(self) -> bool {
        matches!(self, Self::Added | Self::Removed)
    }

    /// Returns `true` for [`Self::Removed`]; equivalent to
    /// `self == DiffLineKind::Removed`.
    #[must_use]
    pub const fn is_removed(self) -> bool {
        matches!(self, Self::Removed)
    }

    /// Returns `true` for [`Self::Added`]; equivalent to
    /// `self == DiffLineKind::Added`.
    #[must_use]
    pub const fn is_added(self) -> bool {
        matches!(self, Self::Added)
    }

    /// Returns `true` for [`Self::Context`]; equivalent to
    /// `self == DiffLineKind::Context`.
    #[must_use]
    pub const fn is_context(self) -> bool {
        matches!(self, Self::Context)
    }
}

impl crate::ClosedAxis for DiffLineKind {
    const ALL: &'static [Self] = Self::ALL;
}

impl crate::ClosedAxisLabel for DiffLineKind {
    fn as_str(self) -> &'static str {
        Self::as_str(self)
    }
}

// The canonical (Display, FromStr, Serialize, Deserialize) string-surface
// quartet on a ClosedAxisLabel primitive — lifted to one macro after the
// 16+ hand-rolled idiom-peers preceding this commit (WatchEventClass at
// `94f8a8b`, ShikumiErrorKind at `4b53792`). See
// `closed_axis_label_string_surface!` in `crate::macros` for the contract;
// behavior is byte-identical to the hand-rolled impls the macro replaces.
closed_axis_label_string_surface! {
    type = DiffLineKind,
    parse_error = "unknown diff line kind",
    expecting = "a canonical DiffLineKind lowercase label \
                 (`removed`, `added`, `context`; case-insensitive)",
}

impl ConfigDiff {
    /// Minimum-viable diff: line-by-line walk of two YAML strings.
    /// Lines that match position-wise are Context; non-matching
    /// positions produce paired Removed/Added entries. Sufficient
    /// for the operator UX of "see what changed between two tiers";
    /// not a structural-merge replacement.
    #[must_use]
    pub fn from_yaml_pair(baseline: &str, candidate: &str) -> Self {
        let a: Vec<&str> = baseline.lines().collect();
        let b: Vec<&str> = candidate.lines().collect();
        let mut lines = Vec::with_capacity(a.len().max(b.len()));
        let mut i = 0;
        let mut j = 0;
        while i < a.len() || j < b.len() {
            match (a.get(i), b.get(j)) {
                (Some(la), Some(lb)) if la == lb => {
                    lines.push(DiffLine::Context((*la).to_string()));
                    i += 1;
                    j += 1;
                }
                (Some(la), Some(lb)) => {
                    lines.push(DiffLine::Removed((*la).to_string()));
                    lines.push(DiffLine::Added((*lb).to_string()));
                    i += 1;
                    j += 1;
                }
                (Some(la), None) => {
                    lines.push(DiffLine::Removed((*la).to_string()));
                    i += 1;
                }
                (None, Some(lb)) => {
                    lines.push(DiffLine::Added((*lb).to_string()));
                    j += 1;
                }
                (None, None) => break,
            }
        }
        Self { lines }
    }

    /// Render as a unified-diff-like string for CLI display.
    /// `-` prefix for Removed, `+` for Added, ` ` for Context.
    ///
    /// Routes the per-kind glyph through [`DiffLineKind::glyph`] and
    /// the payload through [`DiffLine::text`], so the three magic
    /// `'-' / '+' / ' '` characters live at one site
    /// ([`DiffLineKind::glyph`]) instead of being re-stated at every
    /// renderer's three-arm match.
    #[must_use]
    pub fn render_unified(&self) -> String {
        let mut out = String::new();
        for line in &self.lines {
            out.push(line.kind().glyph());
            out.push_str(line.text());
            out.push('\n');
        }
        out
    }

    /// True when there are no Added or Removed lines (only Context).
    /// I.e. baseline == candidate.
    ///
    /// Routes through [`DiffLineKind::is_changed`] — the
    /// (variant → is-it-a-change?) projection lives at one site
    /// instead of inlined here.
    #[must_use]
    pub fn is_empty_diff(&self) -> bool {
        !self.lines.iter().any(|l| l.kind().is_changed())
    }

    /// Typed per-kind tally of [`Self::lines`] over the
    /// [`DiffLineKind`] axis — the dense histogram every CLI
    /// `config-diff` summary, dashboard, attestation manifest, and
    /// alerting policy bucketing the (added × removed × context) line
    /// counts has previously re-derived inline.
    ///
    /// Equivalent to
    /// `crate::axis_histogram(self.lines.iter().map(DiffLine::kind))`
    /// but named at the [`ConfigDiff`] surface so consumers reading a
    /// diff don't reach for the cube-level generic helper. The
    /// histogram's `total()` equals `self.lines.len()` pointwise (every
    /// line projects to exactly one kind); `is_empty()` iff
    /// `self.lines.is_empty()`; `count(DiffLineKind::Added) +
    /// count(DiffLineKind::Removed)` equals zero iff [`Self::is_empty_diff`]
    /// returns `true` — pinned by
    /// `kind_histogram_changed_cells_match_is_empty_diff`.
    #[must_use]
    pub fn kind_histogram(&self) -> crate::AxisHistogram<DiffLineKind> {
        crate::axis_histogram(self.lines.iter().map(DiffLine::kind))
    }

    /// The distinct [`DiffLineKind`]s that appear as ≥1 line in this
    /// diff, in [`DiffLineKind::ALL`] declaration order — the
    /// diff-altitude dual of "which diff-cell kinds actually surfaced
    /// in this render".
    ///
    /// Routes through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::observed`] iterates the histogram's
    /// support (the closed-axis cells with nonzero count) in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`DiffLineKind`] canonical order (`Removed → Added → Context`)
    /// by construction — the closed-axis discipline provides the sort
    /// + dedup automatically, so this method reads directly off the
    /// shikumi cube-native primitive instead of hand-rolling
    /// `Vec::contains` (`O(n·k)` in the line count and distinct-kind
    /// count) + explicit `sort_by_key(axis_ordinal)` at every operator-
    /// facing consumer.
    ///
    /// The diff-altitude peer of
    /// [`crate::ProvenanceMap::contributing_tiers`] on the tier
    /// altitude — both project the observed-support of the underlying
    /// [`crate::AxisHistogram`] over their local closed axis, both
    /// live as a `Vec<CellKind>` collect wrapper alongside their
    /// respective `_histogram()` primitives, and both spell the
    /// closed-axis declaration-order cell iteration at the API
    /// boundary.
    ///
    /// # Invariants
    ///
    /// - `present_kinds().len() ==
    ///   kind_histogram().distinct_cells()` — both project the same
    ///   support-cardinality off the histogram.
    /// - `present_kinds().is_empty() == self.lines.is_empty()` — a
    ///   diff with no lines has no present kinds; a diff with any
    ///   line has ≥1 present kind (every line projects to exactly
    ///   one kind, so the histogram support is nonempty iff the
    ///   line list is).
    /// - `!present_kinds().contains(&DiffLineKind::Added) &&
    ///   !present_kinds().contains(&DiffLineKind::Removed)` iff
    ///   [`Self::is_empty_diff`] returns `true` — the changed-cell
    ///   subset of the present set agrees with the structural-change
    ///   predicate over [`DiffLineKind::is_changed`].
    /// - `present_kinds()` is sorted strictly ascending by
    ///   [`crate::axis_ordinal`] on [`DiffLineKind`] — dedup + sort
    ///   for free from the closed-axis discipline.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build)
    /// and `k = crate::axis_cardinality::<DiffLineKind>()` (the
    /// support scan). Both are `O(n)` in practice since the diff-cell
    /// axis carries a fixed three-cell cardinality; the returned
    /// `Vec<DiffLineKind>` is at most three elements long regardless
    /// of line count.
    #[must_use]
    pub fn present_kinds(&self) -> Vec<DiffLineKind> {
        self.kind_histogram().observed().collect()
    }

    /// The distinct [`DiffLineKind`]s that appear as **zero** lines in
    /// this diff, in [`DiffLineKind::ALL`] declaration order — the
    /// coverage-gap peer of [`Self::present_kinds`] and the diff-altitude
    /// dual of [`crate::ProvenanceMap::absent_tiers`] on the tier altitude.
    ///
    /// Routes through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::unobserved`] iterates the histogram's
    /// **coverage gap** (the closed-axis cells with zero count) in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`DiffLineKind`] canonical order (`Removed → Added → Context`) by
    /// construction — the closed-axis discipline provides the sort +
    /// dedup automatically, so this method reads directly off the shikumi
    /// cube-native primitive instead of hand-rolling
    /// `DiffLineKind::ALL.iter().filter(|k| !self.present_kinds().
    /// contains(k))` (`O(k·k)` in axis-cardinality, quadratic on the
    /// observed side) at every operator-facing consumer asking *"which
    /// diff-cell kinds are absent from this render?"* — the CLI
    /// `config-diff` summary reading *"no removals; nothing to warn
    /// on"*, the attestation manifest recording the diff-cell coverage
    /// gap between two tiers, the alerting policy suppressing per-kind
    /// bins that never fired for this rebuild window.
    ///
    /// The observed-cells peer ([`Self::present_kinds`]) and the
    /// coverage-gap peer ([`Self::absent_kinds`]) together form the
    /// **support / coverage-gap partition** on the diff altitude — every
    /// cell of [`DiffLineKind::ALL`] lies in exactly one of the two, and
    /// the two `Vec<DiffLineKind>` lengths sum to
    /// [`crate::axis_cardinality::<DiffLineKind>()`][crate::axis_cardinality].
    /// The diff-altitude dual of the tier-altitude
    /// [`crate::ProvenanceMap::absent_tiers`] unobserved-cells peer (whose
    /// observed-cells peer is [`crate::ProvenanceMap::contributing_tiers`])
    /// — every altitude of the shikumi typescape now closes both halves
    /// of the histogram's observed / unobserved partition at one named
    /// `Vec<CellKind>` seam alongside the underlying `_histogram()`
    /// primitive.
    ///
    /// # Invariants
    ///
    /// - `absent_kinds().len() == kind_histogram().unobserved_cells()` —
    ///   both project the same coverage-gap cardinality off the
    ///   histogram.
    /// - `present_kinds().len() + absent_kinds().len() ==
    ///   crate::axis_cardinality::<DiffLineKind>()` — the two peers
    ///   partition the closed axis without remainder (every cell is
    ///   either observed or unobserved, never both).
    /// - `present_kinds()` and `absent_kinds()` are disjoint: no
    ///   [`DiffLineKind`] appears in both.
    /// - `absent_kinds().is_empty() == kind_histogram().is_full_cover()`
    ///   — the coverage-gap is empty iff every diff-cell kind was
    ///   observed at least once (all three of Removed / Added / Context
    ///   appear as ≥1 line).
    /// - `absent_kinds()` on an empty [`ConfigDiff`] (no lines) equals
    ///   [`DiffLineKind::ALL`] — every kind is absent when no line
    ///   contributed, the empty-diff / full-coverage-gap boundary.
    /// - `absent_kinds()` is sorted strictly ascending by
    ///   [`crate::axis_ordinal`] on [`DiffLineKind`] — dedup + sort for
    ///   free from the closed-axis discipline.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build)
    /// and `k = crate::axis_cardinality::<DiffLineKind>()` (the
    /// coverage-gap scan). Both are `O(n)` in practice since the
    /// diff-cell axis carries a fixed three-cell cardinality; the
    /// returned `Vec<DiffLineKind>` is at most three elements long
    /// regardless of line count.
    #[must_use]
    pub fn absent_kinds(&self) -> Vec<DiffLineKind> {
        self.kind_histogram().unobserved().collect()
    }

    /// The number of distinct [`DiffLineKind`]s that appear as ≥1 line in
    /// this diff — the support-size scalar peer of [`Self::present_kinds`]
    /// on the diff altitude, closing the "support-size across altitudes"
    /// projection begun on the tier altitude by
    /// [`crate::ProvenanceMap::contributing_tiers_count`] and continued on
    /// the chain altitude by
    /// [`crate::ConfigSourceChain::present_layer_kinds_count`],
    /// [`crate::ConfigSourceChain::present_file_formats_count`], and
    /// [`crate::ConfigSourceChain::present_env_prefix_kinds_count`].
    ///
    /// Routes through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::distinct_cells`] walks the fixed-cardinality
    /// counts vector in a single pass counting the nonzero cells, so this
    /// method reads directly off the shikumi cube-native primitive instead
    /// of allocating a `Vec<DiffLineKind>` via `present_kinds().len()` and
    /// paying twice over the histogram's support (once through
    /// [`crate::AxisHistogram::observed`] to build the vector, once through
    /// [`Vec::len`] to read its length back) at every operator-facing
    /// consumer asking *"how many diff-cell kinds contributed to this
    /// render?"* — the CLI `config-diff` summary line *"3 of 3 diff kinds
    /// contributed to this render"*, the attestation manifest recording
    /// the diff-cell support size between two tiers, the alerting policy
    /// reading *"diff-cell support size = 1"* to flag a diff where only
    /// one kind surfaced.
    ///
    /// The diff-altitude scalar-count peer, sister to the tier altitude's
    /// [`crate::ProvenanceMap::contributing_tiers_count`] and the chain
    /// altitude's [`crate::ConfigSourceChain::present_layer_kinds_count`].
    /// Together with [`Self::present_kinds`] and [`Self::absent_kinds`],
    /// this seam closes the `(observed, unobserved) × (cells, count)` 2×2
    /// support / coverage-gap grid on the diff altitude:
    ///
    /// | | cells (Vec) | count (usize) |
    /// |---|---|---|
    /// | observed | [`Self::present_kinds`] | **`present_kinds_count`** |
    /// | unobserved | [`Self::absent_kinds`] | `absent_kinds().len()` |
    ///
    /// With this lift the substrate now carries the support-size scalar
    /// peer at every altitude and every closed-axis sub-axis — the
    /// "support-size across altitudes" projection is fully closed across
    /// the shikumi typescape.
    ///
    /// # Invariants
    ///
    /// - `present_kinds_count() == kind_histogram().distinct_cells()` —
    ///   both project the same nonzero-cell count off the same primitive;
    ///   the named seam is the cube-native routing of the histogram
    ///   surface.
    /// - `present_kinds_count() == present_kinds().len()` — the scalar-
    ///   count peer of the observed-cells `Vec` peer; both name the same
    ///   support cardinality without materialising the vector.
    /// - `present_kinds_count() + absent_kinds().len() ==
    ///   crate::axis_cardinality::<DiffLineKind>()` — the observed /
    ///   coverage-gap partition on the diff-cell axis without remainder,
    ///   the scalar dual of the
    ///   [`tests::absent_kinds_and_present_kinds_partition_axis`] set-
    ///   level partition law.
    /// - `present_kinds_count() == 0` ⇔ `self.lines.is_empty()` — a diff
    ///   with no lines has no observed kinds and vice versa (every line
    ///   projects to exactly one kind, so the histogram support is
    ///   nonempty iff the line list is).
    /// - `present_kinds_count() >= 1` whenever `!self.lines.is_empty()` —
    ///   the support of a non-empty diff carries at least the singleton
    ///   of the first-line kind.
    /// - `present_kinds_count() <=
    ///   crate::axis_cardinality::<DiffLineKind>()` — the support of a
    ///   histogram over a closed axis is bounded above by the axis
    ///   cardinality (the observed-cells set is a subset of
    ///   [`DiffLineKind::ALL`]).
    /// - `present_kinds_count() <= kind_histogram().total()` — the support
    ///   of a histogram is bounded above by the total observation count
    ///   (every distinct cell contributes at least one line to the
    ///   total).
    /// - `present_kinds_count() ==
    ///   crate::axis_cardinality::<DiffLineKind>()` ⇔
    ///   `absent_kinds().is_empty()` ⇔
    ///   `kind_histogram().is_full_cover()` — the full-cover boundary
    ///   equivalence, the diff-altitude scalar-count peer of the
    ///   [`crate::AxisHistogram::is_full_cover`] boundary law.
    /// - `present_kinds_count() == 1` ⇔
    ///   `kind_histogram().has_singular_support()` — the singleton-
    ///   support boundary equivalence, the diff-altitude peer of the
    ///   [`crate::AxisHistogram::has_singular_support`] boundary law.
    /// - `present_kinds_count() == 1` ⇒ `dominant_kind() ==
    ///   recessive_kind()` — a singleton-support diff has the modal and
    ///   anti-modal cells coincide on the sole observed kind (the
    ///   support-size scalar witnesses the
    ///   [`crate::AxisHistogram`] support-collapse degenerate).
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the support scan).
    /// Both are `O(n)` in practice since the diff-cell axis carries a
    /// fixed three-cell cardinality; unlike [`Self::present_kinds`], no
    /// `Vec<DiffLineKind>` allocation is paid on every call site.
    #[must_use]
    pub fn present_kinds_count(&self) -> usize {
        self.kind_histogram().distinct_cells()
    }

    /// The number of distinct [`DiffLineKind`]s that appear as **zero** lines
    /// in this diff — the coverage-gap scalar peer of [`Self::absent_kinds`]
    /// and the diff-altitude scalar-count sister of [`Self::present_kinds_count`].
    ///
    /// Routes through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::unobserved_cells`] walks the fixed-cardinality
    /// counts vector in a single pass counting the zero cells, so this method
    /// reads directly off the shikumi cube-native primitive instead of
    /// allocating a `Vec<DiffLineKind>` via `absent_kinds().len()` and paying
    /// twice over the histogram's coverage gap (once through
    /// [`crate::AxisHistogram::unobserved`] to build the vector, once through
    /// [`Vec::len`] to read its length back) at every operator-facing consumer
    /// asking *"how many diff-cell kinds are absent from this render?"* —
    /// the CLI `config-diff` summary line *"0 of 3 diff kinds are absent"*,
    /// the attestation manifest recording the diff-cell coverage-gap size
    /// between two tiers, the alerting policy reading *"diff coverage-gap
    /// size = 3"* to flag a rebuild window where the diff was empty.
    ///
    /// The diff-altitude scalar-count coverage-gap peer. Together with
    /// [`Self::present_kinds`], [`Self::absent_kinds`], and
    /// [`Self::present_kinds_count`], this seam closes the
    /// `(observed, unobserved) × (cells, count)` 2×2 support / coverage-gap
    /// grid on the diff altitude explicitly:
    ///
    /// | | cells (Vec) | count (usize) |
    /// |---|---|---|
    /// | observed | [`Self::present_kinds`] | [`Self::present_kinds_count`] |
    /// | unobserved | [`Self::absent_kinds`] | **`absent_kinds_count`** |
    ///
    /// The diff-altitude peer of the tier-altitude
    /// [`crate::ProvenanceMap::absent_tiers_count`] scalar-count coverage-
    /// gap seam — the "coverage-gap-size across altitudes" projection now
    /// carries a named scalar seam at both the tier and diff altitudes,
    /// ready to be climbed sideways across the chain-altitude sub-axes
    /// (`absent_layer_kinds_count`, `absent_file_formats_count`,
    /// `absent_env_prefix_kinds_count`).
    ///
    /// # Invariants
    ///
    /// - `absent_kinds_count() == kind_histogram().unobserved_cells()` —
    ///   both project the same coverage-gap cardinality off the same
    ///   primitive; the named seam is the cube-native routing of the
    ///   histogram surface.
    /// - `absent_kinds_count() == absent_kinds().len()` — the scalar-count
    ///   peer of the coverage-gap `Vec` peer; both name the same coverage-
    ///   gap cardinality without materialising the vector.
    /// - `present_kinds_count() + absent_kinds_count() ==
    ///   crate::axis_cardinality::<DiffLineKind>()` — the observed /
    ///   coverage-gap partition on the diff-cell axis without remainder,
    ///   the fully-scalar dual of the
    ///   [`tests::absent_kinds_and_present_kinds_partition_axis`] set-
    ///   level partition law (both sides now scalar, no `.len()` on either).
    /// - `absent_kinds_count() ==
    ///   crate::axis_cardinality::<DiffLineKind>() - present_kinds_count()`
    ///   — the algebraic rearrangement of the partition, useful for
    ///   consumers that already hold the support-size scalar.
    /// - `absent_kinds_count() ==
    ///   crate::axis_cardinality::<DiffLineKind>()` ⇔ `self.lines.is_empty()`
    ///   — the empty-diff / full-coverage-gap boundary, the scalar peer of
    ///   `absent_kinds() == DiffLineKind::ALL`.
    /// - `absent_kinds_count() == 0` ⇔
    ///   `kind_histogram().is_full_cover()` — the full-cover boundary
    ///   equivalence, the diff-altitude scalar-count peer of the
    ///   [`crate::AxisHistogram::is_full_cover`] boundary law and the
    ///   coverage-gap dual of `present_kinds_count() ==
    ///   crate::axis_cardinality::<DiffLineKind>()`.
    /// - `absent_kinds_count() <=
    ///   crate::axis_cardinality::<DiffLineKind>()` — the coverage gap of a
    ///   histogram over a closed axis is bounded above by the axis
    ///   cardinality (the unobserved-cells set is a subset of
    ///   [`DiffLineKind::ALL`]).
    /// - `absent_kinds_count() >= 1` whenever
    ///   `!kind_histogram().is_full_cover()` — a non-full-cover diff carries
    ///   at least one absent kind.
    /// - `absent_kinds_count() ==
    ///   crate::axis_cardinality::<DiffLineKind>() - 1` ⇔
    ///   `kind_histogram().has_singular_support()` — the singleton-support
    ///   boundary in coverage-gap form: when exactly one kind is observed,
    ///   exactly `axis_cardinality - 1` are absent.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the coverage-gap
    /// scan). Both are `O(n)` in practice since the diff-cell axis carries
    /// a fixed three-cell cardinality; unlike [`Self::absent_kinds`], no
    /// `Vec<DiffLineKind>` allocation is paid on every call site.
    #[must_use]
    pub fn absent_kinds_count(&self) -> usize {
        self.kind_histogram().unobserved_cells()
    }

    /// The [`DiffLineKind`] whose lines dominate this diff by count —
    /// the modal cell of [`Self::kind_histogram`] on the diff altitude.
    /// `None` exactly when the diff is empty (no lines).
    ///
    /// Routes through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::dominant_cell`] picks the argmax cell in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`DiffLineKind`] canonical order (`Removed → Added → Context`)
    /// by construction — the closed-axis discipline provides deterministic
    /// tie-breaking automatically, so this method reads directly off the
    /// shikumi cube-native primitive instead of hand-rolling
    /// `hist.iter().filter(|&(_, c)| c > 0).max_by_key(|&(_, c)| c).map(|(v, _)| v)`
    /// — the inline `max_by_key` form silently picks the *last* tied
    /// cell (per [`Iterator::max_by_key`]'s contract), so two consumers
    /// reading "the dominant diff kind" off the same diff would disagree
    /// under ties unless every one carefully reversed the comparison.
    /// The lift names the scalar at one site with a documented
    /// tie-breaking rule.
    ///
    /// The diff-altitude scalar-mode peer of [`Self::present_kinds`]
    /// (the observed-cells vector peer) and [`Self::absent_kinds`] (the
    /// coverage-gap vector peer): the histogram surface at the diff
    /// altitude now carries the natural triple of "*which* diff kinds
    /// surfaced" / "*which* diff kinds didn't" / "*which single* diff
    /// kind dominated" projections, each a named seam over the shared
    /// [`Self::kind_histogram`] primitive. The diff-altitude dual of
    /// [`crate::ProvenanceMap::dominant_tier`] on the tier altitude —
    /// both project the modal cell of their local closed-axis histogram
    /// off the shared [`crate::AxisHistogram::dominant_cell`] primitive,
    /// both live as an `Option<CellKind>` scalar alongside the observed-
    /// cells / coverage-gap vector peers.
    ///
    /// Operator-facing consumers answering *"which diff-cell kind
    /// dominated this render?"* — the CLI `config-diff` summary
    /// headlining *"Context lines dominate: 47 of 53"*, the attestation
    /// manifest recording the modal diff-cell kind between two tiers,
    /// the alerting policy reading *"diff dominance: Added"* to flag a
    /// rebuild window where net-new lines swamp the changed set — now
    /// route through this named seam instead of a per-consumer
    /// `max_by_key` walk.
    ///
    /// **Tie-breaking is deterministic by declaration order.** When
    /// multiple diff-cell kinds share the maximum line count, the kind
    /// earliest in [`DiffLineKind::ALL`] wins (`Removed → Added →
    /// Context`) — the same order [`Self::present_kinds`] and
    /// [`Self::absent_kinds`] walk. A uniform-cover diff (each kind
    /// producing the same nonzero line count) therefore reports
    /// `Some(DiffLineKind::Removed)` — the first cell in declaration
    /// order — pointwise stable regardless of the insertion order of
    /// individual lines into [`Self::lines`].
    ///
    /// # Invariants
    ///
    /// - `dominant_kind().is_some() == !self.lines.is_empty()` — the
    ///   dominant kind is defined exactly when the diff has at least one
    ///   line. Peer to the `is_empty` boundary [`Self::present_kinds`]
    ///   and [`Self::absent_kinds`] both witness.
    /// - `dominant_kind() == kind_histogram().dominant_cell()` — both
    ///   project the same modal cell off the same primitive; the named
    ///   seam is the cube-native routing of the histogram surface.
    /// - When `Some(k)`, `k` is a member of `present_kinds()` — the
    ///   modal cell is by definition observed.
    /// - When `Some(k)`, `k` is **not** a member of `absent_kinds()` —
    ///   the observed / coverage-gap partition is disjoint.
    /// - `kind_histogram().count(dominant_kind().unwrap()) ==
    ///   kind_histogram().peak_count()` whenever the diff is non-empty —
    ///   the modal cell carries the peak observation count. Peer to
    ///   the (`dominant_cell`, `peak_count`) modal pair invariant on
    ///   [`crate::AxisHistogram`].
    /// - `dominant_kind()` on a uniform per-kind diff (one line per kind)
    ///   equals `Some(DiffLineKind::Removed)` — declaration-order
    ///   tie-breaking on the three-cell axis picks the first cell.
    /// - `dominant_kind()` on an empty [`ConfigDiff`] equals `None` —
    ///   the empty-diff / empty-histogram boundary.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the argmax scan).
    /// Both are `O(n)` in practice since the diff-cell axis carries a
    /// fixed three-cell cardinality; the returned
    /// `Option<DiffLineKind>` reads one cell.
    #[must_use]
    pub fn dominant_kind(&self) -> Option<DiffLineKind> {
        self.kind_histogram().dominant_cell()
    }

    /// The **peak line count** — the number of lines contributed by the
    /// dominant [`DiffLineKind`] on this diff. Returns `0` exactly when the
    /// diff is empty (no lines); otherwise returns the line count carried
    /// by [`Self::dominant_kind`] (pointwise equal to it, and always
    /// `>= 1` on the non-empty side).
    ///
    /// The **scalar peer** of [`Self::dominant_kind`] on the count side —
    /// the natural typed primitive for CLI `config-diff` summaries,
    /// attestation manifests, and alerting policies asking *"how many
    /// lines did the dominant diff kind produce?"*: the summary line
    /// *"Context lines dominate: 47 of 53"* (where 47 is this scalar), the
    /// attestation manifest recording the peak-kind observation count
    /// between two rendered diffs, the alerting policy reading *"peak
    /// diff kind count = 12"* to gate a rebuild window on the modal
    /// kind's density. Before this lift, every such consumer re-derived
    /// the projection inline as `diff.kind_histogram().peak_count()` or
    /// (equivalently but at twice the cost)
    /// `diff.dominant_kind().map_or(0, |k| diff.kind_histogram().count(k))`
    /// — which walked the histogram *twice* (once to argmax, once to read
    /// the count back through [`crate::AxisHistogram::count`] indexing)
    /// and re-built the histogram at every site. Routes through
    /// [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::peak_count`] reads a single pass over the
    /// fixed-cardinality counts vector.
    ///
    /// The diff-altitude scalar-count peer of [`Self::dominant_kind`] (the
    /// modal-cell scalar peer of [`Self::kind_histogram`]) — the histogram
    /// surface on the diff altitude now carries the fused
    /// `(dominant_kind, peak_kind_count)` modal pair, matching the
    /// ([`crate::AxisHistogram::dominant_cell`],
    /// [`crate::AxisHistogram::peak_count`]) pair on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down and the
    /// ([`crate::ProvenanceMap::dominant_tier`],
    /// [`crate::ProvenanceMap::peak_tier_count`]) pair on the tier
    /// altitude. Consumers answering *"which diff kind dominated and by
    /// how much?"* now read a single
    /// `(dominant_kind(), peak_kind_count())` pair — one method each,
    /// both routing through the same primitive — instead of re-deriving
    /// the count off the modal cell.
    ///
    /// **Empty-diff convention** — returns `0` (not `Option<usize>`)
    /// matching the [`crate::AxisHistogram::peak_count`] convention one
    /// altitude down and the [`crate::ProvenanceMap::peak_tier_count`]
    /// convention on the tier altitude; the scalar
    /// `(lines.len(), peak_kind_count)` pair reads uniformly `(0, 0)` on
    /// the empty diff. The dual-form [`Self::dominant_kind`] carries
    /// `Option<DiffLineKind>` because the *kind* is undefined when no
    /// line contributes; the *count* is well-defined as zero. The
    /// asymmetry is intentional: every scalar projection reads zero on
    /// empty; every cell projection reads `None`.
    ///
    /// # Invariants
    ///
    /// - `peak_kind_count() == 0` ⇔ `self.lines.is_empty()` — peer to
    ///   the empty-diff boundary [`Self::dominant_kind`],
    ///   [`Self::recessive_kind`], [`Self::present_kinds`], and
    ///   [`Self::absent_kinds`] all witness on the cell / vector sides.
    /// - `peak_kind_count() == kind_histogram().peak_count()` — both
    ///   project the same scalar off the same primitive; the named seam
    ///   is the cube-native routing of the histogram surface.
    /// - `peak_kind_count() == dominant_kind().map_or(0, |k|
    ///   kind_histogram().count(k))` — the count projection of the
    ///   `(dominant_kind, peak_kind_count)` modal pair equals
    ///   [`Self::peak_kind_count`] pointwise on every diff (empty:
    ///   `None.map_or(0, …) == 0 == peak_kind_count`; non-empty:
    ///   `Some(k).map_or(0, |k| count(k)) == peak_kind_count`, since
    ///   `count(dominant_kind()) == peak_count()`).
    /// - `peak_kind_count() <= self.lines.len()` always: the peak is
    ///   bounded above by the total line count (every kind contributes
    ///   at most every line, and the others contribute zero). Equality
    ///   holds when `present_kinds().len() <= 1`.
    /// - `peak_kind_count() == self.lines.len()` iff
    ///   `present_kinds().len() <= 1`: a single observed kind carries
    ///   every line, so the peak equals the total. Zero observed kinds
    ///   (empty) reads 0 == 0; one observed kind reads N == N; two or
    ///   more reads peak < total strictly.
    /// - `peak_kind_count() >= 1` whenever `!self.lines.is_empty()` — a
    ///   non-empty diff always has at least one line on the dominant
    ///   kind.
    /// - `peak_kind_count()` on a uniform per-kind diff (one line per
    ///   kind) equals `1` — every observed kind collects one line,
    ///   dominant included.
    /// - `peak_kind_count()` on a singleton-support diff (every line on
    ///   the same kind) equals `self.lines.len()` — the dominant kind
    ///   collects every line. Singleton-support pin.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the argmax scan).
    /// Both are `O(n)` in practice since the diff-cell axis carries a
    /// fixed three-cell cardinality; the returned `usize` reads one
    /// scalar. Halves the cost of the previous
    /// `dominant_kind().map_or(0, |k| kind_histogram().count(k))` idiom
    /// (which walked the histogram twice — once to argmax, once to read
    /// the count back).
    #[must_use]
    pub fn peak_kind_count(&self) -> usize {
        self.kind_histogram().peak_count()
    }

    /// The [`DiffLineKind`] whose lines are rarest (but still ≥1) in this
    /// diff — the anti-modal (rarest observed) cell of
    /// [`Self::kind_histogram`] on the diff altitude. `None` exactly when
    /// the diff is empty (no lines).
    ///
    /// Routes through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::recessive_cell`] picks the argmin cell over
    /// the histogram's *support* (the nonzero cells) in
    /// [`crate::ClosedAxis::ALL`] declaration order, which is the
    /// [`DiffLineKind`] canonical order (`Removed → Added → Context`) by
    /// construction — the closed-axis discipline provides deterministic
    /// tie-breaking automatically, so this method reads directly off the
    /// shikumi cube-native primitive instead of hand-rolling
    /// `hist.iter().filter(|&(_, c)| c > 0).min_by_key(|&(_, c)| c).map(|(v, _)| v)`
    /// — the inline `min_by_key` form silently picks the *first* tied
    /// cell (per [`Iterator::min_by_key`]'s contract, which reverses
    /// [`Iterator::max_by_key`]'s "last on ties" behavior), so an
    /// open-coded argmin and the open-coded argmax on the dominant side
    /// would disagree on which tied cell to pick. The pair of lifts
    /// ([`Self::dominant_kind`] and [`Self::recessive_kind`]) pins one
    /// consistent tie-breaking rule across both projections.
    ///
    /// **Zero-count kinds are excluded from the search.** The argmin is
    /// taken over the histogram's support, not over the full axis. Kinds
    /// that contributed no line are trivially the minimum over the full
    /// axis and would shadow the rarest *observed* kind; excluding them
    /// surfaces the rarest kind some line actually landed on — the
    /// question the CLI `config-diff` summary, attestation manifest, and
    /// alerting policy ask when they surface *"the runt cell this diff
    /// saw"*. This matches [`Self::dominant_kind`]'s symmetry on the
    /// maximum side: both projections operate over the nonzero support,
    /// so the empty-diff convention is identical (both return `None`)
    /// and the singleton-support case is identical (both return the sole
    /// observed kind).
    ///
    /// The diff-altitude anti-modal peer of [`Self::dominant_kind`] (the
    /// modal-cell scalar peer of the same [`Self::kind_histogram`]
    /// primitive) — the histogram surface on the diff altitude now
    /// carries the fused (dominant, recessive) cell pair, matching the
    /// ([`crate::AxisHistogram::dominant_cell`],
    /// [`crate::AxisHistogram::recessive_cell`]) pair on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down. The
    /// diff-altitude dual of [`crate::ProvenanceMap::recessive_tier`] on
    /// the tier altitude — both project the anti-modal cell of their
    /// local closed-axis histogram off the shared
    /// [`crate::AxisHistogram::recessive_cell`] primitive, both live as
    /// an `Option<CellKind>` scalar alongside the modal-cell peer.
    ///
    /// Operator-facing consumers answering *"which diff-cell kind is the
    /// runt of this render?"* — the CLI `config-diff` summary
    /// headlining *"runt: Removed, 1 of 47 lines"*, the attestation
    /// manifest recording the anti-modal diff-cell kind between two
    /// tiers, the alerting policy reading *"diff runt: Added"* to flag a
    /// rebuild window where net-new lines are the sparse minority — now
    /// route through this named seam instead of a per-consumer
    /// `min_by_key` walk.
    ///
    /// **Tie-breaking is deterministic by declaration order.** When
    /// multiple observed kinds share the minimum line count, the kind
    /// earliest in [`DiffLineKind::ALL`] wins (`Removed → Added →
    /// Context`) — the same order [`Self::present_kinds`],
    /// [`Self::absent_kinds`], and [`Self::dominant_kind`] walk. A
    /// uniform-cover diff (each kind producing the same nonzero line
    /// count) therefore reports `Some(DiffLineKind::Removed)` — the
    /// first cell in declaration order — pointwise identical to
    /// [`Self::dominant_kind`] on the same input (the singleton-modality
    /// degenerate where the modal and anti-modal cells coincide).
    ///
    /// # Invariants
    ///
    /// - `recessive_kind().is_some() == !self.lines.is_empty()` — the
    ///   recessive kind is defined exactly when the diff has at least
    ///   one line. Peer to the `is_empty` boundary [`Self::dominant_kind`],
    ///   [`Self::present_kinds`], and [`Self::absent_kinds`] all witness.
    /// - `recessive_kind().is_some() == dominant_kind().is_some()` —
    ///   both projections are defined on the same support
    ///   (`!self.lines.is_empty()`), lifted from the
    ///   [`crate::AxisHistogram::recessive_cell`] /
    ///   [`crate::AxisHistogram::dominant_cell`] presence-bound law.
    /// - `recessive_kind() == kind_histogram().recessive_cell()` — both
    ///   project the same anti-modal cell off the same primitive; the
    ///   named seam is the cube-native routing of the histogram surface.
    /// - When `Some(k)`, `k` is a member of `present_kinds()` — the
    ///   anti-modal cell is by definition observed.
    /// - When `Some(k)`, `k` is **not** a member of `absent_kinds()` —
    ///   the observed / coverage-gap partition is disjoint, and the
    ///   argmin over the *support* never coincides with a zero-count
    ///   cell.
    /// - `kind_histogram().count(recessive_kind().unwrap()) ==
    ///   kind_histogram().trough_count()` whenever the diff is non-empty
    ///   — the anti-modal cell carries the trough-of-support observation
    ///   count. Peer to the (`recessive_cell`, `trough_count`) anti-modal
    ///   pair invariant on [`crate::AxisHistogram`].
    /// - `kind_histogram().count(recessive_kind().unwrap()) <=
    ///   kind_histogram().count(dominant_kind().unwrap())` whenever the
    ///   diff is non-empty — the trough-of-support count is bounded
    ///   above by the peak count. Lifted from the trait-uniform
    ///   `count(recessive_cell) <= count(dominant_cell)` law on
    ///   [`crate::AxisHistogram`].
    /// - `recessive_kind() == dominant_kind()` whenever
    ///   `present_kinds().len() == 1` — a single observed kind is both
    ///   the modal and the anti-modal cell (the singleton-support
    ///   degenerate).
    /// - `recessive_kind()` on a uniform per-kind diff (one line per
    ///   kind) equals `Some(DiffLineKind::Removed)` — declaration-order
    ///   tie-breaking on the three-cell axis picks the first cell,
    ///   pointwise identical to `dominant_kind()` on the same input.
    /// - `recessive_kind()` on an empty [`ConfigDiff`] equals `None` —
    ///   the empty-diff / empty-histogram boundary.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the argmin scan).
    /// Both are `O(n)` in practice since the diff-cell axis carries a
    /// fixed three-cell cardinality; the returned `Option<DiffLineKind>`
    /// reads one cell.
    #[must_use]
    pub fn recessive_kind(&self) -> Option<DiffLineKind> {
        self.kind_histogram().recessive_cell()
    }

    /// The **trough line count** — the number of lines contributed by the
    /// recessive (rarest-observed) [`DiffLineKind`] on this diff. Returns
    /// `0` exactly when the diff is empty (no lines); otherwise returns
    /// the line count carried by [`Self::recessive_kind`] (pointwise
    /// equal to it, and always `>= 1` by the histogram-support
    /// definition).
    ///
    /// The **scalar peer** of [`Self::recessive_kind`] on the count side —
    /// the natural typed primitive for CLI `config-diff` summaries,
    /// attestation manifests, and alerting policies asking *"how many
    /// lines did the runt diff kind produce?"*: the summary line *"runt:
    /// Removed, 1 of 47 lines"* (where 1 is this scalar), the attestation
    /// manifest recording the trough-kind observation count between two
    /// rendered diffs, the alerting policy reading *"trough diff kind
    /// count = 1"* to flag a rebuild window where a kind barely appeared.
    /// Before this lift, every such consumer re-derived the projection
    /// inline as `diff.kind_histogram().trough_count()` or (equivalently
    /// but at twice the cost)
    /// `diff.recessive_kind().map_or(0, |k| diff.kind_histogram().count(k))`
    /// — which walked the histogram *twice* (once to argmin over the
    /// support, once to read the count back through
    /// [`crate::AxisHistogram::count`] indexing) and re-built the
    /// histogram at every site. Routes through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::trough_count`] reads a single pass over
    /// the fixed-cardinality counts vector (filtering the zero-count
    /// cells out of the argmin search).
    ///
    /// The diff-altitude scalar-count peer of [`Self::recessive_kind`]
    /// (the anti-modal-cell scalar peer of [`Self::kind_histogram`]) —
    /// the histogram surface on the diff altitude now carries the fused
    /// `(recessive_kind, trough_kind_count)` anti-modal pair, matching
    /// the ([`crate::AxisHistogram::recessive_cell`],
    /// [`crate::AxisHistogram::trough_count`]) pair on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down and the
    /// ([`crate::ProvenanceMap::recessive_tier`],
    /// [`crate::ProvenanceMap::trough_tier_count`]) pair on the tier
    /// altitude. Consumers answering *"which diff kind is the runt and
    /// by how much?"* now read a single
    /// `(recessive_kind(), trough_kind_count())` pair — one method
    /// each, both routing through the same primitive — instead of
    /// re-deriving the count off the anti-modal cell.
    ///
    /// The 2×2 `(dominant, recessive) × (cell, count)` scalar grid on
    /// the diff altitude closes with this lift: the four seams
    /// ([`Self::dominant_kind`], [`Self::peak_kind_count`],
    /// [`Self::recessive_kind`], [`Self::trough_kind_count`]) now each
    /// route through the same [`Self::kind_histogram`] primitive at one
    /// pass per projection, matching the `(dominant_cell, peak_count,
    /// recessive_cell, trough_count)` quad on the shared
    /// [`crate::AxisHistogram`] primitive one altitude down and the
    /// `(dominant_tier, peak_tier_count, recessive_tier,
    /// trough_tier_count)` quad on the tier altitude.
    ///
    /// **Empty-diff convention** — returns `0` (not `Option<usize>`)
    /// matching the [`crate::AxisHistogram::trough_count`] convention
    /// one altitude down, the [`Self::peak_kind_count`] convention on
    /// the same altitude, and the
    /// [`crate::ProvenanceMap::trough_tier_count`] convention on the
    /// tier altitude; the scalar `(peak_kind_count, trough_kind_count)`
    /// pair reads uniformly `(0, 0)` on the empty diff. The dual-form
    /// [`Self::recessive_kind`] carries `Option<DiffLineKind>` because
    /// the *kind* is undefined when no line contributes; the *count* is
    /// well-defined as zero. The asymmetry is intentional: every scalar
    /// projection reads zero on empty; every cell projection reads
    /// `None`.
    ///
    /// # Invariants
    ///
    /// - `trough_kind_count() == 0` ⇔ `self.lines.is_empty()` — peer to
    ///   the empty-diff boundary [`Self::dominant_kind`],
    ///   [`Self::recessive_kind`], and [`Self::peak_kind_count`] all
    ///   witness on the cell / count sides.
    /// - `trough_kind_count() == kind_histogram().trough_count()` — both
    ///   project the same scalar off the same primitive; the named seam
    ///   is the cube-native routing of the histogram surface.
    /// - `trough_kind_count() == recessive_kind().map_or(0, |k|
    ///   kind_histogram().count(k))` — the count projection of the
    ///   `(recessive_kind, trough_kind_count)` anti-modal pair equals
    ///   [`Self::trough_kind_count`] pointwise on every diff (empty:
    ///   `None.map_or(0, …) == 0 == trough_kind_count`; non-empty:
    ///   `Some(k).map_or(0, |k| count(k)) == trough_kind_count`, since
    ///   `count(recessive_kind()) == trough_count()`).
    /// - `trough_kind_count() <= peak_kind_count()` always: the trough
    ///   is bounded above by the peak (lifted from the trait-uniform
    ///   `trough_count() <= peak_count()` law on
    ///   [`crate::AxisHistogram`]). The empty-diff case reads `0 <= 0`;
    ///   the non-empty case reads the trough-of-support bounded above by
    ///   the peak-of-support.
    /// - `trough_kind_count() == peak_kind_count()` iff
    ///   `present_kinds().len() <= 1`: on the empty diff both are 0; on
    ///   a singleton-support diff both equal `self.lines.len()`; on two
    ///   or more observed kinds with distinct counts the trough is
    ///   strictly below the peak.
    /// - `trough_kind_count() >= 1` whenever `!self.lines.is_empty()` —
    ///   the argmin is taken over the histogram's *support* (nonzero
    ///   cells), so the trough of a non-empty histogram is always at
    ///   least one.
    /// - `trough_kind_count()` on a uniform per-kind diff (one line per
    ///   kind) equals `1` — every observed kind collects one line; the
    ///   trough coincides with the peak on the uniform-cover degenerate
    ///   (the singleton-modality analogue on the count side).
    /// - `trough_kind_count()` on a singleton-support diff (every line
    ///   on the same kind) equals `self.lines.len()` — the sole observed
    ///   kind is both the modal and anti-modal cell, so trough == peak
    ///   == len.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the argmin scan
    /// over the support). Both are `O(n)` in practice since the diff-cell
    /// axis carries a fixed three-cell cardinality; the returned `usize`
    /// reads one scalar. Halves the cost of the previous
    /// `recessive_kind().map_or(0, |k| kind_histogram().count(k))` idiom
    /// (which walked the histogram twice — once to argmin, once to read
    /// the count back).
    #[must_use]
    pub fn trough_kind_count(&self) -> usize {
        self.kind_histogram().trough_count()
    }

    /// The **observed-distribution spread of diff kinds** — the
    /// difference between the peak and trough line counts on this diff.
    /// Equal to `self.peak_kind_count() - self.trough_kind_count()` by
    /// construction, routed through [`Self::kind_histogram`]:
    /// [`crate::AxisHistogram::spread`] reads the same difference off
    /// the fixed-cardinality counts vector in one pass. Returns `0`
    /// exactly when every observed [`DiffLineKind`] contributed the
    /// same number of lines — including the empty diff (vacuous
    /// uniformity, no observed kinds), every singleton-support diff
    /// (only one observed kind, trivially balanced), and every uniform
    /// per-kind diff (each observed kind contributing the same nonzero
    /// count, dominant included).
    ///
    /// The **scalar dispersion peer** of the fused
    /// `(peak_kind_count, trough_kind_count)` modal-count pair — the
    /// natural typed primitive for CLI `config-diff` summaries,
    /// attestation manifests, and alerting policies asking *"how
    /// unevenly distributed are the lines across the observed
    /// diff kinds?"*: the summary line *"skew 2: dominant Context 3,
    /// runt Removed 1"* (where 2 is this scalar), the attestation
    /// manifest recording the diff-kind spread between two rebuild
    /// windows, the alerting policy reading *"diff spread = 11"* to
    /// flag a rebuild window where one kind dwarfed the others. Before
    /// this lift, every such consumer re-derived the projection inline
    /// as `diff.peak_kind_count() - diff.trough_kind_count()` — two
    /// method calls plus a subtraction at every site, each site having
    /// to reason independently about the structural non-negativity of
    /// the difference (`peak_count >= trough_count` holds on every
    /// histogram but not on the inline subtraction surface, so an
    /// unwitnessed refactor swapping the operands would silently
    /// underflow). Routes through [`crate::AxisHistogram::spread`] one
    /// altitude down — the underflow-safe named seam whose docs pin the
    /// monotonicity invariant explicitly.
    ///
    /// The diff-altitude scalar-dispersion peer that seeds the
    /// "spread across altitudes" projection — the next natural lift
    /// climbs to the tier altitude
    /// (`ProvenanceMap::tier_spread` over [`Self::tier_histogram`] on
    /// the tier altitude) and sideways along the chain altitude's
    /// three sub-axes (`layer_kind_spread`, `file_format_spread`,
    /// `env_prefix_kind_spread` over the corresponding chain
    /// histograms). The pattern is the same at every altitude: fuse
    /// the (`peak_count`, `trough_count`) modal-count pair into a single
    /// dispersion scalar named at the surface, routed through the
    /// shared [`crate::AxisHistogram::spread`] primitive one altitude
    /// down.
    ///
    /// **Empty-diff convention** — returns `0`, matching the
    /// [`crate::AxisHistogram::spread`] empty convention one altitude
    /// down and the [`Self::peak_kind_count`] / [`Self::trough_kind_count`]
    /// empty conventions on the same altitude. The scalar-count triple
    /// `(peak_kind_count, trough_kind_count, kind_spread)` reads
    /// uniformly `(0, 0, 0)` on the empty diff — every observation
    /// scalar reads zero on empty; every cell projection
    /// ([`Self::dominant_kind`], [`Self::recessive_kind`]) reads
    /// `None`. The asymmetry is intentional and matches the
    /// [`crate::AxisHistogram`] convention one altitude down.
    ///
    /// **Structural-skew predicate.** `kind_spread() == 0` is the
    /// typed *balanced-diff-kinds* predicate at the diff altitude —
    /// every observed [`DiffLineKind`] contributed the same number of
    /// lines. Pointwise equivalent to `peak_kind_count() ==
    /// trough_kind_count()` on the scalar-count pair and to
    /// `dominant_kind() == recessive_kind()` on the modal-cell pair
    /// whenever the diff is non-empty (both branches reduce to
    /// `Some(first) == Some(first)` on singleton-support and uniform
    /// diffs, and to `false` on skewed diffs). Together with
    /// [`Self::is_empty_diff`] and the full-cover predicate on
    /// [`Self::kind_histogram`], the diff-altitude scalar surface now
    /// carries the natural boundary triple *"did this diff change
    /// anything?"* / *"did it exercise every kind?"* / *"did the
    /// kinds fire equally?"* — each a single method call.
    ///
    /// # Invariants
    ///
    /// - `kind_spread() == kind_histogram().spread()` — both project
    ///   the same scalar off the same primitive; the named seam is the
    ///   cube-native routing of the histogram surface.
    /// - `kind_spread() == peak_kind_count() - trough_kind_count()` —
    ///   the fused-pair identity of the scalar-dispersion peer. The
    ///   subtraction is underflow-safe because `peak_kind_count() >=
    ///   trough_kind_count()` holds structurally on every diff (lifted
    ///   from the trait-uniform `peak_count() >= trough_count()` law
    ///   on [`crate::AxisHistogram`]).
    /// - `kind_spread() == 0` on the empty diff — the vacuous
    ///   uniformity boundary, matching the
    ///   [`crate::AxisHistogram::spread`] empty convention one altitude
    ///   down. The `(peak_kind_count, trough_kind_count, kind_spread)`
    ///   triple reads `(0, 0, 0)` uniformly on the empty diff.
    /// - `kind_spread() == 0` whenever `present_kinds().len() <= 1` —
    ///   singleton-support diffs are trivially balanced (the one
    ///   observed kind's count is both the peak and the trough). Also
    ///   holds on every uniform per-kind diff (each observed kind
    ///   contributing the same nonzero count).
    /// - `kind_spread() <= peak_kind_count()` always — the trough is
    ///   non-negative, so the subtraction is bounded above by the
    ///   minuend. Equality holds iff the trough is zero — i.e. on the
    ///   empty diff. Lifted from the trait-uniform
    ///   `spread() <= peak_count()` law on
    ///   [`crate::AxisHistogram`].
    /// - `kind_spread() <= self.lines.len()` always — composition of
    ///   `kind_spread() <= peak_kind_count()` (this method) with
    ///   `peak_kind_count() <= self.lines.len()` (documented on
    ///   [`Self::peak_kind_count`]).
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the peak + trough
    /// scan). Both are `O(n)` in practice since the diff-cell axis
    /// carries a fixed three-cell cardinality; the returned `usize`
    /// reads one scalar. Halves the cost of the previous inline
    /// `diff.peak_kind_count() - diff.trough_kind_count()` idiom (which
    /// walked the counts vector twice — once for the max, once for the
    /// min-over-support — where [`crate::AxisHistogram::spread`] can
    /// fuse both into a single walk with a running-max/min pair).
    #[must_use]
    pub fn kind_spread(&self) -> usize {
        self.kind_histogram().spread()
    }

    /// The **balanced-diff-kinds boolean predicate** at the diff altitude —
    /// `true` exactly when every observed [`DiffLineKind`] contributed the
    /// same number of lines. The typed boolean peer of `kind_spread() == 0`
    /// on the scalar-dispersion surface, lifting the same structural-skew
    /// boundary from the scalar surface to a named predicate at the diff
    /// altitude. Routes through
    /// [`crate::AxisHistogram::is_uniform_count`] one altitude down: the
    /// single-pass scan over the fixed-cardinality counts vector that
    /// short-circuits on the first pair of distinct nonzero cells, tighter
    /// than the two-scan `peak_count()` / `trough_count()` fusion the
    /// scalar-spread form pays for.
    ///
    /// The **balanced-diff-kinds peer** of the fused
    /// `(peak_kind_count, trough_kind_count, kind_spread)` dispersion
    /// triple on the diff altitude — the natural typed boolean primitive
    /// for CLI `config-diff` summaries, attestation manifests, and
    /// alerting policies asking *"did every observed diff kind fire
    /// equally?"*: the summary line *"balanced diff: every observed kind
    /// contributed equally"*, the attestation manifest gate *"rebuild
    /// window balanced across diff kinds"*, the alerting policy predicate
    /// *"diff balanced"*. Before this lift, every such consumer
    /// re-derived the predicate inline as `diff.kind_spread() == 0` (the
    /// scalar-spread form, which routes through a subtraction whose
    /// underflow safety relies on the structural `peak >= trough`
    /// invariant on [`Self::kind_spread`]), or as
    /// `diff.peak_kind_count() == diff.trough_kind_count()` (the
    /// scalar-pair form, which pays for two count walks and equates two
    /// `usize`s without saying structurally *what* is being equated),
    /// or as `diff.dominant_kind() == diff.recessive_kind()` (the modal-
    /// pair form, which peers through `Option<DiffLineKind>` equality
    /// across two argmax/argmin walks). The three forms drifted in subtle
    /// ways at every consumer site. This lift names the balanced-diff-
    /// kinds predicate directly at the diff-altitude surface with a
    /// single-pass short-circuiting scan — the typed boolean every
    /// operator-facing "is this diff balanced?" check reads off as a
    /// single method call.
    ///
    /// The diff-altitude balanced-predicate peer that seeds the "balanced
    /// across altitudes" projection — the next natural lift climbs to the
    /// tier altitude (`ProvenanceMap::tiers_balanced` over
    /// [`Self::tier_histogram`] on the tier altitude) and sideways along
    /// the chain altitude's three sub-axes (`layer_kinds_balanced`,
    /// `file_formats_balanced`, `env_prefix_kinds_balanced` over the
    /// corresponding chain histograms). The pattern is the same at every
    /// altitude: fuse the (`peak_count`, `trough_count`, `spread`) scalar
    /// triple's balanced-boundary into a single boolean predicate named
    /// at the surface, routed through the shared
    /// [`crate::AxisHistogram::is_uniform_count`] primitive one altitude
    /// down. Parallels the "spread across altitudes" projection seeded on
    /// the same altitude by [`Self::kind_spread`], climbed to the tier
    /// altitude by [`crate::ProvenanceMap::tier_spread`], and lifted
    /// sideways along the chain altitude's three sub-axes
    /// ([`crate::ConfigSourceChain::layer_kind_spread`],
    /// [`crate::ConfigSourceChain::file_format_spread`],
    /// [`crate::ConfigSourceChain::env_prefix_kind_spread`]).
    ///
    /// **Empty-diff convention** — returns `true` vacuously: the empty
    /// diff has no observed cells, so the universal "every observed cell
    /// carries the same count" reads `true` over the empty support.
    /// Matches [`crate::AxisHistogram::is_uniform_count`]'s empty
    /// convention one altitude down and `kind_spread() == 0` on the empty
    /// case (peak == trough == 0). The empty diff is therefore on the
    /// `true` side of the balanced-diff-kinds boundary — the vacuous-
    /// uniformity witness.
    ///
    /// **Singleton-support convention** — returns `true` on every diff
    /// whose observed support is a single [`DiffLineKind`] (trivially
    /// balanced: the one observed kind's count is both the peak and the
    /// trough). Includes every diff of only-`Removed`, only-`Added`, or
    /// only-`Context` lines.
    ///
    /// **Uniform per-kind convention** — returns `true` on every uniform
    /// per-kind diff (each observed kind contributing the same nonzero
    /// count), including the k-kind-observed-once-each shape and the
    /// uniform three-kind cover.
    ///
    /// # Invariants
    ///
    /// - `kinds_balanced() == kind_histogram().is_uniform_count()` — both
    ///   project the same predicate off the same primitive; the named
    ///   seam is the cube-native routing of the histogram surface.
    /// - `kinds_balanced() == (kind_spread() == 0)` always — the defining
    ///   equivalence on the scalar-spread surface at the diff altitude.
    /// - `kinds_balanced() == (peak_kind_count() == trough_kind_count())`
    ///   always — the structural form on the underlying scalar pair.
    /// - `kinds_balanced() == (dominant_kind() == recessive_kind())`
    ///   always — the modal-pair form; both branches agree on the empty
    ///   diff (`None == None`), on every singleton-support diff
    ///   (`Some(k) == Some(k)`), on every uniform per-kind diff
    ///   (`Some(first_kind) == Some(first_kind)` after declaration-order
    ///   tie-break), and on every skewed diff (both sides read `false`).
    /// - `self.lines.is_empty() ⇒ kinds_balanced()` — vacuous uniformity
    ///   on the empty diff. Contrapositively, `!kinds_balanced() ⇒
    ///   !self.lines.is_empty()` (a skewed diff has at least two
    ///   distinct positive counts, so the diff is non-empty).
    /// - `present_kinds().len() <= 1 ⇒ kinds_balanced()` — every diff
    ///   with support size 0 or 1 is trivially balanced. Contrapositively,
    ///   `!kinds_balanced() ⇒ present_kinds().len() >= 2` (a skewed diff
    ///   observes at least two distinct kinds with differing counts).
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the uniform-count
    /// scan). Both are `O(n)` in practice since the diff-cell axis
    /// carries a fixed three-cell cardinality; the returned `bool` reads
    /// one predicate. The scan short-circuits on the first pair of
    /// distinct nonzero cells (bounded at two nonzero cells visited),
    /// strictly tighter than the two-full-scan `peak_count()` /
    /// `trough_count()` fusion the scalar-spread form pays for on skewed
    /// inputs.
    #[must_use]
    pub fn kinds_balanced(&self) -> bool {
        self.kind_histogram().is_uniform_count()
    }

    /// `true` exactly when every [`DiffLineKind`] cell was observed at
    /// least once on this diff — the **full-cover-diff-kinds predicate**
    /// on the diff altitude. Routes through
    /// [`crate::AxisHistogram::is_full_cover`] one altitude down: the
    /// single-pass scan over the fixed-cardinality counts vector that
    /// short-circuits on the first zero cell, tighter than any of the
    /// four coverage-gap equality forms one seam over.
    ///
    /// The **full-cover-diff-kinds peer** of the fused
    /// `(present_kinds, absent_kinds, present_kinds_count,
    /// absent_kinds_count)` support / coverage-gap 2×2 grid on the diff
    /// altitude — the natural typed boolean primitive for CLI
    /// `config-diff` summaries, attestation manifests, and alerting
    /// policies asking *"did every diff-cell kind fire at least once on
    /// this rebuild?"*: the summary line *"full-cover diff: every diff
    /// kind fired"*, the attestation manifest gate *"rebuild window
    /// full-cover across diff kinds"*, the alerting policy predicate
    /// *"diff full-cover"*. Before this lift, every such consumer
    /// re-derived the predicate inline as one of four pointwise-
    /// equivalent forms: `diff.absent_kinds().is_empty()` (the coverage-
    /// gap-`Vec` form, which allocates a `Vec<DiffLineKind>` and reads
    /// its emptiness), `diff.absent_kinds_count() == 0` (the coverage-
    /// gap-scalar form, which pays for a full-axis scan and equates a
    /// `usize` to zero without saying structurally *what* is being
    /// equated), `diff.present_kinds_count() ==
    /// crate::axis_cardinality::<DiffLineKind>()` (the support-scalar
    /// form, which pays for the support scan and pulls in the
    /// [`crate::axis_cardinality`] turbofish at every call site), and
    /// `diff.present_kinds().len() ==
    /// crate::axis_cardinality::<DiffLineKind>()` (the support-`Vec`
    /// form, which allocates a `Vec<DiffLineKind>` and reads its
    /// length back). The four forms drifted in subtle ways at every
    /// consumer site (allocation vs. scalar, turbofish vs. name-only,
    /// coverage-gap side vs. support side). This lift names the
    /// full-cover-diff-kinds predicate directly at the diff-altitude
    /// surface with a single-pass short-circuiting scan — the typed
    /// boolean every operator-facing "did the diff fully cover the
    /// axis?" check reads off as a single method call.
    ///
    /// The diff-altitude full-cover-predicate peer that **seeds the
    /// "full-cover across altitudes" projection** — the natural next
    /// lift climbs to the tier altitude (`ProvenanceMap::tiers_full_cover`
    /// over [`crate::ProvenanceMap::tier_histogram`] on the tier
    /// altitude) and sideways along the chain altitude's three sub-axes
    /// (`layer_kinds_full_cover`, `file_formats_full_cover`,
    /// `env_prefix_kinds_full_cover` over the corresponding chain
    /// histograms). The pattern is the same at every altitude: fuse
    /// the (`present_cells`, `absent_cells`, `present_cells_count`,
    /// `absent_cells_count`) support / coverage-gap 2×2 grid's full-
    /// cover-boundary into a single boolean predicate named at the
    /// surface, routed through the shared
    /// [`crate::AxisHistogram::is_full_cover`] primitive one altitude
    /// down. Parallels the "balanced across altitudes" projection
    /// seeded on the same altitude by [`Self::kinds_balanced`],
    /// climbed to the tier altitude by
    /// [`crate::ProvenanceMap::tiers_balanced`], and lifted sideways
    /// along the chain altitude's three sub-axes
    /// ([`crate::ConfigSourceChain::layer_kinds_balanced`],
    /// [`crate::ConfigSourceChain::file_formats_balanced`],
    /// [`crate::ConfigSourceChain::env_prefix_kinds_balanced`]).
    ///
    /// **Empty-diff convention** — returns `false` on the empty diff:
    /// the empty diff has no observed cells, so the coverage gap
    /// equals every cell of [`DiffLineKind::ALL`] — the full-cover
    /// predicate fails. Matches [`crate::AxisHistogram::is_full_cover`]'s
    /// empty-histogram convention one altitude down on the non-zero-
    /// cardinality [`DiffLineKind`] axis (three cells: `Removed`,
    /// `Added`, `Context`). The empty diff is therefore on the `false`
    /// side of the full-cover-diff-kinds boundary — the dual of the
    /// vacuous-uniformity witness on [`Self::kinds_balanced`], which
    /// reads `true` on the empty diff.
    ///
    /// **Singleton-support convention** — returns `false` on every diff
    /// whose observed support is a single [`DiffLineKind`]: one observed
    /// cell out of three leaves at least two cells in the coverage
    /// gap, so the full-cover predicate fails. Every diff of only-
    /// `Removed`, only-`Added`, or only-`Context` lines is a witness.
    ///
    /// **Uniform three-kind cover convention** — returns `true` on
    /// every diff where each of the three [`DiffLineKind`] cells was
    /// observed at least once (regardless of per-kind count). Includes
    /// the k-kind-observed-once-each shape (one `Removed` + one `Added`
    /// + one `Context`) and every skewed three-kind cover.
    ///
    /// # Invariants
    ///
    /// - `kinds_full_cover() == kind_histogram().is_full_cover()` — both
    ///   project the same predicate off the same primitive; the named
    ///   seam is the cube-native routing of the histogram surface.
    /// - `kinds_full_cover() == absent_kinds().is_empty()` always —
    ///   the defining equivalence on the coverage-gap-`Vec` surface at
    ///   the diff altitude.
    /// - `kinds_full_cover() == (absent_kinds_count() == 0)` always —
    ///   the defining equivalence on the coverage-gap-scalar surface,
    ///   without allocating the `Vec<DiffLineKind>`.
    /// - `kinds_full_cover() == (present_kinds_count() ==
    ///   crate::axis_cardinality::<DiffLineKind>())` always — the
    ///   support-scalar form, the dual-side surfacing of the same
    ///   boolean across the (observed, unobserved) partition.
    /// - `kinds_full_cover() == (present_kinds().len() ==
    ///   crate::axis_cardinality::<DiffLineKind>())` always — the
    ///   support-`Vec` form, without allocating twice through
    ///   [`Vec::len`].
    /// - `kinds_full_cover() ⇒ !self.lines.is_empty()` — a full-cover
    ///   diff observes at least one line per [`DiffLineKind`], so the
    ///   line list is non-empty. Contrapositively, `self.lines.is_empty()
    ///   ⇒ !kinds_full_cover()` (the empty-diff / full-coverage-gap
    ///   boundary).
    /// - `kinds_full_cover() ⇒ present_kinds().len() ==
    ///   crate::axis_cardinality::<DiffLineKind>()` — a full-cover diff
    ///   observes every kind, so the support size equals the axis
    ///   cardinality. Contrapositively, `present_kinds().len() <
    ///   crate::axis_cardinality::<DiffLineKind>() ⇒ !kinds_full_cover()`.
    /// - `kinds_full_cover() ⇒ self.lines.len() >=
    ///   crate::axis_cardinality::<DiffLineKind>()` — a full-cover diff
    ///   observes at least one line per kind, so the line count is
    ///   bounded below by the axis cardinality.
    ///
    /// # Cost
    ///
    /// `O(n + k)` where `n = self.lines.len()` (the histogram build) and
    /// `k = crate::axis_cardinality::<DiffLineKind>()` (the full-cover
    /// scan). Both are `O(n)` in practice since the diff-cell axis
    /// carries a fixed three-cell cardinality; the returned `bool`
    /// reads one predicate. The scan short-circuits on the first zero
    /// cell (bounded at one zero cell visited on a non-full-cover diff),
    /// strictly tighter than the four coverage-gap equality forms — no
    /// `Vec<DiffLineKind>` allocation, no [`crate::axis_cardinality`]
    /// turbofish, no scalar equality against a magic axis-cardinality
    /// constant.
    #[must_use]
    pub fn kinds_full_cover(&self) -> bool {
        self.kind_histogram().is_full_cover()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;

    #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
    struct Toy {
        name: String,
        size: u32,
        flag: bool,
    }

    impl TieredConfig for Toy {
        fn bare() -> Self {
            Self {
                name: String::new(),
                size: 0,
                flag: false,
            }
        }
        fn prescribed_default() -> Self {
            Self {
                name: "default-name".into(),
                size: 42,
                flag: true,
            }
        }
    }

    #[test]
    fn bare_returns_floor_values() {
        let b = Toy::bare();
        assert_eq!(b.name, "");
        assert_eq!(b.size, 0);
        assert!(!b.flag);
    }

    #[test]
    fn prescribed_default_is_different_from_bare() {
        let b = Toy::bare();
        let p = Toy::prescribed_default();
        assert_ne!(b, p);
    }

    #[test]
    fn discovered_default_impl_returns_bare() {
        // No override → discovered is identical to bare.
        let d = Toy::discovered();
        let b = Toy::bare();
        assert_eq!(d, b);
    }

    #[test]
    fn diff_against_self_is_empty() {
        let p = Toy::prescribed_default();
        let diff = p.diff_against(&p);
        assert!(diff.is_empty_diff());
    }

    #[test]
    fn diff_bare_vs_default_yields_added_and_removed_lines() {
        let b = Toy::bare();
        let p = Toy::prescribed_default();
        let diff = p.diff_against(&b);
        assert!(!diff.is_empty_diff());
        let has_added = diff
            .lines
            .iter()
            .any(|l| matches!(l, DiffLine::Added(s) if s.contains("default-name")));
        let has_removed = diff
            .lines
            .iter()
            .any(|l| matches!(l, DiffLine::Removed(s) if s.contains("name: ''")));
        assert!(has_added, "diff should add the prescribed name");
        assert!(has_removed, "diff should remove the bare empty name");
    }

    #[test]
    fn render_unified_uses_diff_prefixes() {
        let b = Toy::bare();
        let p = Toy::prescribed_default();
        let rendered = p.diff_against(&b).render_unified();
        assert!(rendered.contains("-name: ''"));
        assert!(rendered.contains("+name: default-name"));
    }

    #[test]
    fn extend_default_impl_full_replaces_base() {
        let b = Toy::bare();
        let p = Toy::prescribed_default();
        let merged = p.clone().extend(&b);
        assert_eq!(merged, p);
    }

    // ── ConfigTier + resolve_tier coverage ──────────────────────

    #[test]
    fn config_tier_default_is_default_variant() {
        assert_eq!(ConfigTier::default(), ConfigTier::Default);
    }

    #[test]
    fn config_tier_from_str_recognizes_named_tiers() {
        assert_eq!(ConfigTier::from_str_or_default("bare"), ConfigTier::Bare);
        assert_eq!(
            ConfigTier::from_str_or_default("DISCOVERED"),
            ConfigTier::Discovered
        );
        assert_eq!(
            ConfigTier::from_str_or_default("default"),
            ConfigTier::Default
        );
        assert_eq!(ConfigTier::from_str_or_default(""), ConfigTier::Default);
        match ConfigTier::from_str_or_default("/etc/foo.yaml") {
            ConfigTier::Custom(p) => {
                assert_eq!(p, std::path::PathBuf::from("/etc/foo.yaml"));
            }
            other => panic!("expected Custom, got {other:?}"),
        }
    }

    #[test]
    fn config_tier_names_are_stable() {
        assert_eq!(ConfigTier::Bare.name(), "bare");
        assert_eq!(ConfigTier::Discovered.name(), "discovered");
        assert_eq!(ConfigTier::Default.name(), "default");
        assert_eq!(
            ConfigTier::Custom(std::path::PathBuf::from("/x")).name(),
            "custom"
        );
    }

    #[test]
    fn config_tier_from_env_resolves_correctly() {
        let key = "SHIKUMI_TIERED_TEST_TIER_X";
        // Set to "bare", verify resolution.
        // SAFETY: tests run single-threaded per test by default;
        // we restore + clear the env var on every branch.
        unsafe {
            std::env::set_var(key, "bare");
        }
        assert_eq!(ConfigTier::from_env(key), ConfigTier::Bare);
        unsafe {
            std::env::set_var(key, "");
        }
        assert_eq!(ConfigTier::from_env(key), ConfigTier::Default);
        unsafe {
            std::env::remove_var(key);
        }
        assert_eq!(ConfigTier::from_env(key), ConfigTier::Default);
    }

    #[test]
    fn resolve_tier_dispatches_to_each_method() {
        assert_eq!(Toy::resolve_tier(ConfigTier::Bare), Toy::bare());
        assert_eq!(Toy::resolve_tier(ConfigTier::Discovered), Toy::discovered());
        assert_eq!(
            Toy::resolve_tier(ConfigTier::Default),
            Toy::prescribed_default()
        );
    }

    #[test]
    fn resolve_tier_custom_missing_file_falls_back_to_default() {
        let phantom = std::path::PathBuf::from("/nonexistent/path/shikumi-tier-fallback-test.yaml");
        let resolved = Toy::resolve_tier(ConfigTier::Custom(phantom));
        assert_eq!(resolved, Toy::prescribed_default());
    }

    // ── ConfigTierKind + ConfigTier::kind coverage ──────────────

    #[test]
    fn config_tier_kind_all_has_four_entries() {
        // Pin today's tier-kind cardinality. A fifth tier kind
        // landing forces the ::ALL slice in lockstep with the
        // enum, and the `for_each_closed_axis_primitive!` macro
        // cardinality checksum in `cube::tests` (axis_cardinality
        // sum) catches the drift before silent dropouts at the
        // trait-uniform test sites.
        assert_eq!(ConfigTierKind::ALL.len(), 4);
        assert_eq!(ConfigTierKind::ALL[0], ConfigTierKind::Bare);
        assert_eq!(ConfigTierKind::ALL[1], ConfigTierKind::Discovered);
        assert_eq!(ConfigTierKind::ALL[2], ConfigTierKind::Default);
        assert_eq!(ConfigTierKind::ALL[3], ConfigTierKind::Custom);
    }

    #[test]
    fn config_tier_kind_trait_all_matches_inherent_all() {
        // Mirror of the per-axis trait/inherent agreement test:
        // <ConfigTierKind as ClosedAxis>::ALL is the same slice as
        // ConfigTierKind::ALL pointwise in declaration order.
        assert_eq!(
            <ConfigTierKind as crate::ClosedAxis>::ALL.len(),
            ConfigTierKind::ALL.len(),
        );
        for (i, (trait_kind, inherent_kind)) in <ConfigTierKind as crate::ClosedAxis>::ALL
            .iter()
            .zip(ConfigTierKind::ALL.iter())
            .enumerate()
        {
            assert_eq!(
                trait_kind, inherent_kind,
                "trait ALL[{i}] must equal inherent ALL[{i}]",
            );
        }
    }

    #[test]
    fn config_tier_kind_as_str_yields_canonical_lowercase_names() {
        assert_eq!(ConfigTierKind::Bare.as_str(), "bare");
        assert_eq!(ConfigTierKind::Discovered.as_str(), "discovered");
        assert_eq!(ConfigTierKind::Default.as_str(), "default");
        assert_eq!(ConfigTierKind::Custom.as_str(), "custom");
    }

    #[test]
    fn config_tier_kind_from_str_round_trips_with_as_str() {
        // Round-trip law: `from_str(kind.as_str()) == Some(kind)`
        // for every kind. Pinned over the full ::ALL slice so a
        // fifth tier kind inherits the law automatically.
        for &kind in ConfigTierKind::ALL {
            assert_eq!(
                ConfigTierKind::from_str(kind.as_str()),
                Some(kind),
                "round-trip failed for kind {kind:?}",
            );
        }
    }

    #[test]
    fn config_tier_kind_from_str_is_case_insensitive() {
        assert_eq!(ConfigTierKind::from_str("BARE"), Some(ConfigTierKind::Bare),);
        assert_eq!(
            ConfigTierKind::from_str("Discovered"),
            Some(ConfigTierKind::Discovered),
        );
        assert_eq!(
            ConfigTierKind::from_str("DeFaUlT"),
            Some(ConfigTierKind::Default),
        );
        assert_eq!(
            ConfigTierKind::from_str("CUSTOM"),
            Some(ConfigTierKind::Custom),
        );
    }

    #[test]
    fn config_tier_kind_from_str_returns_none_on_unknown() {
        assert_eq!(ConfigTierKind::from_str(""), None);
        assert_eq!(ConfigTierKind::from_str("nonexistent"), None);
        assert_eq!(ConfigTierKind::from_str("/etc/foo.yaml"), None);
        // No trim — the caller owns trim policy.
        assert_eq!(ConfigTierKind::from_str(" bare "), None);
    }

    #[test]
    fn config_tier_kind_projection_matches_config_tier_name() {
        // The kind projection and the ConfigTier::name() lookup
        // must agree pointwise — both are routed through
        // ConfigTierKind::as_str. Pins the duplication budget at
        // zero: the four tier-name strings live at one site
        // (ConfigTierKind::as_str).
        let pairs: [(ConfigTier, ConfigTierKind); 4] = [
            (ConfigTier::Bare, ConfigTierKind::Bare),
            (ConfigTier::Discovered, ConfigTierKind::Discovered),
            (ConfigTier::Default, ConfigTierKind::Default),
            (
                ConfigTier::Custom(std::path::PathBuf::from("/x")),
                ConfigTierKind::Custom,
            ),
        ];
        for (tier, expected_kind) in pairs {
            assert_eq!(tier.kind(), expected_kind);
            assert_eq!(tier.name(), expected_kind.as_str());
        }
    }

    #[test]
    fn config_tier_from_env_still_lowercases_unknown_paths() {
        // Behavior preservation: prior implementation lowercased
        // unrecognized strings before wrapping them in Custom.
        // This pin catches any future drift away from that
        // (somewhat surprising) behavior — kept so that the lift
        // is purely structural and doesn't change semantics.
        let key = "SHIKUMI_TIERED_TEST_TIER_PATH";
        unsafe {
            std::env::set_var(key, "/Foo/Bar.YAML");
        }
        let tier = ConfigTier::from_env(key);
        match tier {
            ConfigTier::Custom(p) => assert_eq!(
                p,
                std::path::PathBuf::from("/foo/bar.yaml"),
                "from_env preserves the pre-lift lowercase behavior",
            ),
            other => panic!("expected Custom, got {other:?}"),
        }
        unsafe {
            std::env::remove_var(key);
        }
    }

    // ── DiffLineKind + DiffLine::kind coverage ──────────────────
    //
    // The (DiffLine → DiffLineKind) lift closes the diff-cell kind
    // partition on the third closed three-way classification of the
    // typescape, alongside `ConfigSourceKind` (3 cells), `FieldPathLocalization`
    // (3), and `WatchEventClass` (3). Tests mirror the
    // `EnvMetadataTagKind` suite pointwise on the source axis:
    // forward-map exhaustivity, payload-independence, trait-bounds
    // parity, no-duplicates on the closed list, image containment in
    // `ALL`, declaration-order pin, concrete-position canonical
    // labels, glyph-pin against the operator-facing unified-diff
    // convention, refactor pins on the two consumer sites
    // (`is_empty_diff` / `render_unified`), and the trait-default
    // round-trip.

    fn canonical_diff_line_kind_samples() -> Vec<(DiffLine, DiffLineKind)> {
        vec![
            (DiffLine::Removed("name: ''".into()), DiffLineKind::Removed),
            (
                DiffLine::Added("name: default-name".into()),
                DiffLineKind::Added,
            ),
            (DiffLine::Context("size: 42".into()), DiffLineKind::Context),
            (DiffLine::Removed(String::new()), DiffLineKind::Removed),
            (DiffLine::Added(String::new()), DiffLineKind::Added),
            (DiffLine::Context(String::new()), DiffLineKind::Context),
        ]
    }

    #[test]
    fn diff_line_kind_classifies_each_variant() {
        // The forward map DiffLine → DiffLineKind is exhaustive: every
        // variant pins to exactly one kind.
        assert_eq!(DiffLine::Removed("x".into()).kind(), DiffLineKind::Removed,);
        assert_eq!(DiffLine::Added("y".into()).kind(), DiffLineKind::Added);
        assert_eq!(DiffLine::Context("z".into()).kind(), DiffLineKind::Context,);
    }

    #[test]
    fn diff_line_kind_is_data_free() {
        // Inner payload does not influence kind — every Removed
        // variant maps to DiffLineKind::Removed regardless of the
        // inner String. Mirrors `env_metadata_tag_kind_is_data_free`
        // on the figment-Name env-name sub-axis.
        for payload in ["", "a", "name: 'long value'  ", "\n", "\u{1F600}"] {
            assert_eq!(
                DiffLine::Removed(payload.to_string()).kind(),
                DiffLineKind::Removed,
            );
            assert_eq!(
                DiffLine::Added(payload.to_string()).kind(),
                DiffLineKind::Added,
            );
            assert_eq!(
                DiffLine::Context(payload.to_string()).kind(),
                DiffLineKind::Context,
            );
        }
    }

    #[test]
    fn diff_line_kind_agrees_with_predicates_pointwise() {
        // The kind() projection must agree with the kind-side
        // `is_removed` / `is_added` / `is_context` predicates pointwise
        // on every constructible variant.
        for (line, expected) in canonical_diff_line_kind_samples() {
            let k = line.kind();
            assert_eq!(k, expected);
            assert_eq!(k.is_removed(), k == DiffLineKind::Removed);
            assert_eq!(k.is_added(), k == DiffLineKind::Added);
            assert_eq!(k.is_context(), k == DiffLineKind::Context);
        }
    }

    #[test]
    fn diff_line_kind_is_changed_partitions_added_or_removed() {
        // is_changed() partitions the kind axis: true exactly on the
        // two changed kinds (Added, Removed), false on Context. The
        // partition is the structural law `ConfigDiff::is_empty_diff`
        // refines through `.kind().is_changed()`.
        assert!(DiffLineKind::Removed.is_changed());
        assert!(DiffLineKind::Added.is_changed());
        assert!(!DiffLineKind::Context.is_changed());
    }

    #[test]
    fn diff_line_kind_is_static_and_copy_and_hashable() {
        // The discriminant is `'static` (no lifetime parameter) and
        // Copy + Hash + Eq, so it can be hashed in a `'static` map and
        // cross thread boundaries the borrowed payload `&String`
        // cannot. Trait bounds match the sibling typescape primitives.
        use std::collections::HashSet;
        fn assert_static<T: 'static>() {}
        assert_static::<DiffLineKind>();
        let mut set: HashSet<DiffLineKind> = DiffLineKind::ALL.iter().copied().collect();
        set.insert(DiffLineKind::Removed); // duplicate
        assert_eq!(set.len(), DiffLineKind::ALL.len());
        // Copy: rebind without move.
        let k = DiffLineKind::Added;
        let k2 = k;
        assert_eq!(k, k2);
    }

    #[test]
    fn diff_line_kind_all_has_no_duplicates() {
        // `ALL` is a set on the closed axis — no duplicated variant.
        use std::collections::HashSet;
        let unique: HashSet<DiffLineKind> = DiffLineKind::ALL.iter().copied().collect();
        assert_eq!(unique.len(), DiffLineKind::ALL.len());
    }

    #[test]
    fn diff_line_kind_all_covers_every_constructible_line() {
        // Every kind produced by DiffLine::kind() on the canonical
        // sample table appears in DiffLineKind::ALL. Catches drift if
        // a future DiffLine variant lands without extending ::ALL.
        for (line, _) in canonical_diff_line_kind_samples() {
            assert!(
                DiffLineKind::ALL.contains(&line.kind()),
                "DiffLineKind::ALL must contain the kind of every constructible DiffLine",
            );
        }
    }

    #[test]
    fn diff_line_kind_all_equals_diff_line_kind_image() {
        // Tight image / `ALL` equality: the image of DiffLine::kind
        // over the canonical sample table equals DiffLineKind::ALL as
        // a set — no kind cell is unreachable, no orphan cell exists.
        use std::collections::HashSet;
        let image: HashSet<DiffLineKind> = canonical_diff_line_kind_samples()
            .into_iter()
            .map(|(l, _)| l.kind())
            .collect();
        let all: HashSet<DiffLineKind> = DiffLineKind::ALL.iter().copied().collect();
        assert_eq!(image, all);
    }

    #[test]
    fn diff_line_kind_all_declaration_order_is_removed_added_context() {
        // Declaration order pin. Mirror of the renderer's natural
        // reading order (removed → added → context) so the canonical
        // axis enumeration matches the unified-diff legend operators
        // already read in tools.
        assert_eq!(DiffLineKind::ALL.len(), 3);
        assert_eq!(DiffLineKind::ALL[0], DiffLineKind::Removed);
        assert_eq!(DiffLineKind::ALL[1], DiffLineKind::Added);
        assert_eq!(DiffLineKind::ALL[2], DiffLineKind::Context);
    }

    #[test]
    fn diff_line_kind_as_str_yields_canonical_lowercase_names() {
        // Concrete-position pin on the canonical operator-facing
        // labels. A rename here would surface a literal string change
        // before drifting through the round-trip law.
        assert_eq!(DiffLineKind::Removed.as_str(), "removed");
        assert_eq!(DiffLineKind::Added.as_str(), "added");
        assert_eq!(DiffLineKind::Context.as_str(), "context");
    }

    #[test]
    fn diff_line_kind_glyph_yields_canonical_unified_diff_prefixes() {
        // Concrete-position pin on the canonical unified-diff glyphs.
        // The three glyph characters previously lived inline at the
        // renderer's three-arm match; pinning them at the kind axis
        // catches any future rename before drifting through the
        // renderer.
        assert_eq!(DiffLineKind::Removed.glyph(), '-');
        assert_eq!(DiffLineKind::Added.glyph(), '+');
        assert_eq!(DiffLineKind::Context.glyph(), ' ');
    }

    #[test]
    fn diff_line_text_returns_inner_payload_pointwise() {
        // The `text` accessor borrows the inner payload regardless of
        // kind. Composes with `.kind()` to losslessly decompose a
        // DiffLine into its (kind, text) pair — the natural shape for
        // any renderer that previously matched on the three variants.
        for payload in ["", "a", "name: value", "  leading spaces"] {
            assert_eq!(DiffLine::Removed(payload.to_string()).text(), payload);
            assert_eq!(DiffLine::Added(payload.to_string()).text(), payload);
            assert_eq!(DiffLine::Context(payload.to_string()).text(), payload);
        }
    }

    #[test]
    fn diff_line_kind_from_canonical_str_round_trips_through_trait() {
        // Trait-default round-trip law: case-insensitively, every
        // canonical label parses back to its kind via the
        // `ClosedAxisLabel` trait default. Mixed-case inputs hit the
        // case-insensitive parse path.
        use crate::ClosedAxisLabel;
        for &k in DiffLineKind::ALL {
            let lower = k.as_str();
            assert_eq!(DiffLineKind::from_canonical_str(lower), Some(k));
            let upper = lower.to_ascii_uppercase();
            assert_eq!(DiffLineKind::from_canonical_str(&upper), Some(k));
            // Mixed: capitalize first letter only.
            let mut mixed = String::new();
            for (i, c) in lower.chars().enumerate() {
                if i == 0 {
                    mixed.extend(c.to_uppercase());
                } else {
                    mixed.push(c);
                }
            }
            assert_eq!(DiffLineKind::from_canonical_str(&mixed), Some(k));
        }
    }

    #[test]
    fn config_diff_is_empty_diff_routes_through_diff_line_kind_is_changed() {
        // Pin the structural refactor: `ConfigDiff::is_empty_diff`
        // returns false iff some line has a `is_changed` kind. A diff
        // composed of only Context lines is empty; any Added or
        // Removed line makes it non-empty regardless of how many
        // Context lines surround it.
        let only_context = ConfigDiff {
            lines: vec![DiffLine::Context("a".into()), DiffLine::Context("b".into())],
        };
        assert!(only_context.is_empty_diff());

        let with_added = ConfigDiff {
            lines: vec![
                DiffLine::Context("a".into()),
                DiffLine::Added("c".into()),
                DiffLine::Context("b".into()),
            ],
        };
        assert!(!with_added.is_empty_diff());

        let with_removed = ConfigDiff {
            lines: vec![DiffLine::Removed("x".into())],
        };
        assert!(!with_removed.is_empty_diff());

        let empty_lines = ConfigDiff { lines: vec![] };
        assert!(empty_lines.is_empty_diff());
    }

    #[test]
    fn config_diff_render_unified_emits_one_glyph_per_kind() {
        // Pin the structural refactor: `ConfigDiff::render_unified`
        // routes each line's glyph through `DiffLineKind::glyph` and
        // each payload through `DiffLine::text`. The rendered output
        // is byte-identical to the prior open-coded three-arm match.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("name: ''".into()),
                DiffLine::Added("name: default-name".into()),
                DiffLine::Context("size: 42".into()),
            ],
        };
        let rendered = diff.render_unified();
        assert_eq!(
            rendered, "-name: ''\n+name: default-name\n size: 42\n",
            "render_unified must emit the canonical glyph per kind",
        );
        // Pointwise: each line's first character equals its kind's glyph.
        for (i, line) in diff.lines.iter().enumerate() {
            let expected_glyph = line.kind().glyph();
            let actual_first = rendered
                .lines()
                .nth(i)
                .and_then(|s| s.chars().next())
                .expect("rendered output must have at least i+1 lines");
            assert_eq!(
                actual_first, expected_glyph,
                "rendered line {i} must start with its kind's glyph",
            );
        }
    }

    #[test]
    fn config_diff_render_unified_byte_identical_to_pre_lift_form() {
        // Strong pin on the refactor: the rendered output must match
        // what the prior three-arm match produced byte-for-byte across
        // every line position (empty payloads, mixed kinds, trailing
        // newlines). Composes with the kind-axis lift without changing
        // the operator-facing surface.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context(String::new()),
                DiffLine::Removed("a".into()),
                DiffLine::Added("b".into()),
                DiffLine::Context("c".into()),
            ],
        };
        // Pre-lift expected output:
        //   " \n" + "-a\n" + "+b\n" + " c\n"
        assert_eq!(diff.render_unified(), " \n-a\n+b\n c\n");
    }

    #[test]
    fn config_tier_from_str_or_default_via_kind_dispatch() {
        // Smoke pin on the refactored dispatch — same matching
        // rules as before, now routed through ConfigTierKind.
        assert_eq!(ConfigTier::from_str_or_default("bare"), ConfigTier::Bare);
        assert_eq!(
            ConfigTier::from_str_or_default("DISCOVERED"),
            ConfigTier::Discovered,
        );
        assert_eq!(
            ConfigTier::from_str_or_default("default"),
            ConfigTier::Default,
        );
        assert_eq!(ConfigTier::from_str_or_default(""), ConfigTier::Default,);
        // "custom" with no path → Custom(PathBuf::from("custom"))
        // (the literal string becomes the path). Preserves the
        // pre-lift fall-through behavior.
        match ConfigTier::from_str_or_default("custom") {
            ConfigTier::Custom(p) => {
                assert_eq!(p, std::path::PathBuf::from("custom"));
            }
            other => panic!("expected Custom, got {other:?}"),
        }
        match ConfigTier::from_str_or_default("/etc/foo.yaml") {
            ConfigTier::Custom(p) => {
                assert_eq!(p, std::path::PathBuf::from("/etc/foo.yaml"));
            }
            other => panic!("expected Custom, got {other:?}"),
        }
    }

    #[test]
    fn kind_histogram_counts_each_kind_pointwise() {
        // Concrete pin on the [`ConfigDiff::kind_histogram`] lift: the
        // per-cell counts agree with the manual filter-and-count loop
        // it replaces. The fixture covers the three diff-cell kinds at
        // distinct cardinalities so the per-cell numbers are
        // distinguishable (1 removed, 2 added, 3 context).
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
            ],
        };
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Removed), 1);
        assert_eq!(hist.count(DiffLineKind::Added), 2);
        assert_eq!(hist.count(DiffLineKind::Context), 3);
        assert_eq!(hist.total(), diff.lines.len());
    }

    #[test]
    fn kind_histogram_empty_diff_is_zero_on_every_cell() {
        // An empty [`ConfigDiff`] yields the all-zero histogram: total
        // = 0, every cell = 0, `is_empty()` = true. The identity slot
        // of the histogram monoid on the diff-cell axis.
        let diff = ConfigDiff::default();
        let hist = diff.kind_histogram();
        assert_eq!(hist.total(), 0);
        assert!(hist.is_empty());
        for cell in [
            DiffLineKind::Removed,
            DiffLineKind::Added,
            DiffLineKind::Context,
        ] {
            assert_eq!(hist.count(cell), 0);
        }
    }

    #[test]
    fn kind_histogram_changed_cells_match_is_empty_diff() {
        // Cross-primitive law: the sum of the [`DiffLineKind::Added`]
        // and [`DiffLineKind::Removed`] cells equals zero iff
        // [`ConfigDiff::is_empty_diff`] returns true. Both
        // surfaces project from the same partition over the
        // [`DiffLineKind`] axis (the `is_changed()` half), so the
        // agreement is structural — pinned here on a context-only
        // diff (empty by structure) and on a mixed diff.
        let context_only = ConfigDiff {
            lines: vec![DiffLine::Context("c".into())],
        };
        let h1 = context_only.kind_histogram();
        assert!(context_only.is_empty_diff());
        assert_eq!(
            h1.count(DiffLineKind::Added) + h1.count(DiffLineKind::Removed),
            0
        );

        let with_change = ConfigDiff {
            lines: vec![DiffLine::Context("c".into()), DiffLine::Added("a".into())],
        };
        let h2 = with_change.kind_histogram();
        assert!(!with_change.is_empty_diff());
        assert!(h2.count(DiffLineKind::Added) + h2.count(DiffLineKind::Removed) > 0);
    }

    #[test]
    fn kind_histogram_iter_yields_declaration_order() {
        // The histogram's `iter()` walks
        // [`DiffLineKind::ALL`] in declaration order
        // (Removed, Added, Context) regardless of input ordering.
        // Pinned here against an input that observes Context first,
        // then Added, then Removed — the histogram's iteration order
        // is by axis declaration, not by observation order.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c".into()),
                DiffLine::Added("a".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        let pairs: Vec<(DiffLineKind, usize)> = diff.kind_histogram().iter().collect();
        assert_eq!(
            pairs,
            vec![
                (DiffLineKind::Removed, 1),
                (DiffLineKind::Added, 1),
                (DiffLineKind::Context, 1),
            ],
        );
    }

    // ── ConfigDiff::present_kinds — observed-cells peer of
    //    ProvenanceMap::contributing_tiers on the diff altitude ──

    #[test]
    fn present_kinds_matches_kind_histogram_observed_pointwise() {
        // The observed-support pin: `present_kinds` routes through
        // `kind_histogram().observed().collect()`, so the two seams
        // must stay pointwise equivalent under every fixture. Catches
        // any future drift where either implementation stops projecting
        // through the shared cube-native primitive.
        let fixtures: [ConfigDiff; 4] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r1".into()),
                    DiffLine::Added("a1".into()),
                    DiffLine::Added("a2".into()),
                    DiffLine::Context("c1".into()),
                    DiffLine::Context("c2".into()),
                    DiffLine::Context("c3".into()),
                ],
            },
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Removed("r".into())],
            },
        ];
        for diff in fixtures {
            let via_direct = diff.present_kinds();
            let via_histogram: Vec<DiffLineKind> = diff.kind_histogram().observed().collect();
            assert_eq!(
                via_direct, via_histogram,
                "present_kinds must equal kind_histogram().observed().collect() pointwise",
            );
        }
    }

    #[test]
    fn present_kinds_empty_diff_is_empty() {
        // The empty-boundary invariant: a diff with no lines has no
        // present kinds; a diff with any line has ≥1 present kind
        // (every line projects to exactly one kind). Peer of the same
        // empty-boundary pin on `ProvenanceMap::contributing_tiers`
        // and on `ConfigDiff::kind_histogram`.
        let empty = ConfigDiff::default();
        assert!(empty.lines.is_empty());
        assert!(empty.present_kinds().is_empty());
        assert_eq!(empty.present_kinds(), Vec::<DiffLineKind>::new());

        let one_line = ConfigDiff {
            lines: vec![DiffLine::Context("x".into())],
        };
        assert!(!one_line.lines.is_empty());
        assert!(!one_line.present_kinds().is_empty());
    }

    #[test]
    fn present_kinds_iterates_in_declaration_order() {
        // Declaration-order pin: even when the observation order is
        // Context → Added → Removed (the reverse of ::ALL), the
        // returned Vec walks the closed axis in canonical
        // (Removed → Added → Context) order — the closed-axis
        // discipline provides the sort automatically.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c".into()),
                DiffLine::Added("a".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        assert_eq!(
            diff.present_kinds(),
            vec![
                DiffLineKind::Removed,
                DiffLineKind::Added,
                DiffLineKind::Context,
            ],
        );
    }

    #[test]
    fn present_kinds_dedups_across_repeated_observations() {
        // Repeated observations of the same kind collapse to one entry
        // in the returned Vec — the closed-axis discipline provides
        // dedup automatically. Six lines split (2 removed × 3 added ×
        // 1 context) yield three present kinds.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Added("a3".into()),
                DiffLine::Context("c1".into()),
            ],
        };
        assert_eq!(
            diff.present_kinds(),
            vec![
                DiffLineKind::Removed,
                DiffLineKind::Added,
                DiffLineKind::Context,
            ],
        );
    }

    #[test]
    fn present_kinds_context_only_diff_yields_context() {
        // A diff composed only of context lines has exactly Context
        // as its present-kinds set — the changed-cell subset is
        // empty, and `is_empty_diff` returns true concurrently.
        let ctx_only = ConfigDiff {
            lines: vec![
                DiffLine::Context("a".into()),
                DiffLine::Context("b".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(ctx_only.present_kinds(), vec![DiffLineKind::Context]);
        assert!(ctx_only.is_empty_diff());
    }

    #[test]
    fn present_kinds_distinct_cells_matches_histogram() {
        // The support-cardinality invariant: `present_kinds().len()`
        // equals `kind_histogram().distinct_cells()` pointwise. Both
        // project the observed-cell count off the shared histogram
        // over the DiffLineKind closed axis. Peer of the same
        // invariant on `ProvenanceMap::tier_histogram().distinct_cells()
        // == contributing_tiers().len()`.
        let fixtures: [ConfigDiff; 4] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r".into()),
                    DiffLine::Added("a".into()),
                    DiffLine::Context("c".into()),
                ],
            },
        ];
        for diff in fixtures {
            assert_eq!(
                diff.present_kinds().len(),
                diff.kind_histogram().distinct_cells(),
                "present_kinds().len() must equal kind_histogram().distinct_cells()",
            );
        }
    }

    #[test]
    fn present_kinds_changed_subset_agrees_with_is_empty_diff() {
        // Cross-primitive law: the changed-cell subset of
        // `present_kinds()` (Added ∪ Removed) is empty iff
        // `is_empty_diff` returns true. Both surfaces project the
        // same partition over the DiffLineKind axis (`is_changed`),
        // so the agreement is structural.
        let context_only = ConfigDiff {
            lines: vec![DiffLine::Context("c".into())],
        };
        assert!(context_only.is_empty_diff());
        let changed_in_ctx_only: Vec<DiffLineKind> = context_only
            .present_kinds()
            .into_iter()
            .filter(|k| k.is_changed())
            .collect();
        assert!(changed_in_ctx_only.is_empty());

        let with_change = ConfigDiff {
            lines: vec![DiffLine::Context("c".into()), DiffLine::Added("a".into())],
        };
        assert!(!with_change.is_empty_diff());
        let changed_in_mixed: Vec<DiffLineKind> = with_change
            .present_kinds()
            .into_iter()
            .filter(|k| k.is_changed())
            .collect();
        assert!(!changed_in_mixed.is_empty());
        assert!(changed_in_mixed.contains(&DiffLineKind::Added));
    }

    #[test]
    fn present_kinds_is_strictly_ascending_by_axis_ordinal() {
        // Structural-sort pin: the returned Vec is strictly ascending
        // by `crate::axis_ordinal` on DiffLineKind — dedup + sort for
        // free from the closed-axis discipline. Every consecutive pair
        // in the returned Vec has strictly increasing axis ordinal.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c".into()),
                DiffLine::Removed("r".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Added("a".into()),
                DiffLine::Removed("r2".into()),
            ],
        };
        let present = diff.present_kinds();
        for window in present.windows(2) {
            let a = crate::axis_ordinal(window[0]);
            let b = crate::axis_ordinal(window[1]);
            assert!(
                a < b,
                "present_kinds must be strictly ascending by axis_ordinal, \
                 but ord({:?})={a} >= ord({:?})={b}",
                window[0],
                window[1],
            );
        }
    }

    // ── ConfigDiff::absent_kinds — unobserved-cells peer of
    //    present_kinds on the diff altitude ──

    #[test]
    fn absent_kinds_matches_kind_histogram_unobserved_pointwise() {
        // The coverage-gap pin: `absent_kinds` routes through
        // `kind_histogram().unobserved().collect()`, so the two seams
        // must stay pointwise equivalent under every fixture. Catches
        // any future drift where either implementation stops projecting
        // through the shared cube-native primitive. Diff-altitude peer
        // of `absent_tiers_matches_tier_histogram_unobserved_pointwise`
        // on the tier altitude.
        let fixtures: [ConfigDiff; 4] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r1".into()),
                    DiffLine::Added("a1".into()),
                    DiffLine::Added("a2".into()),
                    DiffLine::Context("c1".into()),
                    DiffLine::Context("c2".into()),
                ],
            },
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Removed("r".into())],
            },
        ];
        for diff in fixtures {
            let via_direct = diff.absent_kinds();
            let via_histogram: Vec<DiffLineKind> = diff.kind_histogram().unobserved().collect();
            assert_eq!(
                via_direct, via_histogram,
                "absent_kinds must equal kind_histogram().unobserved().collect() pointwise",
            );
        }
    }

    #[test]
    fn absent_kinds_empty_diff_is_full_axis() {
        // A diff with no lines has no observed kinds — every cell of
        // `DiffLineKind::ALL` lies in the coverage gap. The empty-diff
        // / full-coverage-gap boundary of the observed / unobserved
        // partition, diff-altitude peer of `absent_tiers_empty_map_
        // is_full_axis` on the tier altitude.
        let empty = ConfigDiff::default();
        assert_eq!(empty.absent_kinds(), DiffLineKind::ALL.to_vec());
    }

    #[test]
    fn absent_kinds_iterates_in_declaration_order() {
        // The coverage-gap iter walks `DiffLineKind::ALL` in
        // declaration order (`Removed → Added → Context`) and yields
        // only the cells with zero count. Pinned here on the empty
        // diff, whose gap is the entire axis — the emitted order
        // matches `DiffLineKind::ALL` verbatim.
        let empty = ConfigDiff::default();
        assert_eq!(
            empty.absent_kinds(),
            vec![
                DiffLineKind::Removed,
                DiffLineKind::Added,
                DiffLineKind::Context,
            ],
        );
    }

    #[test]
    fn absent_kinds_context_only_diff_is_added_and_removed() {
        // A diff composed only of Context lines has exactly
        // { Added, Removed } as its coverage gap — the changed-cell
        // subset of the axis is entirely absent, and `is_empty_diff`
        // returns true concurrently. Operator-facing pin on the
        // "nothing changed; only Context lines" render.
        let ctx_only = ConfigDiff {
            lines: vec![
                DiffLine::Context("a".into()),
                DiffLine::Context("b".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(
            ctx_only.absent_kinds(),
            vec![DiffLineKind::Removed, DiffLineKind::Added],
        );
        assert!(ctx_only.is_empty_diff());
    }

    #[test]
    fn absent_kinds_len_matches_unobserved_cells() {
        // The coverage-gap-cardinality invariant on the histogram's
        // support / gap partition: `absent_kinds().len()` equals
        // `kind_histogram().unobserved_cells()` pointwise across every
        // fixture. Any future re-implementation of either seam must
        // keep this equality.
        let fixtures: [ConfigDiff; 5] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r".into()),
                    DiffLine::Added("a".into()),
                    DiffLine::Context("c".into()),
                ],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Added("b".into())],
            },
        ];
        for diff in fixtures {
            assert_eq!(
                diff.absent_kinds().len(),
                diff.kind_histogram().unobserved_cells(),
                "absent_kinds().len() must equal kind_histogram().unobserved_cells()",
            );
        }
    }

    #[test]
    fn absent_kinds_and_present_kinds_partition_axis() {
        // The support / coverage-gap partition on the closed axis:
        // every cell of `DiffLineKind::ALL` lies in exactly one of
        // (observed, unobserved), so the two Vec lengths sum to the
        // axis cardinality. Diff-altitude peer of
        // `absent_tiers_and_contributing_tiers_partition_axis` on the
        // tier altitude.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();
        let fixtures: [ConfigDiff; 5] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r".into()),
                    DiffLine::Added("a".into()),
                    DiffLine::Context("c".into()),
                ],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Added("b".into())],
            },
        ];
        for diff in fixtures {
            let observed = diff.present_kinds();
            let absent = diff.absent_kinds();
            assert_eq!(observed.len() + absent.len(), axis_size);
            for kind in &observed {
                assert!(
                    !absent.contains(kind),
                    "kind {kind:?} appears in both present and absent",
                );
            }
            for cell in DiffLineKind::ALL {
                assert!(
                    observed.contains(cell) || absent.contains(cell),
                    "kind {cell:?} appears in neither present nor absent",
                );
            }
        }
    }

    #[test]
    fn absent_kinds_is_empty_iff_is_full_cover() {
        // The coverage-gap is empty iff every diff-cell kind was
        // observed at least once. Pinned across every fixture in the
        // module against `kind_histogram().is_full_cover()`, plus a
        // direct positive pin: a diff carrying one Removed, one Added,
        // and one Context is full-cover; the coverage-gap is empty.
        let fixtures: [ConfigDiff; 5] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r".into()),
                    DiffLine::Added("a".into()),
                    DiffLine::Context("c".into()),
                ],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Added("b".into())],
            },
        ];
        for diff in fixtures {
            assert_eq!(
                diff.absent_kinds().is_empty(),
                diff.kind_histogram().is_full_cover(),
            );
        }
        let full_cover = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(full_cover.kind_histogram().is_full_cover());
        assert_eq!(full_cover.absent_kinds(), Vec::<DiffLineKind>::new());
        assert_eq!(full_cover.present_kinds(), DiffLineKind::ALL.to_vec());
    }

    #[test]
    fn absent_kinds_is_strictly_ascending_by_axis_ordinal() {
        // Structural sort pin: the coverage-gap walks the closed axis
        // in declaration order, so `absent_kinds()` is strictly
        // ascending by `crate::axis_ordinal` — the dedup + sort every
        // hand-rolled walk would have to spell explicitly comes for
        // free from the closed-axis discipline.
        let fixtures: [ConfigDiff; 5] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Added("b".into())],
            },
        ];
        for diff in fixtures {
            let absent = diff.absent_kinds();
            for pair in absent.windows(2) {
                assert!(
                    crate::axis_ordinal(pair[0]) < crate::axis_ordinal(pair[1]),
                    "absent_kinds must be strictly ascending: {absent:?}",
                );
            }
        }
    }

    #[test]
    fn absent_kinds_full_cover_yields_empty() {
        // The full-cover positive case: a diff containing ≥1 line of
        // every DiffLineKind has an empty coverage gap. Symmetrically,
        // the observed peer equals `DiffLineKind::ALL` (in declaration
        // order) at full cover.
        let full_cover = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(full_cover.kind_histogram().is_full_cover());
        assert_eq!(full_cover.absent_kinds(), Vec::<DiffLineKind>::new());
        assert_eq!(full_cover.present_kinds(), DiffLineKind::ALL.to_vec());
    }

    #[test]
    fn absent_kinds_singleton_diff_yields_two_absent() {
        // A diff of a single line has exactly `axis_cardinality - 1`
        // absent kinds — every axis cell except the one carried by that
        // line. Cross-verified against `present_kinds().len() +
        // absent_kinds().len() == axis_cardinality`. Diff-altitude
        // peer of the singleton pins on the chain-altitude present/
        // absent seams.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();
        for (line, present_kind) in [
            (DiffLine::Removed("r".into()), DiffLineKind::Removed),
            (DiffLine::Added("a".into()), DiffLineKind::Added),
            (DiffLine::Context("c".into()), DiffLineKind::Context),
        ] {
            let diff = ConfigDiff { lines: vec![line] };
            let absent = diff.absent_kinds();
            assert_eq!(absent.len(), axis_size - 1);
            assert!(
                !absent.contains(&present_kind),
                "the observed kind {present_kind:?} must not appear in the coverage gap",
            );
            for cell in DiffLineKind::ALL {
                if *cell != present_kind {
                    assert!(
                        absent.contains(cell),
                        "the singleton diff's coverage gap must contain \
                         every non-observed axis cell — missing {cell:?}",
                    );
                }
            }
        }
    }

    #[test]
    fn absent_kinds_agrees_with_open_coded_coverage_gap_walk() {
        // Parity against the exact `DiffLineKind::ALL.iter().filter(|k|
        // !present_kinds().contains(k))` walk this lift replaces —
        // both the named seam and the hand-rolled coverage-gap must
        // pointwise agree over every fixture. Diff-altitude peer of
        // `absent_tiers_agrees_with_open_coded_coverage_gap_walk` on
        // the tier altitude.
        let fixtures: [ConfigDiff; 6] = [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r".into()),
                    DiffLine::Added("a".into()),
                    DiffLine::Context("c".into()),
                ],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Added("b".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into())],
            },
        ];
        for diff in fixtures {
            let via_seam = diff.absent_kinds();
            let present = diff.present_kinds();
            let hand_rolled: Vec<DiffLineKind> = DiffLineKind::ALL
                .iter()
                .copied()
                .filter(|k| !present.contains(k))
                .collect();
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── ConfigDiff::present_kinds_count — support-size scalar peer of
    //    present_kinds on the diff altitude ──

    fn present_kinds_count_fixtures() -> [ConfigDiff; 6] {
        [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r".into()),
                    DiffLine::Added("a".into()),
                    DiffLine::Context("c".into()),
                ],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into()), DiffLine::Added("b".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r1".into()),
                    DiffLine::Removed("r2".into()),
                    DiffLine::Added("a1".into()),
                    DiffLine::Context("c1".into()),
                ],
            },
        ]
    }

    #[test]
    fn present_kinds_count_matches_kind_histogram_distinct_cells_pointwise() {
        // The support-size pin: `present_kinds_count` routes through
        // `kind_histogram().distinct_cells()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through the
        // shared cube-native primitive. Diff-altitude peer of
        // `contributing_tiers_count_matches_tier_histogram_distinct_cells_pointwise`
        // on the tier altitude.
        for diff in present_kinds_count_fixtures() {
            let via_histogram = diff.kind_histogram().distinct_cells();
            assert_eq!(
                diff.present_kinds_count(),
                via_histogram,
                "present_kinds_count must equal kind_histogram().distinct_cells() pointwise",
            );
        }
    }

    #[test]
    fn present_kinds_count_equals_present_kinds_len_pointwise() {
        // The Vec-peer identity: the scalar-count seam equals the length
        // of the observed-cells `Vec` peer. Any future re-implementation
        // of either seam must keep this equality — pinned uniformly.
        // Diff-altitude peer of
        // `contributing_tiers_count_equals_contributing_tiers_len_pointwise`
        // on the tier altitude.
        for diff in present_kinds_count_fixtures() {
            assert_eq!(diff.present_kinds_count(), diff.present_kinds().len());
        }
    }

    #[test]
    fn present_kinds_count_and_absent_kinds_len_partition_axis_cardinality() {
        // The partition law: the scalar dual of
        // `absent_kinds_and_present_kinds_partition_axis`. Every diff-
        // cell kind lies in exactly one of (observed, unobserved), so the
        // scalar-count peers of the two Vec peers sum to the axis
        // cardinality. Diff-altitude peer of
        // `contributing_tiers_count_and_absent_tiers_len_partition_axis_cardinality`
        // on the tier altitude.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();
        for diff in present_kinds_count_fixtures() {
            assert_eq!(
                diff.present_kinds_count() + diff.absent_kinds().len(),
                axis_size,
            );
        }
    }

    #[test]
    fn present_kinds_count_is_zero_iff_diff_is_empty() {
        // The empty-boundary equivalence: a zero-support diff has zero
        // lines and vice versa (every line projects to exactly one kind,
        // so the histogram support is nonempty iff the line list is).
        // Diff-altitude peer of
        // `contributing_tiers_count_is_zero_iff_map_is_empty` on the tier
        // altitude.
        let empty = ConfigDiff::default();
        assert!(empty.lines.is_empty());
        assert_eq!(empty.present_kinds_count(), 0);

        let one_line = ConfigDiff {
            lines: vec![DiffLine::Context("x".into())],
        };
        assert!(!one_line.lines.is_empty());
        assert!(one_line.present_kinds_count() > 0);

        let with_change = ConfigDiff {
            lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
        };
        assert!(!with_change.lines.is_empty());
        assert!(with_change.present_kinds_count() > 0);
    }

    #[test]
    fn present_kinds_count_is_at_least_one_on_nonempty_diff() {
        // The lower-bound invariant: the support of a non-empty diff
        // carries at least the singleton of the first-line kind. Diff-
        // altitude peer of
        // `contributing_tiers_count_is_at_least_one_on_nonempty_map` on
        // the tier altitude.
        for diff in present_kinds_count_fixtures() {
            if diff.lines.is_empty() {
                continue;
            }
            assert!(diff.present_kinds_count() >= 1);
        }
    }

    #[test]
    fn present_kinds_count_is_bounded_by_axis_cardinality() {
        // The upper-bound invariant: the support of a closed-axis
        // histogram is at most the axis cardinality (the observed-cells
        // set is a subset of `DiffLineKind::ALL`). Diff-altitude peer of
        // `contributing_tiers_count_is_bounded_by_axis_cardinality` on
        // the tier altitude.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();
        for diff in present_kinds_count_fixtures() {
            assert!(diff.present_kinds_count() <= axis_size);
        }
    }

    #[test]
    fn present_kinds_count_is_bounded_by_kind_histogram_total() {
        // The support ≤ total invariant: every distinct cell contributes
        // at least one observation to the total, so the support size is
        // bounded above by the total observation count. Diff-altitude
        // peer of
        // `contributing_tiers_count_is_bounded_by_tier_histogram_total`
        // on the tier altitude.
        for diff in present_kinds_count_fixtures() {
            assert!(diff.present_kinds_count() <= diff.kind_histogram().total());
        }
    }

    #[test]
    fn present_kinds_count_equals_axis_cardinality_iff_is_full_cover() {
        // The full-cover boundary equivalence: the support size equals
        // the axis cardinality iff every diff-cell kind contributed ≥1
        // line iff the coverage gap is empty. Diff-altitude peer of
        // `contributing_tiers_count_equals_axis_cardinality_iff_is_full_cover`
        // on the tier altitude.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();

        // Full-cover: one line per diff-cell kind.
        let axis_cover = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(axis_cover.kind_histogram().is_full_cover());
        assert!(axis_cover.absent_kinds().is_empty());
        assert_eq!(axis_cover.present_kinds_count(), axis_size);

        // Strict-subset: an Added-only diff omits Removed and Context, so
        // full-cover is false and the support size is strictly less than
        // axis size.
        let added_only = ConfigDiff {
            lines: vec![DiffLine::Added("a".into())],
        };
        assert!(!added_only.kind_histogram().is_full_cover());
        assert!(added_only.present_kinds_count() < axis_size);

        // Empty diff: coverage gap is the entire axis, so support size
        // is zero, strictly less than axis size.
        let empty = ConfigDiff::default();
        assert!(!empty.kind_histogram().is_full_cover());
        assert!(empty.present_kinds_count() < axis_size);
    }

    #[test]
    fn present_kinds_count_is_one_iff_has_singular_support() {
        // The singleton-support boundary equivalence: the support size
        // equals 1 iff exactly one diff-cell kind contributed iff the
        // histogram has singular support. Diff-altitude peer of
        // `contributing_tiers_count_is_one_iff_has_singular_support` on
        // the tier altitude.
        let context_only = ConfigDiff {
            lines: vec![DiffLine::Context("a".into()), DiffLine::Context("b".into())],
        };
        assert!(context_only.kind_histogram().has_singular_support());
        assert_eq!(context_only.present_kinds_count(), 1);

        let added_only = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Added("a3".into()),
            ],
        };
        assert!(added_only.kind_histogram().has_singular_support());
        assert_eq!(added_only.present_kinds_count(), 1);

        // Two-kind diff has non-singular support and support size > 1.
        let two_kind = ConfigDiff {
            lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
        };
        assert!(!two_kind.kind_histogram().has_singular_support());
        assert!(two_kind.present_kinds_count() > 1);

        // Empty diff has no support at all: neither singular nor > 1.
        let empty = ConfigDiff::default();
        assert!(!empty.kind_histogram().has_singular_support());
        assert_eq!(empty.present_kinds_count(), 0);
    }

    #[test]
    fn present_kinds_count_of_one_implies_dominant_equals_recessive() {
        // The support-collapse degenerate: a singleton-support diff has
        // the modal and anti-modal cells coincide on the sole observed
        // kind. Diff-altitude peer of
        // `contributing_tiers_count_of_one_implies_dominant_equals_recessive`
        // on the tier altitude.
        let context_only = ConfigDiff {
            lines: vec![DiffLine::Context("a".into()), DiffLine::Context("b".into())],
        };
        assert_eq!(context_only.present_kinds_count(), 1);
        assert_eq!(context_only.dominant_kind(), context_only.recessive_kind());

        let removed_only = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
            ],
        };
        assert_eq!(removed_only.present_kinds_count(), 1);
        assert_eq!(removed_only.dominant_kind(), removed_only.recessive_kind());

        let added_only = ConfigDiff {
            lines: vec![DiffLine::Added("a".into())],
        };
        assert_eq!(added_only.present_kinds_count(), 1);
        assert_eq!(added_only.dominant_kind(), added_only.recessive_kind());
    }

    #[test]
    fn present_kinds_count_agrees_with_open_coded_nonzero_walk() {
        // Parity against the exact `DiffLineKind::ALL.iter().filter(|k|
        // kind_histogram().count(*k) > 0).count()` walk this lift
        // replaces. Diff-altitude peer of
        // `contributing_tiers_count_agrees_with_open_coded_nonzero_walk`
        // on the tier altitude.
        for diff in present_kinds_count_fixtures() {
            let via_seam = diff.present_kinds_count();
            let hist = diff.kind_histogram();
            let hand_rolled = DiffLineKind::ALL
                .iter()
                .filter(|k| hist.count(**k) > 0)
                .count();
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn present_kinds_count_empty_diff_is_zero() {
        // Direct fixture pin: an empty diff has zero-support so
        // `present_kinds_count` reads 0.
        let empty = ConfigDiff::default();
        assert_eq!(empty.present_kinds_count(), 0);
    }

    #[test]
    fn present_kinds_count_full_cover_is_axis_cardinality() {
        // Direct fixture pin: a diff covering every diff-cell kind reads
        // the axis cardinality (3 = |{Removed, Added, Context}|).
        let full_cover = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(
            full_cover.present_kinds_count(),
            crate::axis_cardinality::<DiffLineKind>(),
        );
    }

    #[test]
    fn present_kinds_count_two_kind_diff_is_two() {
        // Direct fixture pin: a diff with two distinct kinds reads 2 —
        // the two-kind support-size witness.
        let two_kind = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
            ],
        };
        assert_eq!(two_kind.present_kinds_count(), 2);
    }

    // ── ConfigDiff::absent_kinds_count — coverage-gap-size scalar peer on the diff altitude ──

    #[test]
    fn absent_kinds_count_matches_kind_histogram_unobserved_cells_pointwise() {
        // The coverage-gap-size pin: `absent_kinds_count` routes through
        // `kind_histogram().unobserved_cells()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Diff-altitude
        // coverage-gap peer of
        // `present_kinds_count_matches_kind_histogram_distinct_cells_pointwise`.
        for diff in present_kinds_count_fixtures() {
            let via_histogram = diff.kind_histogram().unobserved_cells();
            assert_eq!(
                diff.absent_kinds_count(),
                via_histogram,
                "absent_kinds_count must equal kind_histogram().unobserved_cells() pointwise",
            );
        }
    }

    #[test]
    fn absent_kinds_count_equals_absent_kinds_len_pointwise() {
        // The Vec-peer identity: the scalar-count seam equals the length
        // of the coverage-gap `Vec` peer. Any future re-implementation of
        // either seam must keep this equality — pinned uniformly.
        // Diff-altitude coverage-gap peer of
        // `present_kinds_count_equals_present_kinds_len_pointwise`.
        for diff in present_kinds_count_fixtures() {
            assert_eq!(diff.absent_kinds_count(), diff.absent_kinds().len());
        }
    }

    #[test]
    fn present_kinds_count_and_absent_kinds_count_partition_axis_cardinality() {
        // The fully-scalar partition law: both sides now the scalar-count
        // peers, no `.len()` on either. Every diff-cell kind lies in
        // exactly one of (observed, unobserved). The scalar dual of
        // `absent_kinds_and_present_kinds_partition_axis` closed on both
        // sides. Sits alongside
        // `present_kinds_count_and_absent_kinds_len_partition_axis_cardinality`
        // which still uses `.len()` on the coverage-gap side.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();
        for diff in present_kinds_count_fixtures() {
            assert_eq!(
                diff.present_kinds_count() + diff.absent_kinds_count(),
                axis_size,
            );
        }
    }

    #[test]
    fn absent_kinds_count_equals_axis_cardinality_minus_present_kinds_count() {
        // The algebraic rearrangement: the coverage-gap size equals the
        // axis cardinality minus the support size, useful for consumers
        // that already hold the support-size scalar.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();
        for diff in present_kinds_count_fixtures() {
            assert_eq!(
                diff.absent_kinds_count(),
                axis_size - diff.present_kinds_count(),
            );
        }
    }

    #[test]
    fn absent_kinds_count_is_axis_cardinality_iff_diff_is_empty() {
        // The empty-diff / full-coverage-gap boundary equivalence: an
        // empty diff has every kind absent (the coverage gap is the
        // whole axis), and vice versa (every line projects to exactly
        // one kind, so any observed line pulls at least one kind out
        // of the gap). The scalar peer of `absent_kinds() ==
        // DiffLineKind::ALL`.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();

        let empty = ConfigDiff::default();
        assert!(empty.lines.is_empty());
        assert_eq!(empty.absent_kinds_count(), axis_size);

        let one_line = ConfigDiff {
            lines: vec![DiffLine::Context("x".into())],
        };
        assert!(!one_line.lines.is_empty());
        assert!(one_line.absent_kinds_count() < axis_size);

        let with_change = ConfigDiff {
            lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
        };
        assert!(!with_change.lines.is_empty());
        assert!(with_change.absent_kinds_count() < axis_size);
    }

    #[test]
    fn absent_kinds_count_is_zero_iff_is_full_cover() {
        // The full-cover boundary equivalence in coverage-gap form: the
        // coverage gap is empty iff every diff-cell kind contributed ≥1
        // line iff the histogram is full-cover. The diff-altitude
        // scalar-count coverage-gap peer of the
        // `AxisHistogram::is_full_cover` boundary law.

        // Full-cover: one line per diff-cell kind.
        let axis_cover = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(axis_cover.kind_histogram().is_full_cover());
        assert_eq!(axis_cover.absent_kinds_count(), 0);

        // Strict-subset: an Added-only diff omits Removed and Context,
        // so full-cover is false and the coverage gap is nonempty.
        let added_only = ConfigDiff {
            lines: vec![DiffLine::Added("a".into())],
        };
        assert!(!added_only.kind_histogram().is_full_cover());
        assert!(added_only.absent_kinds_count() > 0);

        // Empty diff: coverage gap is the entire axis, so the
        // coverage-gap size is strictly greater than 0.
        let empty = ConfigDiff::default();
        assert!(!empty.kind_histogram().is_full_cover());
        assert!(empty.absent_kinds_count() > 0);
    }

    #[test]
    fn absent_kinds_count_is_bounded_by_axis_cardinality() {
        // The upper-bound invariant: the coverage gap of a closed-axis
        // histogram is at most the axis cardinality (the unobserved-
        // cells set is a subset of `DiffLineKind::ALL`).
        let axis_size = crate::axis_cardinality::<DiffLineKind>();
        for diff in present_kinds_count_fixtures() {
            assert!(diff.absent_kinds_count() <= axis_size);
        }
    }

    #[test]
    fn absent_kinds_count_is_at_least_one_when_not_full_cover() {
        // A non-full-cover diff carries at least one absent kind. The
        // coverage-gap-side lower bound on non-full-cover, dual to
        // `present_kinds_count_is_at_least_one_on_nonempty_diff` on the
        // observed side.
        for diff in present_kinds_count_fixtures() {
            if diff.kind_histogram().is_full_cover() {
                continue;
            }
            assert!(diff.absent_kinds_count() >= 1);
        }
    }

    #[test]
    fn absent_kinds_count_is_axis_cardinality_minus_one_iff_has_singular_support() {
        // The singleton-support boundary in coverage-gap form: when
        // exactly one diff-cell kind is observed, exactly
        // `axis_cardinality - 1` are absent. Diff-altitude coverage-gap
        // peer of `present_kinds_count_is_one_iff_has_singular_support`.
        let axis_size = crate::axis_cardinality::<DiffLineKind>();

        let context_only = ConfigDiff {
            lines: vec![DiffLine::Context("a".into()), DiffLine::Context("b".into())],
        };
        assert!(context_only.kind_histogram().has_singular_support());
        assert_eq!(context_only.absent_kinds_count(), axis_size - 1);

        let added_only = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Added("a3".into()),
            ],
        };
        assert!(added_only.kind_histogram().has_singular_support());
        assert_eq!(added_only.absent_kinds_count(), axis_size - 1);

        // Two-kind diff has non-singular support and coverage gap size
        // strictly less than `axis_cardinality - 1`.
        let two_kind = ConfigDiff {
            lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
        };
        assert!(!two_kind.kind_histogram().has_singular_support());
        assert!(two_kind.absent_kinds_count() < axis_size - 1);

        // Empty diff has no support at all: the coverage gap is the
        // full axis (strictly greater than `axis_cardinality - 1`).
        let empty = ConfigDiff::default();
        assert!(!empty.kind_histogram().has_singular_support());
        assert!(empty.absent_kinds_count() > axis_size - 1);
    }

    #[test]
    fn absent_kinds_count_agrees_with_open_coded_zero_walk() {
        // Parity against the exact `DiffLineKind::ALL.iter().filter(|k|
        // kind_histogram().count(*k) == 0).count()` walk this lift
        // replaces on the coverage-gap side. Diff-altitude coverage-gap
        // peer of `present_kinds_count_agrees_with_open_coded_nonzero_walk`.
        for diff in present_kinds_count_fixtures() {
            let via_seam = diff.absent_kinds_count();
            let hist = diff.kind_histogram();
            let hand_rolled = DiffLineKind::ALL
                .iter()
                .filter(|k| hist.count(**k) == 0)
                .count();
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn absent_kinds_count_empty_diff_is_axis_cardinality() {
        // Direct fixture pin: an empty diff has full coverage gap so
        // `absent_kinds_count` reads the axis cardinality
        // (3 = |{Removed, Added, Context}|).
        let empty = ConfigDiff::default();
        assert_eq!(
            empty.absent_kinds_count(),
            crate::axis_cardinality::<DiffLineKind>(),
        );
    }

    #[test]
    fn absent_kinds_count_full_cover_is_zero() {
        // Direct fixture pin: a diff covering every diff-cell kind has
        // an empty coverage gap so `absent_kinds_count` reads 0.
        let full_cover = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(full_cover.absent_kinds_count(), 0);
    }

    #[test]
    fn absent_kinds_count_two_kind_diff_is_one() {
        // Direct fixture pin: a diff with two distinct kinds leaves
        // exactly one kind absent — the coverage-gap complement of the
        // two-kind support-size witness.
        let two_kind = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
            ],
        };
        assert_eq!(two_kind.absent_kinds_count(), 1);
    }

    // ── ConfigDiff::dominant_kind — modal-cell scalar peer on the diff altitude ──

    fn dominant_kind_fixtures() -> [ConfigDiff; 8] {
        [
            ConfigDiff::default(),
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Context("c".into())],
            },
            ConfigDiff {
                lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Removed("r".into()),
                    DiffLine::Added("a".into()),
                    DiffLine::Context("c".into()),
                ],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Added("a".into()),
                    DiffLine::Added("b".into()),
                    DiffLine::Context("c".into()),
                ],
            },
            ConfigDiff {
                lines: vec![
                    DiffLine::Context("c1".into()),
                    DiffLine::Context("c2".into()),
                    DiffLine::Context("c3".into()),
                    DiffLine::Removed("r".into()),
                ],
            },
        ]
    }

    #[test]
    fn dominant_kind_matches_kind_histogram_dominant_cell_pointwise() {
        // The modal-cell pin: `dominant_kind` routes through
        // `kind_histogram().dominant_cell()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Diff-altitude peer
        // of `dominant_tier_matches_tier_histogram_dominant_cell_pointwise`
        // on the tier altitude.
        for diff in dominant_kind_fixtures() {
            let via_histogram = diff.kind_histogram().dominant_cell();
            assert_eq!(diff.dominant_kind(), via_histogram);
        }
    }

    #[test]
    fn dominant_kind_context_dominated_fixture_is_context() {
        // Direct pin: a diff of 3 Context + 1 Removed has Context
        // uniquely dominant with 3 of 4 lines. The named seam answers
        // the operator's *"which diff kind dominated this render?"*
        // question at one call, no `max_by_key` walk in the summary.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        assert_eq!(diff.dominant_kind(), Some(DiffLineKind::Context));
    }

    #[test]
    fn dominant_kind_added_dominated_fixture_is_added() {
        // Direct pin: a diff of 2 Added + 1 Context has Added uniquely
        // dominant with 2 of 3 lines. Cross-verified against the
        // per-kind count directly on the underlying histogram.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(diff.dominant_kind(), Some(DiffLineKind::Added));
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Added), 2);
        assert_eq!(hist.peak_count(), 2);
    }

    #[test]
    fn dominant_kind_empty_diff_is_none() {
        // An empty ConfigDiff has no lines and therefore no modal cell —
        // the empty-diff / empty-histogram boundary of the dominant-cell
        // projection. Diff-altitude peer of `dominant_tier_empty_map_is_none`
        // and the empty-diff boundary on the coverage-gap side
        // (`absent_kinds` returns `DiffLineKind::ALL`).
        let empty = ConfigDiff::default();
        assert_eq!(empty.dominant_kind(), None);
        assert!(empty.lines.is_empty());
    }

    #[test]
    fn dominant_kind_is_some_iff_diff_is_nonempty() {
        // Cross-surface pin: the presence-of-modal-cell predicate
        // agrees with the non-emptiness of `self.lines`. Structural
        // completeness of the `(is_empty, dominant_kind)` boundary — a
        // well-formed diff with ≥1 line always has a modal cell, and an
        // empty diff never does.
        for diff in dominant_kind_fixtures() {
            assert_eq!(diff.dominant_kind().is_some(), !diff.lines.is_empty());
        }
    }

    #[test]
    fn dominant_kind_is_member_of_present_kinds() {
        // Structural pin: whenever `dominant_kind()` is `Some(k)`, `k`
        // must appear in `present_kinds()` (the modal cell is by
        // definition observed). The support / dominance partition on
        // the diff altitude reads consistently between the two named
        // seams. Diff-altitude peer of
        // `dominant_tier_is_member_of_contributing_tiers`.
        for diff in dominant_kind_fixtures() {
            let Some(dominant) = diff.dominant_kind() else {
                continue;
            };
            assert!(
                diff.present_kinds().contains(&dominant),
                "dominant kind {dominant:?} must appear in present_kinds",
            );
        }
    }

    #[test]
    fn dominant_kind_is_not_member_of_absent_kinds() {
        // Structural pin: whenever `dominant_kind()` is `Some(k)`, `k`
        // must NOT appear in `absent_kinds()` — the modal cell lies on
        // the observed side of the observed / coverage-gap partition.
        // Disjointness pin between the two named seams. Diff-altitude
        // peer of `dominant_tier_is_not_member_of_absent_tiers`.
        for diff in dominant_kind_fixtures() {
            let Some(dominant) = diff.dominant_kind() else {
                continue;
            };
            assert!(
                !diff.absent_kinds().contains(&dominant),
                "dominant kind {dominant:?} must not appear in absent_kinds",
            );
        }
    }

    #[test]
    fn dominant_kind_count_equals_peak_count_on_nonempty_diff() {
        // The (dominant_cell, peak_count) modal-pair invariant lifted
        // to the diff altitude: the observation count of the dominant
        // kind equals the histogram's peak count. Pins the fused form
        // of the modal-pair the AxisHistogram surface carries as
        // (dominant_cell(), peak_count()).
        for diff in dominant_kind_fixtures() {
            let Some(dominant) = diff.dominant_kind() else {
                continue;
            };
            let hist = diff.kind_histogram();
            assert_eq!(hist.count(dominant), hist.peak_count());
        }
    }

    #[test]
    fn dominant_kind_ties_broken_by_declaration_order() {
        // Structural tie-breaking pin: on a uniform per-kind diff
        // (each of the three `DiffLineKind` cells contributing exactly
        // one line), `dominant_kind` reports `Some(DiffLineKind::Removed)`
        // — the first cell in `DiffLineKind::ALL` declaration order.
        // Any future switch to a nondeterministic `max_by_key` walk
        // (which silently picks the LAST tied cell) would flip this
        // pin to `Some(Context)` — the seam names the tiebreak once.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Removed), 1);
        assert_eq!(hist.count(DiffLineKind::Added), 1);
        assert_eq!(hist.count(DiffLineKind::Context), 1);
        assert!(hist.is_full_cover());
        // Tiebreak lands on the first cell in declaration order.
        assert_eq!(diff.dominant_kind(), Some(DiffLineKind::Removed));
    }

    #[test]
    fn dominant_kind_two_way_tie_picks_declaration_order_first() {
        // A two-way tie between Added and Context (2 each) with no
        // Removed lines must still resolve to the declaration-order
        // earliest cell — Added (which precedes Context in ALL) —
        // even though Removed has zero count. Distinguishes the
        // "first tied cell" tiebreak from a naive "first cell of ALL"
        // fallback.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
            ],
        };
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Removed), 0);
        assert_eq!(hist.count(DiffLineKind::Added), 2);
        assert_eq!(hist.count(DiffLineKind::Context), 2);
        assert_eq!(diff.dominant_kind(), Some(DiffLineKind::Added));
    }

    #[test]
    fn dominant_kind_agrees_with_open_coded_argmax_walk() {
        // Parity against the exact `hist.iter().filter(|&(_, c)| c > 0)
        // .fold(count-then-declaration-order)` walk this lift replaces —
        // both the named seam and the hand-rolled argmax must
        // pointwise agree over every fixture. The hand-rolled form
        // spells the declaration-order tiebreak explicitly (fold-
        // forward with strict `>` inequality — the first tied cell
        // wins, mirroring `AxisHistogram::dominant_cell` — rather than
        // `max_by_key`'s LAST-tied-cell semantics). Diff-altitude peer
        // of `dominant_tier_agrees_with_open_coded_argmax_walk`.
        for diff in dominant_kind_fixtures() {
            let via_seam = diff.dominant_kind();
            let hist = diff.kind_histogram();
            let mut iter = hist.iter().filter(|&(_, c)| c > 0);
            let hand_rolled = iter.next().map(|first| {
                iter.fold(
                    first,
                    |best, current| {
                        if current.1 > best.1 { current } else { best }
                    },
                )
                .0
            });
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn dominant_kind_uniform_cover_picks_first_cell() {
        // Trait-uniform invariant: on a full-cover diff where every
        // kind observes the same nonzero count (2 each here), the
        // dominant cell is the first cell of `DiffLineKind::ALL` — the
        // declaration-order tiebreak reduces to `Some(Removed)`. Peer
        // of the trait-uniform
        // `axis_histogram_dominant_cell_axis_cover_picks_first_*` laws
        // in cube tests, and of
        // `dominant_tier_uniform_cover_picks_first_cell` on the tier
        // altitude.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
            ],
        };
        assert!(diff.kind_histogram().is_full_cover());
        assert_eq!(diff.dominant_kind(), Some(DiffLineKind::Removed));
    }

    // ── ConfigDiff::peak_kind_count — modal-count scalar peer on the diff altitude ──

    #[test]
    fn peak_kind_count_matches_kind_histogram_peak_count_pointwise() {
        // The modal-count pin: `peak_kind_count` routes through
        // `kind_histogram().peak_count()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through the
        // shared cube-native primitive. Diff-altitude peer of
        // `peak_tier_count_matches_tier_histogram_peak_count_pointwise`
        // on the tier altitude.
        for diff in dominant_kind_fixtures() {
            let via_histogram = diff.kind_histogram().peak_count();
            assert_eq!(diff.peak_kind_count(), via_histogram);
        }
    }

    #[test]
    fn peak_kind_count_context_dominated_fixture_is_three() {
        // Direct pin: a diff of 3 Context + 1 Removed has Context
        // uniquely dominant with 3 of 4 lines — the peak count is 3.
        // Peer of `dominant_kind_context_dominated_fixture_is_context`
        // reading the paired `(dominant_kind, peak_kind_count)` modal
        // scalar as `(Some(Context), 3)`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        assert_eq!(diff.dominant_kind(), Some(DiffLineKind::Context));
        assert_eq!(diff.peak_kind_count(), 3);
    }

    #[test]
    fn peak_kind_count_added_dominated_fixture_is_two() {
        // Direct pin: a diff of 2 Added + 1 Context has Added uniquely
        // dominant with 2 of 3 lines — the peak count is 2. Peer of
        // `dominant_kind_added_dominated_fixture_is_added` reading the
        // paired `(dominant_kind, peak_kind_count)` modal scalar as
        // `(Some(Added), 2)`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(diff.dominant_kind(), Some(DiffLineKind::Added));
        assert_eq!(diff.peak_kind_count(), 2);
    }

    #[test]
    fn peak_kind_count_empty_diff_is_zero() {
        // An empty ConfigDiff has no lines and therefore no peak count —
        // reads `0` per the [`crate::AxisHistogram::peak_count`] and
        // [`crate::ProvenanceMap::peak_tier_count`] empty conventions
        // (not `Option<usize>`; the scalar projection reads zero on
        // empty, and the dual-form [`Self::dominant_kind`] on the cell
        // side reads `None` — the asymmetry between scalar and cell
        // projections on the empty boundary is intentional). The fused
        // `(dominant_kind, peak_kind_count)` modal scalar pair reads
        // `(None, 0)` uniformly on the empty diff.
        let empty = ConfigDiff::default();
        assert_eq!(empty.dominant_kind(), None);
        assert_eq!(empty.peak_kind_count(), 0);
        assert!(empty.lines.is_empty());
    }

    #[test]
    fn peak_kind_count_is_zero_iff_diff_is_empty() {
        // Cross-surface pin: the zero-of-peak-count predicate agrees
        // with the emptiness of `self.lines`. Structural completeness of
        // the `(is_empty, peak_kind_count)` boundary — a well-formed
        // diff with ≥1 line always has a positive peak, and an empty
        // diff always reads zero. Peer of
        // `peak_tier_count_is_zero_iff_map_is_empty` on the tier
        // altitude.
        for diff in dominant_kind_fixtures() {
            assert_eq!(diff.peak_kind_count() == 0, diff.lines.is_empty());
        }
    }

    #[test]
    fn peak_kind_count_equals_count_at_dominant_kind_on_nonempty_diff() {
        // The (dominant_cell, peak_count) modal-pair identity lifted to
        // the diff altitude: `peak_kind_count == count(dominant_kind)`
        // whenever the diff is non-empty. Pins the ProvenanceMap-side
        // identity of the fused-pair seam; peer of
        // `dominant_kind_count_equals_peak_count_on_nonempty_diff`
        // (which pins the histogram-side identity in terms of
        // `hist.count(dominant)` and `hist.peak_count()`).
        for diff in dominant_kind_fixtures() {
            let Some(dominant) = diff.dominant_kind() else {
                continue;
            };
            let hist = diff.kind_histogram();
            assert_eq!(hist.count(dominant), diff.peak_kind_count());
        }
    }

    #[test]
    fn peak_kind_count_equals_dominant_kind_map_or_count() {
        // Fused-pair boundary-complete pin: `peak_kind_count() ==
        // dominant_kind().map_or(0, |k| kind_histogram().count(k))` on
        // every fixture — including the empty-diff convention where
        // `None.map_or(0, …) == 0 == peak_kind_count`. The full identity
        // of the `(dominant_kind, peak_kind_count)` modal pair across
        // the empty / non-empty partition. Peer of
        // `peak_tier_count_equals_dominant_tier_map_or_count` on the
        // tier altitude.
        for diff in dominant_kind_fixtures() {
            let hist = diff.kind_histogram();
            let via_pair = diff.dominant_kind().map_or(0, |k| hist.count(k));
            assert_eq!(diff.peak_kind_count(), via_pair);
        }
    }

    #[test]
    fn peak_kind_count_bounded_above_by_lines_len() {
        // The peak is bounded above by the total line count on every
        // diff: `peak_kind_count() <= self.lines.len()`. Every kind
        // contributes at most every line, and the others contribute
        // zero. Peer of `peak_tier_count_bounded_above_by_len` on the
        // tier altitude reading the same bound against `map.len()`.
        for diff in dominant_kind_fixtures() {
            assert!(
                diff.peak_kind_count() <= diff.lines.len(),
                "peak_kind_count {} must not exceed lines.len() {}",
                diff.peak_kind_count(),
                diff.lines.len(),
            );
        }
    }

    #[test]
    fn peak_kind_count_equals_lines_len_iff_at_most_one_present_kind() {
        // Equality case of the `peak_kind_count() <= lines.len()`
        // bound: `peak == len` iff `present_kinds().len() <= 1`. Zero
        // present kinds (empty diff) reads `0 == 0`; one present kind
        // reads `N == N`; two or more reads `peak < total` strictly.
        // Peer of `peak_tier_count_equals_len_iff_at_most_one_contributing_tier`
        // on the tier altitude.
        for diff in dominant_kind_fixtures() {
            let peak_eq_len = diff.peak_kind_count() == diff.lines.len();
            let support_le_one = diff.present_kinds().len() <= 1;
            assert_eq!(
                peak_eq_len,
                support_le_one,
                "peak_kind_count == lines.len() must agree with present_kinds().len() <= 1 \
                 for diff with peak={peak_kind}, len={line_count}, present={present:?}",
                peak_kind = diff.peak_kind_count(),
                line_count = diff.lines.len(),
                present = diff.present_kinds(),
            );
        }
    }

    #[test]
    fn peak_kind_count_is_at_least_one_on_nonempty_diff() {
        // The lower bound peer: a non-empty diff always has a peak
        // count of at least one line — the dominant kind carries at
        // least the single line witnessing non-emptiness. Together with
        // the `<= lines.len()` upper bound: `1 <= peak_kind_count <=
        // lines.len()` on every non-empty diff. Peer of
        // `peak_tier_count_is_at_least_one_on_nonempty_map` on the tier
        // altitude.
        for diff in dominant_kind_fixtures() {
            if diff.lines.is_empty() {
                continue;
            }
            assert!(
                diff.peak_kind_count() >= 1,
                "non-empty diff must have peak_kind_count >= 1, got {}",
                diff.peak_kind_count(),
            );
        }
    }

    #[test]
    fn peak_kind_count_uniform_cover_is_one() {
        // Trait-uniform invariant: on a uniform per-kind diff (one line
        // per kind, three lines total), every observed kind collects
        // one line, dominant included — the peak count reads `1`. Peer
        // of `peak_tier_count_uniform_cover_is_one` on the tier altitude
        // and diff-altitude peer of the AxisHistogram trait-uniform
        // `peak_count == 1` law on the singleton-per-cell degenerate.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(diff.kind_histogram().is_full_cover());
        assert_eq!(diff.peak_kind_count(), 1);
    }

    #[test]
    fn peak_kind_count_singleton_support_equals_lines_len() {
        // Singleton-support pin: every line lands on the same kind, so
        // the dominant kind collects every line and `peak_kind_count ==
        // lines.len()`. Peer of
        // `peak_tier_count_singleton_support_equals_len` on the tier
        // altitude reading the same equality against `map.len()`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Removed("r3".into()),
                DiffLine::Removed("r4".into()),
            ],
        };
        assert_eq!(diff.present_kinds().len(), 1);
        assert_eq!(diff.peak_kind_count(), 4);
        assert_eq!(diff.peak_kind_count(), diff.lines.len());
    }

    #[test]
    fn peak_kind_count_agrees_with_open_coded_max_over_axis_walk() {
        // Parity against the exact `hist.iter().map(|(_, c)| c).max()
        // .unwrap_or(0)` walk this lift replaces — the named seam and
        // the hand-rolled argmax must pointwise agree over every
        // fixture. The `.unwrap_or(0)` names the empty-diff convention
        // (`max()` over an empty iterator returns `None`, but the
        // histogram's counts vector is fixed-cardinality so the iter
        // is always non-empty; the `unwrap_or(0)` is a safety belt for
        // the trait-uniform empty-axis edge). Peer of
        // `peak_tier_count_agrees_with_open_coded_max_over_axis_walk`
        // on the tier altitude.
        for diff in dominant_kind_fixtures() {
            let via_seam = diff.peak_kind_count();
            let hist = diff.kind_histogram();
            let hand_rolled = hist.iter().map(|(_, c)| c).max().unwrap_or(0);
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── ConfigDiff::recessive_kind — anti-modal-cell scalar peer on the diff altitude ──

    #[test]
    fn recessive_kind_matches_kind_histogram_recessive_cell_pointwise() {
        // The anti-modal-cell pin: `recessive_kind` routes through
        // `kind_histogram().recessive_cell()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Diff-altitude peer
        // of `recessive_tier_matches_tier_histogram_recessive_cell_pointwise`
        // on the tier altitude, and dominant-side peer of
        // `dominant_kind_matches_kind_histogram_dominant_cell_pointwise`.
        for diff in dominant_kind_fixtures() {
            let via_histogram = diff.kind_histogram().recessive_cell();
            assert_eq!(diff.recessive_kind(), via_histogram);
        }
    }

    #[test]
    fn recessive_kind_context_dominated_fixture_is_removed() {
        // A diff of 3 Context + 1 Removed has counts Removed=1,
        // Added=0, Context=3 over the axis. The argmin over the
        // support {Removed, Context} is uniquely Removed at count 1 —
        // no tie, no declaration-order fallback needed. The named seam
        // answers the operator's *"which diff kind is the runt of this
        // render?"* question at one call, no `min_by_key` walk in the
        // summary.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Removed));
    }

    #[test]
    fn recessive_kind_added_dominated_fixture_is_context() {
        // A diff of 2 Added + 1 Context has counts Removed=0, Added=2,
        // Context=1 over the axis. The argmin over the support
        // {Added, Context} is uniquely Context at count 1 — no tie.
        // Cross-verified against the per-kind count directly on the
        // underlying histogram.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Context));
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Context), 1);
        assert_eq!(hist.trough_count(), 1);
    }

    #[test]
    fn recessive_kind_empty_diff_is_none() {
        // An empty ConfigDiff has no lines and therefore no anti-modal
        // cell — the empty-diff / empty-histogram boundary of the
        // recessive-cell projection. Diff-altitude peer of
        // `recessive_tier_empty_map_is_none` on the tier altitude, and
        // dominant-side peer of `dominant_kind_empty_diff_is_none`.
        let empty = ConfigDiff::default();
        assert_eq!(empty.recessive_kind(), None);
        assert!(empty.lines.is_empty());
    }

    #[test]
    fn recessive_kind_is_some_iff_diff_is_nonempty() {
        // Cross-surface pin: the presence-of-anti-modal-cell predicate
        // agrees with the non-emptiness of `self.lines`. Structural
        // completeness of the `(is_empty, recessive_kind)` boundary —
        // a well-formed diff with ≥1 line always has an anti-modal
        // cell, and an empty diff never does. Peer of
        // `dominant_kind_is_some_iff_diff_is_nonempty`.
        for diff in dominant_kind_fixtures() {
            assert_eq!(diff.recessive_kind().is_some(), !diff.lines.is_empty());
        }
    }

    #[test]
    fn recessive_kind_is_some_iff_dominant_kind_is_some() {
        // Cross-projection pin lifted from the trait-uniform
        // `recessive_cell().is_some() == dominant_cell().is_some()` law
        // on AxisHistogram: both projections operate over the same
        // nonzero support, so they agree on presence at every input.
        // Diff-altitude peer of
        // `recessive_tier_is_some_iff_dominant_tier_is_some`.
        for diff in dominant_kind_fixtures() {
            assert_eq!(
                diff.recessive_kind().is_some(),
                diff.dominant_kind().is_some(),
            );
        }
    }

    #[test]
    fn recessive_kind_is_member_of_present_kinds() {
        // Structural pin: whenever `recessive_kind()` is `Some(k)`, `k`
        // must appear in `present_kinds()` (the anti-modal cell is
        // taken over the support, so it is by definition observed).
        // The support / anti-modal-cell partition on the diff altitude
        // reads consistently between the two named seams. Diff-altitude
        // peer of `recessive_tier_is_member_of_contributing_tiers`.
        for diff in dominant_kind_fixtures() {
            let Some(recessive) = diff.recessive_kind() else {
                continue;
            };
            assert!(
                diff.present_kinds().contains(&recessive),
                "recessive kind {recessive:?} must appear in present_kinds",
            );
        }
    }

    #[test]
    fn recessive_kind_is_not_member_of_absent_kinds() {
        // Structural pin: whenever `recessive_kind()` is `Some(k)`, `k`
        // must NOT appear in `absent_kinds()` — the anti-modal cell
        // lies on the observed side of the observed / coverage-gap
        // partition by construction (argmin taken over the nonzero
        // support). Disjointness pin between the two named seams.
        // Diff-altitude peer of
        // `recessive_tier_is_not_member_of_absent_tiers`.
        for diff in dominant_kind_fixtures() {
            let Some(recessive) = diff.recessive_kind() else {
                continue;
            };
            assert!(
                !diff.absent_kinds().contains(&recessive),
                "recessive kind {recessive:?} must not appear in absent_kinds",
            );
        }
    }

    #[test]
    fn recessive_kind_count_equals_trough_count_on_nonempty_diff() {
        // The (recessive_cell, trough_count) anti-modal-pair invariant
        // lifted to the diff altitude: the observation count of the
        // recessive kind equals the histogram's trough count over the
        // support. Peer of
        // `recessive_tier_count_equals_trough_count_on_nonempty_map` on
        // the tier altitude, and dominant-side peer of
        // `dominant_kind_count_equals_peak_count_on_nonempty_diff`.
        for diff in dominant_kind_fixtures() {
            let Some(recessive) = diff.recessive_kind() else {
                continue;
            };
            let hist = diff.kind_histogram();
            assert_eq!(hist.count(recessive), hist.trough_count());
        }
    }

    #[test]
    fn recessive_kind_count_bounded_by_dominant_kind_count() {
        // Structural bound lifted from the trait-uniform
        // `count(recessive_cell) <= count(dominant_cell)` law on
        // AxisHistogram: the trough-of-support is bounded above by the
        // peak-of-support at every fixture. Cross-projection pin
        // between `recessive_kind` and `dominant_kind`. Diff-altitude
        // peer of `recessive_tier_count_bounded_by_dominant_tier_count`.
        for diff in dominant_kind_fixtures() {
            let Some(recessive) = diff.recessive_kind() else {
                continue;
            };
            let Some(dominant) = diff.dominant_kind() else {
                unreachable!("presence of recessive kind implies presence of dominant kind");
            };
            let hist = diff.kind_histogram();
            assert!(
                hist.count(recessive) <= hist.count(dominant),
                "count(recessive={recessive:?})={r} must be <= count(dominant={dominant:?})={d}",
                r = hist.count(recessive),
                d = hist.count(dominant),
            );
        }
    }

    #[test]
    fn recessive_kind_ties_broken_by_declaration_order() {
        // Structural tie-breaking pin: on a uniform per-kind diff
        // (each of the three `DiffLineKind` cells contributing exactly
        // one line), `recessive_kind` reports
        // `Some(DiffLineKind::Removed)` — the first cell in
        // `DiffLineKind::ALL` declaration order (the singleton-modality
        // degenerate where the modal and anti-modal cells coincide).
        // Any future switch to a nondeterministic `min_by_key` walk
        // over the full axis (which would silently pick a zero-count
        // cell over the closed axis) would flip this pin — the seam
        // names the tiebreak once. Peer of
        // `recessive_tier_ties_broken_by_declaration_order`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Removed), 1);
        assert_eq!(hist.count(DiffLineKind::Added), 1);
        assert_eq!(hist.count(DiffLineKind::Context), 1);
        assert!(hist.is_full_cover());
        // Tiebreak lands on the first cell in declaration order —
        // pointwise identical to `dominant_kind` on the same uniform
        // input (the singleton-modality degenerate).
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Removed));
        assert_eq!(diff.recessive_kind(), diff.dominant_kind());
    }

    #[test]
    fn recessive_kind_two_way_tie_picks_declaration_order_first() {
        // A two-way tie between Removed and Added (1 each) with 3
        // Context lines must resolve to the declaration-order earliest
        // cell — Removed (which precedes Added in ALL) — not to Added
        // (which `min_by_key`'s FIRST-tied-cell semantics would agree
        // with by coincidence, but which any reversed comparison would
        // silently break). The argmin over the support {Removed,
        // Added, Context} respects declaration order at the trough.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
            ],
        };
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Removed), 1);
        assert_eq!(hist.count(DiffLineKind::Added), 1);
        assert_eq!(hist.count(DiffLineKind::Context), 3);
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Removed));
    }

    #[test]
    fn recessive_kind_singleton_support_agrees_with_dominant_kind() {
        // Singleton-support degenerate lifted from the trait-uniform
        // `distinct_cells() == 1 → dominant_cell() == recessive_cell()`
        // law on AxisHistogram: when only one kind contributes, that
        // kind is both the modal and the anti-modal cell. Direct
        // construction: three lines, all Added. Peer of
        // `recessive_tier_singleton_support_agrees_with_dominant_tier`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Added("a3".into()),
            ],
        };
        assert_eq!(diff.present_kinds().len(), 1);
        assert_eq!(diff.recessive_kind(), diff.dominant_kind());
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Added));
    }

    #[test]
    fn recessive_kind_agrees_with_open_coded_argmin_walk() {
        // Parity against the exact `hist.iter().filter(|&(_, c)| c > 0)
        // .fold(count-then-declaration-order)` walk this lift replaces —
        // both the named seam and the hand-rolled argmin must
        // pointwise agree over every fixture. The hand-rolled form
        // spells the declaration-order tiebreak explicitly (fold-
        // forward with strict `<` inequality — the first tied cell
        // wins, mirroring `AxisHistogram::recessive_cell`, rather than
        // `min_by_key`'s FIRST-tied-cell semantics which agrees by
        // coincidence but drifts under any reversed comparison).
        // Diff-altitude peer of
        // `recessive_tier_agrees_with_open_coded_argmin_walk`.
        for diff in dominant_kind_fixtures() {
            let via_seam = diff.recessive_kind();
            let hist = diff.kind_histogram();
            let mut iter = hist.iter().filter(|&(_, c)| c > 0);
            let hand_rolled = iter.next().map(|first| {
                iter.fold(
                    first,
                    |best, current| {
                        if current.1 < best.1 { current } else { best }
                    },
                )
                .0
            });
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn recessive_kind_uniform_cover_picks_first_cell() {
        // Trait-uniform invariant: on a full-cover diff where every
        // kind observes the same nonzero count (2 each here), the
        // recessive cell is the first cell of `DiffLineKind::ALL` —
        // the declaration-order tiebreak reduces to `Some(Removed)`,
        // pointwise identical to `dominant_kind` on the same input
        // (the singleton-modality degenerate). Peer of the
        // trait-uniform
        // `axis_histogram_dominant_and_recessive_agree_on_uniform_axis_cover_for_every_implementor`
        // law in cube tests.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
            ],
        };
        assert!(diff.kind_histogram().is_full_cover());
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Removed));
        assert_eq!(diff.recessive_kind(), diff.dominant_kind());
    }

    // ── ConfigDiff::trough_kind_count — anti-modal-count scalar peer on the
    //    diff altitude, fusing with recessive_kind into the (cell, count)
    //    anti-modal pair and closing the (dominant, recessive) × (cell, count)
    //    2×2 scalar grid on the diff altitude ──

    #[test]
    fn trough_kind_count_matches_kind_histogram_trough_count_pointwise() {
        // The scalar-count pin: `trough_kind_count` routes through
        // `kind_histogram().trough_count()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through the
        // shared cube-native primitive. Diff-altitude peer of
        // `trough_tier_count_matches_tier_histogram_trough_count_pointwise`
        // on the tier altitude, and count-side dual of
        // `recessive_kind_matches_kind_histogram_recessive_cell_pointwise`
        // on the diff altitude.
        for diff in dominant_kind_fixtures() {
            let via_histogram = diff.kind_histogram().trough_count();
            assert_eq!(diff.trough_kind_count(), via_histogram);
        }
    }

    #[test]
    fn trough_kind_count_context_dominated_fixture_is_one() {
        // Direct pin: a diff of 3 Context + 1 Removed has Removed
        // uniquely rarest with 1 of 4 lines — the trough count is 1.
        // Peer of `recessive_kind_context_dominated_fixture_is_removed`
        // reading the paired `(recessive_kind, trough_kind_count)`
        // anti-modal scalar as `(Some(Removed), 1)`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Removed));
        assert_eq!(diff.trough_kind_count(), 1);
    }

    #[test]
    fn trough_kind_count_added_dominated_fixture_is_one() {
        // Direct pin: a diff of 2 Added + 1 Context has Context uniquely
        // rarest with 1 of 3 lines — the trough count is 1. Peer of
        // `recessive_kind_added_dominated_fixture_is_context` reading
        // the paired `(recessive_kind, trough_kind_count)` anti-modal
        // scalar as `(Some(Context), 1)`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(diff.recessive_kind(), Some(DiffLineKind::Context));
        assert_eq!(diff.trough_kind_count(), 1);
    }

    #[test]
    fn trough_kind_count_empty_diff_is_zero() {
        // An empty ConfigDiff has no lines and therefore no trough
        // count — reads `0` per the [`crate::AxisHistogram::trough_count`]
        // and [`crate::ProvenanceMap::trough_tier_count`] empty
        // conventions (not `Option<usize>`; the scalar projection reads
        // zero on empty, and the dual-form [`Self::recessive_kind`] on
        // the cell side reads `None` — the asymmetry between scalar and
        // cell projections on the empty boundary is intentional). The
        // fused quad `(dominant_kind, peak_kind_count, recessive_kind,
        // trough_kind_count)` reads `(None, 0, None, 0)` uniformly on
        // the empty diff.
        let empty = ConfigDiff::default();
        assert_eq!(empty.recessive_kind(), None);
        assert_eq!(empty.trough_kind_count(), 0);
        assert!(empty.lines.is_empty());
    }

    #[test]
    fn trough_kind_count_is_zero_iff_diff_is_empty() {
        // Cross-surface pin: the zero-of-trough-count predicate agrees
        // with the emptiness of `self.lines`. Structural completeness of
        // the `(is_empty, trough_kind_count == 0)` boundary — a
        // well-formed diff with ≥1 line always has a positive trough
        // (the argmin is taken over the *support*), and an empty diff
        // always reads zero. Peer of
        // `trough_tier_count_is_zero_iff_map_is_empty` on the tier
        // altitude and count-side dual of
        // `recessive_kind_is_some_iff_diff_is_nonempty` on the diff
        // altitude.
        for diff in dominant_kind_fixtures() {
            assert_eq!(diff.trough_kind_count() == 0, diff.lines.is_empty());
        }
    }

    #[test]
    fn trough_kind_count_equals_count_at_recessive_kind_on_nonempty_diff() {
        // The (recessive_cell, trough_count) anti-modal-pair identity
        // lifted to the diff altitude: `trough_kind_count ==
        // count(recessive_kind)` whenever the diff is non-empty. Pins
        // the ConfigDiff-side identity of the fused-pair seam; peer of
        // `recessive_kind_count_equals_trough_count_on_nonempty_diff`
        // (which pins the histogram-side identity in terms of
        // `hist.count(recessive)` and `hist.trough_count()`).
        for diff in dominant_kind_fixtures() {
            let Some(recessive) = diff.recessive_kind() else {
                continue;
            };
            let hist = diff.kind_histogram();
            assert_eq!(hist.count(recessive), diff.trough_kind_count());
        }
    }

    #[test]
    fn trough_kind_count_equals_recessive_kind_map_or_count() {
        // Fused-pair boundary-complete pin: `trough_kind_count() ==
        // recessive_kind().map_or(0, |k| kind_histogram().count(k))` on
        // every fixture — including the empty-diff convention where
        // `None.map_or(0, …) == 0 == trough_kind_count`. The full
        // identity of the `(recessive_kind, trough_kind_count)`
        // anti-modal pair across the empty / non-empty partition. Peer
        // of `trough_tier_count_equals_recessive_tier_map_or_count` on
        // the tier altitude and diff-altitude count-side dual of
        // `peak_kind_count_equals_dominant_kind_map_or_count`.
        for diff in dominant_kind_fixtures() {
            let hist = diff.kind_histogram();
            let via_pair = diff.recessive_kind().map_or(0, |k| hist.count(k));
            assert_eq!(diff.trough_kind_count(), via_pair);
        }
    }

    #[test]
    fn trough_kind_count_bounded_above_by_peak_kind_count() {
        // Structural bound `trough_kind_count() <= peak_kind_count()` on
        // every fixture — the trough is bounded above by the peak.
        // Lifted from the trait-uniform `trough_count() <= peak_count()`
        // law on AxisHistogram. The empty-diff case reads `0 <= 0`; the
        // non-empty case reads the trough-of-support bounded above by
        // the peak-of-support. Closes the `(trough, peak)` scalar lattice
        // on the diff altitude — both projections read through the same
        // seam pair. Peer of
        // `trough_tier_count_is_bounded_by_peak_tier_count` on the tier
        // altitude.
        for diff in dominant_kind_fixtures() {
            assert!(
                diff.trough_kind_count() <= diff.peak_kind_count(),
                "trough_kind_count()={t} must be <= peak_kind_count()={p}",
                t = diff.trough_kind_count(),
                p = diff.peak_kind_count(),
            );
        }
    }

    #[test]
    fn trough_kind_count_equals_peak_kind_count_iff_at_most_one_present_kind() {
        // Structural bound `trough_kind_count() == peak_kind_count()`
        // iff `present_kinds().len() <= 1` — the trough equals the peak
        // exactly when zero or one kind is observed. Zero: empty diff,
        // both zero. One: singleton-support diff, both equal
        // `self.lines.len()`. Two or more with distinct counts: trough
        // strictly below peak. Peer of
        // `trough_tier_count_equals_peak_tier_count_iff_at_most_one_contributing_tier`
        // on the tier altitude.
        for diff in dominant_kind_fixtures() {
            let equal = diff.trough_kind_count() == diff.peak_kind_count();
            let support_le_one = diff.present_kinds().len() <= 1;
            if support_le_one {
                assert!(
                    equal,
                    "at_most_one_present_kind → trough == peak \
                     (trough={t}, peak={p}, present={present:?})",
                    t = diff.trough_kind_count(),
                    p = diff.peak_kind_count(),
                    present = diff.present_kinds(),
                );
            }
        }
    }

    #[test]
    fn trough_kind_count_is_at_least_one_on_nonempty_diff() {
        // The lower bound peer: a non-empty diff always has a trough
        // count of at least one line — the argmin is taken over the
        // histogram's *support* (nonzero cells), so the recessive kind
        // carries at least the single line witnessing non-emptiness.
        // Combined with the `<= peak_kind_count() <= lines.len()`
        // upper-bound chain: `1 <= trough_kind_count <= peak_kind_count
        // <= lines.len()` on every non-empty diff — the complete
        // inequality chain on the diff altitude scalar-count surface.
        // Peer of `trough_tier_count_is_at_least_one_on_nonempty_map`
        // on the tier altitude.
        for diff in dominant_kind_fixtures() {
            if diff.lines.is_empty() {
                continue;
            }
            assert!(
                diff.trough_kind_count() >= 1,
                "non-empty diff must have trough_kind_count >= 1, got {}",
                diff.trough_kind_count(),
            );
        }
    }

    #[test]
    fn trough_kind_count_uniform_cover_is_one() {
        // Trait-uniform invariant: on a uniform per-kind diff (one line
        // per kind, three lines total), every observed kind collects
        // one line — the trough count reads `1` (and equals the peak on
        // the uniform-cover degenerate, the singleton-modality
        // count-side analogue). Peer of
        // `trough_tier_count_uniform_cover_is_one` on the tier altitude
        // and diff-altitude peer of the AxisHistogram trait-uniform
        // `trough_count == 1` law on the singleton-per-cell degenerate.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(diff.kind_histogram().is_full_cover());
        assert_eq!(diff.trough_kind_count(), 1);
        assert_eq!(diff.trough_kind_count(), diff.peak_kind_count());
    }

    #[test]
    fn trough_kind_count_singleton_support_equals_lines_len() {
        // Singleton-support degenerate: when only one kind contributes,
        // every line lands on that kind, so the trough equals the total
        // (and equals the peak — the singleton-support count-side
        // degenerate). Peer of
        // `trough_tier_count_singleton_support_equals_len` on the tier
        // altitude reading the same equality against `map.len()`, and
        // diff-altitude count-side dual of
        // `peak_kind_count_singleton_support_equals_lines_len`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Removed("r3".into()),
                DiffLine::Removed("r4".into()),
            ],
        };
        assert_eq!(diff.present_kinds().len(), 1);
        assert_eq!(diff.trough_kind_count(), 4);
        assert_eq!(diff.trough_kind_count(), diff.lines.len());
        assert_eq!(diff.trough_kind_count(), diff.peak_kind_count());
    }

    #[test]
    fn trough_kind_count_agrees_with_open_coded_min_over_support_walk() {
        // Parity against the exact `hist.iter().filter(|&(_, c)| c > 0)
        // .map(|(_, c)| c).min().unwrap_or(0)` walk this lift replaces
        // — both the named seam and the hand-rolled min over the support
        // must pointwise agree over every fixture. The `.filter(c > 0)`
        // step is essential: without it the argmin would silently pick
        // a zero-count cell (any kind the diff did not credit),
        // shadowing the *rarest observed* count with a "trivial minimum"
        // over the full axis. The `.min().unwrap_or(0)` idiom mirrors
        // the empty-histogram convention on
        // [`crate::AxisHistogram::trough_count`] one altitude down (both
        // read 0 on empty). Peer of
        // `trough_tier_count_agrees_with_open_coded_min_over_support_walk`
        // on the tier altitude and diff-altitude count-side dual of
        // `peak_kind_count_agrees_with_open_coded_max_over_axis_walk`
        // (that walk does NOT filter, since
        // [`crate::AxisHistogram::peak_count`] operates over the full
        // axis — the trough side does, since a zero-count cell would
        // otherwise dominate the min).
        for diff in dominant_kind_fixtures() {
            let via_seam = diff.trough_kind_count();
            let hand_rolled = diff
                .kind_histogram()
                .iter()
                .filter(|&(_, c)| c > 0)
                .map(|(_, c)| c)
                .min()
                .unwrap_or(0);
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── ConfigDiff::kind_spread — scalar-dispersion peer on the diff altitude,
    //    fusing peak_kind_count and trough_kind_count into one dispersion
    //    scalar and seeding the "spread across altitudes" projection ──

    #[test]
    fn kind_spread_matches_kind_histogram_spread_pointwise() {
        // The scalar-dispersion pin: `kind_spread` routes through
        // `kind_histogram().spread()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through
        // the shared cube-native primitive. Diff-altitude scalar-
        // dispersion seed of the "spread across altitudes" projection.
        for diff in dominant_kind_fixtures() {
            let via_histogram = diff.kind_histogram().spread();
            assert_eq!(diff.kind_spread(), via_histogram);
        }
    }

    #[test]
    fn kind_spread_equals_peak_minus_trough_pointwise() {
        // The fused-pair pin: `kind_spread == peak_kind_count -
        // trough_kind_count` on every fixture. The subtraction is
        // underflow-safe because `peak_kind_count >= trough_kind_count`
        // holds structurally on every diff (lifted from the trait-
        // uniform `peak_count >= trough_count` law on AxisHistogram).
        // Closes the identity of the scalar-dispersion peer against
        // the two count seams it fuses.
        for diff in dominant_kind_fixtures() {
            let peak = diff.peak_kind_count();
            let trough = diff.trough_kind_count();
            assert!(
                peak >= trough,
                "peak_kind_count ({peak}) must be >= trough_kind_count ({trough}) \
                 for kind_spread to be underflow-safe",
            );
            assert_eq!(diff.kind_spread(), peak - trough);
        }
    }

    #[test]
    fn kind_spread_context_dominated_fixture_is_two() {
        // Direct pin: a diff of 3 Context + 1 Removed has Context
        // dominant at 3, Removed rarest at 1 — the spread is 2. Reads
        // the paired `(peak_kind_count, trough_kind_count, kind_spread)`
        // dispersion triple as `(3, 1, 2)`. Peer of
        // `peak_kind_count_context_dominated_fixture_is_three` and
        // `trough_kind_count_context_dominated_fixture_is_one`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        assert_eq!(diff.peak_kind_count(), 3);
        assert_eq!(diff.trough_kind_count(), 1);
        assert_eq!(diff.kind_spread(), 2);
    }

    #[test]
    fn kind_spread_added_dominated_fixture_is_one() {
        // Direct pin: a diff of 2 Added + 1 Context has Added dominant
        // at 2, Context rarest at 1 — the spread is 1. Reads the paired
        // dispersion triple as `(2, 1, 1)`. Peer of
        // `peak_kind_count_added_dominated_fixture_is_two` and
        // `trough_kind_count_added_dominated_fixture_is_one`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(diff.peak_kind_count(), 2);
        assert_eq!(diff.trough_kind_count(), 1);
        assert_eq!(diff.kind_spread(), 1);
    }

    #[test]
    fn kind_spread_empty_diff_is_zero() {
        // An empty ConfigDiff has no lines and therefore zero spread —
        // reads `0` per the AxisHistogram::spread empty convention one
        // altitude down; the `(peak_kind_count, trough_kind_count,
        // kind_spread)` triple reads `(0, 0, 0)` uniformly on the
        // empty diff. Peer of `peak_kind_count_empty_diff_is_zero` and
        // `trough_kind_count_empty_diff_is_zero`.
        let empty = ConfigDiff::default();
        assert_eq!(empty.peak_kind_count(), 0);
        assert_eq!(empty.trough_kind_count(), 0);
        assert_eq!(empty.kind_spread(), 0);
        assert!(empty.lines.is_empty());
    }

    #[test]
    fn kind_spread_singleton_support_is_zero() {
        // Singleton-support pin: every line lands on the same kind, so
        // the dominant kind is both peak and trough of the support, and
        // the spread is zero — the balanced-diff-kinds boundary on the
        // singleton-support side. Diff-altitude peer of the trait-
        // uniform `spread() == 0 on singleton support` law on
        // AxisHistogram.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Removed("r3".into()),
                DiffLine::Removed("r4".into()),
            ],
        };
        assert_eq!(diff.present_kinds().len(), 1);
        assert_eq!(diff.kind_spread(), 0);
    }

    #[test]
    fn kind_spread_uniform_cover_is_zero() {
        // Uniform-cover pin: every observed kind contributes the same
        // nonzero count (one line each here), so peak == trough == 1
        // and the spread is zero — the balanced-diff-kinds boundary on
        // the uniform-cover side. Peer of `peak_kind_count_uniform_cover_is_one`
        // and `trough_kind_count_uniform_cover_is_one` on the count sides.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(diff.kind_histogram().is_full_cover());
        assert_eq!(diff.peak_kind_count(), 1);
        assert_eq!(diff.trough_kind_count(), 1);
        assert_eq!(diff.kind_spread(), 0);
    }

    #[test]
    fn kind_spread_is_zero_iff_at_most_one_present_kind_or_uniform_cover() {
        // Structural-skew boundary: `kind_spread() == 0` iff every
        // observed kind carries the same count — the balanced-diff-kinds
        // shape. On every fixture, the predicate agrees with the
        // scalar-pair form `peak_kind_count == trough_kind_count`
        // pointwise. The full-cover-with-equal-counts case, the
        // singleton-support case, and the empty diff all read `true`;
        // every skewed diff reads `false`.
        for diff in dominant_kind_fixtures() {
            let spread_zero = diff.kind_spread() == 0;
            let counts_equal = diff.peak_kind_count() == diff.trough_kind_count();
            assert_eq!(
                spread_zero,
                counts_equal,
                "kind_spread == 0 must agree with peak_kind_count == trough_kind_count \
                 for diff with peak={p}, trough={t}, spread={s}",
                p = diff.peak_kind_count(),
                t = diff.trough_kind_count(),
                s = diff.kind_spread(),
            );
        }
    }

    #[test]
    fn kind_spread_agrees_with_modal_pair_equality_on_nonempty_diff() {
        // Cross-surface pin: on every non-empty diff, `kind_spread() ==
        // 0` agrees with `dominant_kind() == recessive_kind()` — the
        // modal-pair equality form of the balanced-diff-kinds predicate.
        // Lifted from the trait-uniform
        // `spread() == 0 <=> dominant_cell() == recessive_cell()` law
        // on AxisHistogram (non-empty case). The empty-diff case is
        // separately pinned on both surfaces.
        for diff in dominant_kind_fixtures() {
            if diff.lines.is_empty() {
                continue;
            }
            let spread_zero = diff.kind_spread() == 0;
            let modal_pair_equal = diff.dominant_kind() == diff.recessive_kind();
            assert_eq!(
                spread_zero, modal_pair_equal,
                "kind_spread == 0 must agree with dominant_kind == recessive_kind \
                 on non-empty diff",
            );
        }
    }

    #[test]
    fn kind_spread_bounded_above_by_peak_kind_count() {
        // Structural bound: `kind_spread() <= peak_kind_count()` on every
        // fixture — the trough is non-negative, so the subtraction is
        // bounded above by the minuend. Lifted from the trait-uniform
        // `spread() <= peak_count()` law on AxisHistogram. Equality
        // holds exactly when the trough is zero — i.e. on the empty
        // diff (both sides read 0).
        for diff in dominant_kind_fixtures() {
            assert!(
                diff.kind_spread() <= diff.peak_kind_count(),
                "kind_spread ({s}) must not exceed peak_kind_count ({p})",
                s = diff.kind_spread(),
                p = diff.peak_kind_count(),
            );
        }
    }

    #[test]
    fn kind_spread_equals_peak_iff_diff_is_empty() {
        // Equality-case pin of the `kind_spread <= peak_kind_count`
        // bound: equality holds iff the trough is zero, which by
        // `trough_kind_count == 0 <=> lines.is_empty()` holds iff the
        // diff is empty. The two projections agree on the (0, 0) empty
        // corner and disagree strictly on every non-empty diff (where
        // the trough is >= 1, so `spread < peak`).
        for diff in dominant_kind_fixtures() {
            let equality = diff.kind_spread() == diff.peak_kind_count();
            let is_empty = diff.lines.is_empty();
            assert_eq!(
                equality,
                is_empty,
                "kind_spread == peak_kind_count must agree with lines.is_empty() \
                 for diff with peak={p}, trough={t}, spread={s}",
                p = diff.peak_kind_count(),
                t = diff.trough_kind_count(),
                s = diff.kind_spread(),
            );
        }
    }

    #[test]
    fn kind_spread_bounded_above_by_lines_len() {
        // Composition bound: `kind_spread() <= self.lines.len()` on every
        // fixture — chaining `kind_spread <= peak_kind_count` (previous
        // pin) with `peak_kind_count <= lines.len()` (documented on
        // `peak_kind_count_bounded_above_by_lines_len`). The scalar
        // dispersion of a diff is bounded above by the total line count
        // of the diff.
        for diff in dominant_kind_fixtures() {
            assert!(
                diff.kind_spread() <= diff.lines.len(),
                "kind_spread ({s}) must not exceed lines.len() ({n})",
                s = diff.kind_spread(),
                n = diff.lines.len(),
            );
        }
    }

    #[test]
    fn kind_spread_skewed_fixture_matches_peak_minus_trough_direct() {
        // Direct pin: a skewed fixture with Context=3, Added=2,
        // Removed=1 has peak 3, trough 1, spread 2 — the strictly-
        // ordered three-cell case where every count is distinct. Pins
        // the fused-pair identity at a concrete position where no
        // tie-breaking is needed on either side of the modal-count
        // pair.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
            ],
        };
        let hist = diff.kind_histogram();
        assert_eq!(hist.count(DiffLineKind::Removed), 1);
        assert_eq!(hist.count(DiffLineKind::Added), 2);
        assert_eq!(hist.count(DiffLineKind::Context), 3);
        assert_eq!(diff.peak_kind_count(), 3);
        assert_eq!(diff.trough_kind_count(), 1);
        assert_eq!(diff.kind_spread(), 2);
    }

    #[test]
    fn kind_spread_agrees_with_open_coded_max_minus_min_walk() {
        // Parity against the exact `hist.iter().map(|(_, c)| c).max()
        // .unwrap_or(0) - hist.iter().filter(|&(_, c)| c > 0)
        // .map(|(_, c)| c).min().unwrap_or(0)` walk this lift replaces
        // — both the named seam and the hand-rolled dispersion must
        // pointwise agree over every fixture. The `.filter(c > 0)` on
        // the min side is essential (mirroring `trough_count`'s support
        // discipline); the `.max()` on the peak side operates over the
        // full axis (mirroring `peak_count`). The subtraction is
        // underflow-safe on the histogram because `peak >= trough`
        // holds structurally, but the hand-rolled form must be careful
        // about the empty-histogram case where both sides read 0.
        for diff in dominant_kind_fixtures() {
            let via_seam = diff.kind_spread();
            let hist = diff.kind_histogram();
            let peak = hist.iter().map(|(_, c)| c).max().unwrap_or(0);
            let trough = hist
                .iter()
                .filter(|&(_, c)| c > 0)
                .map(|(_, c)| c)
                .min()
                .unwrap_or(0);
            assert_eq!(via_seam, peak - trough);
        }
    }

    // ── ConfigDiff::kinds_balanced — balanced-diff-kinds boolean predicate on
    //    the diff altitude, lifting is_uniform_count from the histogram surface
    //    and seeding the "balanced across altitudes" projection ──

    #[test]
    fn kinds_balanced_matches_kind_histogram_is_uniform_count_pointwise() {
        // The routing pin: `kinds_balanced` routes through
        // `kind_histogram().is_uniform_count()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Diff-altitude
        // balanced-predicate seed of the "balanced across altitudes"
        // projection — peer of `kind_spread_matches_kind_histogram_spread_pointwise`.
        for diff in dominant_kind_fixtures() {
            let via_histogram = diff.kind_histogram().is_uniform_count();
            assert_eq!(diff.kinds_balanced(), via_histogram);
        }
    }

    #[test]
    fn kinds_balanced_agrees_with_kind_spread_zero_pointwise() {
        // The defining equivalence on the scalar-spread surface at the
        // diff altitude: `kinds_balanced() == (kind_spread() == 0)` on
        // every fixture. The balanced-boundary of the fused
        // `(peak_kind_count, trough_kind_count, kind_spread)` dispersion
        // triple as a named boolean predicate. Lifted from the trait-
        // uniform `is_uniform_count() == (spread() == 0)` law on
        // AxisHistogram.
        for diff in dominant_kind_fixtures() {
            let balanced = diff.kinds_balanced();
            let spread_zero = diff.kind_spread() == 0;
            assert_eq!(
                balanced,
                spread_zero,
                "kinds_balanced ({balanced}) must agree with kind_spread == 0 \
                 (spread={s}) for diff",
                s = diff.kind_spread(),
            );
        }
    }

    #[test]
    fn kinds_balanced_agrees_with_peak_equals_trough_pointwise() {
        // The structural form on the underlying scalar pair:
        // `kinds_balanced() == (peak_kind_count() == trough_kind_count())`
        // on every fixture. Pins the balanced-diff-kinds predicate against
        // the direct scalar-pair equality form.
        for diff in dominant_kind_fixtures() {
            let balanced = diff.kinds_balanced();
            let peak = diff.peak_kind_count();
            let trough = diff.trough_kind_count();
            assert_eq!(
                balanced,
                peak == trough,
                "kinds_balanced ({balanced}) must agree with peak_kind_count == \
                 trough_kind_count ({peak} == {trough}) for diff",
            );
        }
    }

    #[test]
    fn kinds_balanced_agrees_with_modal_pair_equality_pointwise() {
        // The modal-pair form: `kinds_balanced() == (dominant_kind() ==
        // recessive_kind())` on every fixture — including the empty diff
        // where both branches reduce to `None == None`, every singleton-
        // support diff where both reduce to `Some(k) == Some(k)`, every
        // uniform per-kind diff where both reduce to `Some(first) ==
        // Some(first)` (after declaration-order tie-break on both sides),
        // and every skewed diff where both read `false`. Lifted from the
        // trait-uniform `is_uniform_count() == (dominant_cell() ==
        // recessive_cell())` law on AxisHistogram.
        for diff in dominant_kind_fixtures() {
            let balanced = diff.kinds_balanced();
            let modal_pair_equal = diff.dominant_kind() == diff.recessive_kind();
            assert_eq!(
                balanced, modal_pair_equal,
                "kinds_balanced ({balanced}) must agree with \
                 dominant_kind == recessive_kind for diff",
            );
        }
    }

    #[test]
    fn kinds_balanced_empty_diff_is_true() {
        // Vacuous-uniformity boundary: the empty diff has no observed
        // cells, so the universal "every observed cell carries the same
        // count" reads `true` over the empty support — matching
        // AxisHistogram::is_uniform_count's empty convention one altitude
        // down and `kind_spread == 0` on the empty case. Peer of
        // `kind_spread_empty_diff_is_zero`.
        let empty = ConfigDiff::default();
        assert!(empty.lines.is_empty());
        assert!(empty.kinds_balanced());
        assert_eq!(empty.kind_spread(), 0);
    }

    #[test]
    fn kinds_balanced_singleton_support_is_true() {
        // Singleton-support pin: every line lands on the same kind, so
        // the one observed kind's count is both peak and trough of the
        // support — trivially balanced. Peer of
        // `kind_spread_singleton_support_is_zero`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Removed("r3".into()),
                DiffLine::Removed("r4".into()),
            ],
        };
        assert_eq!(diff.present_kinds().len(), 1);
        assert!(diff.kinds_balanced());
    }

    #[test]
    fn kinds_balanced_uniform_cover_is_true() {
        // Uniform-cover pin: every observed kind contributes the same
        // nonzero count (one line each here), so peak == trough == 1
        // and the balanced-diff-kinds predicate reads `true`. Peer of
        // `kind_spread_uniform_cover_is_zero`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(diff.kind_histogram().is_full_cover());
        assert!(diff.kinds_balanced());
    }

    #[test]
    fn kinds_balanced_context_dominated_fixture_is_false() {
        // Direct pin: a diff of 3 Context + 1 Removed has Context
        // dominant at 3, Removed rarest at 1 — the balanced-diff-kinds
        // predicate reads `false`. Peer of
        // `kind_spread_context_dominated_fixture_is_two` on the boolean
        // side.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
                DiffLine::Removed("r".into()),
            ],
        };
        assert_eq!(diff.kind_spread(), 2);
        assert!(!diff.kinds_balanced());
    }

    #[test]
    fn kinds_balanced_added_dominated_fixture_is_false() {
        // Direct pin: a diff of 2 Added + 1 Context has Added dominant
        // at 2, Context rarest at 1 — the balanced-diff-kinds predicate
        // reads `false`. Peer of `kind_spread_added_dominated_fixture_is_one`
        // on the boolean side.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert_eq!(diff.kind_spread(), 1);
        assert!(!diff.kinds_balanced());
    }

    #[test]
    fn kinds_balanced_singleton_multi_line_is_true() {
        // Singleton-support multi-line pin: 5 Added lines, one observed
        // kind at count 5 — peak == trough == 5, balanced reads `true`.
        // Distinct peak from the 4-line singleton fixture above so any
        // misread that reintroduces a `kind_spread == 0` inline idiom
        // silently underflows on a fixture at a different peak.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Added("a3".into()),
                DiffLine::Added("a4".into()),
                DiffLine::Added("a5".into()),
            ],
        };
        assert_eq!(diff.peak_kind_count(), 5);
        assert_eq!(diff.trough_kind_count(), 5);
        assert!(diff.kinds_balanced());
    }

    #[test]
    fn kinds_balanced_implies_at_most_one_present_kind_or_uniform_cover() {
        // Structural characterization: on every fixture, `kinds_balanced`
        // holds exactly when the diff has support size 0 or 1, or every
        // observed kind carries the same nonzero count. The contrapositive
        // reads: `!kinds_balanced() ⇒ present_kinds().len() >= 2` with
        // at least two distinct counts. Direct witness of the trait-
        // uniform `distinct_cells() <= 1 ⇒ is_uniform_count()` law on
        // AxisHistogram, lifted to the diff altitude.
        for diff in dominant_kind_fixtures() {
            if diff.present_kinds().len() <= 1 {
                assert!(
                    diff.kinds_balanced(),
                    "diff with present_kinds.len() = {} must be kinds_balanced",
                    diff.present_kinds().len(),
                );
            }
        }
    }

    #[test]
    fn kinds_balanced_false_implies_diff_is_nonempty() {
        // Contrapositive of the vacuous-uniformity implication:
        // `!kinds_balanced() ⇒ !self.lines.is_empty()`. A skewed diff has
        // at least two distinct positive counts, so the diff is non-
        // empty. Directly witnessed on the fixture set.
        for diff in dominant_kind_fixtures() {
            if !diff.kinds_balanced() {
                assert!(
                    !diff.lines.is_empty(),
                    "non-balanced diff must be non-empty (lines={})",
                    diff.lines.len(),
                );
            }
        }
    }

    #[test]
    fn kinds_balanced_false_implies_at_least_two_present_kinds() {
        // Contrapositive of the singleton-support implication:
        // `!kinds_balanced() ⇒ present_kinds().len() >= 2`. A skewed diff
        // observes at least two distinct kinds with differing counts.
        // Lifted from the trait-uniform `!is_uniform_count() ⇒
        // distinct_cells() >= 2` law on AxisHistogram.
        for diff in dominant_kind_fixtures() {
            if !diff.kinds_balanced() {
                assert!(
                    diff.present_kinds().len() >= 2,
                    "non-balanced diff must observe >= 2 present kinds (was {})",
                    diff.present_kinds().len(),
                );
            }
        }
    }

    #[test]
    fn kinds_balanced_skewed_three_cell_fixture_is_false() {
        // Direct pin: a strictly-ordered three-cell case with
        // Removed=1, Added=2, Context=3 — peak 3, trough 1, spread 2 —
        // reads `false`. Every count distinct, no tie-breaking on
        // either side of the modal-count pair. Peer of
        // `kind_spread_skewed_fixture_matches_peak_minus_trough_direct`.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
            ],
        };
        assert_eq!(diff.peak_kind_count(), 3);
        assert_eq!(diff.trough_kind_count(), 1);
        assert!(!diff.kinds_balanced());
    }

    #[test]
    fn kinds_balanced_agrees_with_open_coded_uniform_walk() {
        // Parity against the exact hand-rolled uniform-count walk this
        // lift replaces: pull the nonzero counts and check they all
        // agree. Empty support reads `true` vacuously. Mirrors the
        // parity pin `kind_spread_agrees_with_open_coded_max_minus_min_walk`
        // on the scalar-spread surface.
        for diff in dominant_kind_fixtures() {
            let via_seam = diff.kinds_balanced();
            let hist = diff.kind_histogram();
            let mut nonzero = hist.iter().map(|(_, c)| c).filter(|&c| c > 0);
            let hand_rolled = match nonzero.next() {
                None => true,
                Some(first) => nonzero.all(|c| c == first),
            };
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── ConfigDiff::kinds_full_cover — full-cover-diff-kinds boolean predicate
    //    on the diff altitude, lifting is_full_cover from the histogram surface
    //    and seeding the "full-cover across altitudes" projection ──

    #[test]
    fn kinds_full_cover_matches_kind_histogram_is_full_cover_pointwise() {
        // The routing pin: `kinds_full_cover` routes through
        // `kind_histogram().is_full_cover()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Diff-altitude
        // full-cover-predicate seed of the "full-cover across altitudes"
        // projection — peer of
        // `kinds_balanced_matches_kind_histogram_is_uniform_count_pointwise`
        // on the balanced-predicate projection.
        for diff in dominant_kind_fixtures() {
            let via_histogram = diff.kind_histogram().is_full_cover();
            assert_eq!(diff.kinds_full_cover(), via_histogram);
        }
    }

    #[test]
    fn kinds_full_cover_agrees_with_absent_kinds_empty_pointwise() {
        // The defining equivalence on the coverage-gap-Vec surface at
        // the diff altitude: `kinds_full_cover() == absent_kinds().is_empty()`
        // on every fixture. The full-cover-boundary of the fused
        // `(absent_kinds, absent_kinds_count)` coverage-gap peers as a
        // named boolean predicate. Lifted from the trait-uniform
        // `is_full_cover() == unobserved().next().is_none()` law on
        // AxisHistogram.
        for diff in dominant_kind_fixtures() {
            let full_cover = diff.kinds_full_cover();
            let gap_empty = diff.absent_kinds().is_empty();
            assert_eq!(
                full_cover, gap_empty,
                "kinds_full_cover ({full_cover}) must agree with \
                 absent_kinds().is_empty() ({gap_empty}) for diff",
            );
        }
    }

    #[test]
    fn kinds_full_cover_agrees_with_absent_kinds_count_zero_pointwise() {
        // The coverage-gap-scalar form:
        // `kinds_full_cover() == (absent_kinds_count() == 0)` on every
        // fixture. Pins the full-cover-diff-kinds predicate against the
        // scalar-zero equality form on the coverage-gap side.
        for diff in dominant_kind_fixtures() {
            let full_cover = diff.kinds_full_cover();
            let count_zero = diff.absent_kinds_count() == 0;
            assert_eq!(
                full_cover,
                count_zero,
                "kinds_full_cover ({full_cover}) must agree with \
                 absent_kinds_count == 0 (count={c}) for diff",
                c = diff.absent_kinds_count(),
            );
        }
    }

    #[test]
    fn kinds_full_cover_agrees_with_present_kinds_count_equals_axis_cardinality_pointwise() {
        // The support-scalar form: `kinds_full_cover() ==
        // (present_kinds_count() == axis_cardinality::<DiffLineKind>())`
        // on every fixture — the dual-side surfacing of the same boolean
        // across the (observed, unobserved) partition. Lifted from the
        // trait-uniform `is_full_cover() == (distinct_cells() ==
        // axis_cardinality::<A>())` law on AxisHistogram.
        for diff in dominant_kind_fixtures() {
            let full_cover = diff.kinds_full_cover();
            let support_full =
                diff.present_kinds_count() == crate::axis_cardinality::<DiffLineKind>();
            assert_eq!(
                full_cover, support_full,
                "kinds_full_cover ({full_cover}) must agree with \
                 present_kinds_count == axis_cardinality for diff",
            );
        }
    }

    #[test]
    fn kinds_full_cover_agrees_with_present_kinds_len_equals_axis_cardinality_pointwise() {
        // The support-Vec form: `kinds_full_cover() == (present_kinds().len()
        // == axis_cardinality::<DiffLineKind>())` on every fixture. Pins
        // the predicate against the `Vec<DiffLineKind>` length form
        // consumers reach for when they already hold the support vector.
        for diff in dominant_kind_fixtures() {
            let full_cover = diff.kinds_full_cover();
            let support_len_full =
                diff.present_kinds().len() == crate::axis_cardinality::<DiffLineKind>();
            assert_eq!(
                full_cover, support_len_full,
                "kinds_full_cover ({full_cover}) must agree with \
                 present_kinds().len() == axis_cardinality for diff",
            );
        }
    }

    #[test]
    fn kinds_full_cover_empty_diff_is_false() {
        // Empty-diff boundary: the empty diff has no observed cells, so
        // the coverage gap equals every cell of `DiffLineKind::ALL`
        // (three-cell axis, no zero-cardinality degenerate case) —
        // `kinds_full_cover` reads `false`. Dual of
        // `kinds_balanced_empty_diff_is_true`: the empty diff is on the
        // opposite side of the full-cover boundary from the balanced
        // boundary. Matches `is_full_cover` reading `false` on the
        // empty histogram over a non-zero-cardinality axis one altitude
        // down.
        let empty = ConfigDiff::default();
        assert!(empty.lines.is_empty());
        assert!(!empty.kinds_full_cover());
        assert_eq!(
            empty.absent_kinds_count(),
            crate::axis_cardinality::<DiffLineKind>()
        );
    }

    #[test]
    fn kinds_full_cover_singleton_support_is_false() {
        // Singleton-support pin: every line lands on the same kind, so
        // one observed cell out of three leaves two cells in the
        // coverage gap — `kinds_full_cover` reads `false`. Peer of
        // `kinds_balanced_singleton_support_is_true` on the opposite
        // side of the boundary: singleton-support is trivially balanced
        // but never full-cover on a three-cell axis.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r1".into()),
                DiffLine::Removed("r2".into()),
                DiffLine::Removed("r3".into()),
                DiffLine::Removed("r4".into()),
            ],
        };
        assert_eq!(diff.present_kinds().len(), 1);
        assert!(!diff.kinds_full_cover());
    }

    #[test]
    fn kinds_full_cover_uniform_cover_is_true() {
        // Uniform-cover pin: every observed kind contributes one line,
        // so every cell of `DiffLineKind::ALL` receives at least one
        // observation — `kinds_full_cover` reads `true`. Peer of
        // `kinds_balanced_uniform_cover_is_true` on the same fixture:
        // the uniform three-kind cover is on the `true` side of BOTH
        // the balanced-diff-kinds and full-cover-diff-kinds boundaries.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
                DiffLine::Context("c".into()),
            ],
        };
        assert!(diff.kinds_full_cover());
        assert!(diff.kinds_balanced());
    }

    #[test]
    fn kinds_full_cover_context_dominated_fixture_is_true() {
        // Skewed three-cell fixture: 3 Context + 1 Removed + 1 Added has
        // every kind observed at least once — `kinds_full_cover` reads
        // `true` even though `kinds_balanced` reads `false`. Pins the
        // orthogonality of the balanced-boundary and the full-cover-
        // boundary: full-cover is coverage-side (does every cell fire?)
        // while balanced is uniform-count-side (does every observed cell
        // fire equally?). Peer of
        // `kinds_balanced_context_dominated_fixture_is_false` on the
        // orthogonal boundary.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
                DiffLine::Removed("r".into()),
                DiffLine::Added("a".into()),
            ],
        };
        assert!(diff.kinds_full_cover());
        assert!(!diff.kinds_balanced());
    }

    #[test]
    fn kinds_full_cover_added_removed_only_is_false() {
        // Two-kind cover pin: a diff of only Added + Removed lines
        // leaves Context in the coverage gap — `kinds_full_cover` reads
        // `false`. Direct witness that the two-kind-observed shape is
        // on the `false` side of the full-cover boundary.
        let diff = ConfigDiff {
            lines: vec![DiffLine::Removed("r".into()), DiffLine::Added("a".into())],
        };
        assert_eq!(diff.present_kinds().len(), 2);
        assert!(!diff.kinds_full_cover());
        assert!(diff.absent_kinds().contains(&DiffLineKind::Context));
    }

    #[test]
    fn kinds_full_cover_implies_diff_is_nonempty() {
        // Contrapositive of the empty-diff boundary: `kinds_full_cover()
        // ⇒ !self.lines.is_empty()`. A full-cover diff observes at
        // least one line per kind, so the line list is non-empty.
        // Directly witnessed on the fixture set. Peer of
        // `kinds_balanced_false_implies_diff_is_nonempty` on the same
        // structural implication, opposite polarity.
        for diff in dominant_kind_fixtures() {
            if diff.kinds_full_cover() {
                assert!(
                    !diff.lines.is_empty(),
                    "full-cover diff must be non-empty (lines={})",
                    diff.lines.len(),
                );
            }
        }
    }

    #[test]
    fn kinds_full_cover_implies_present_kinds_equals_axis_cardinality() {
        // Structural characterization: `kinds_full_cover() ⇒
        // present_kinds().len() == axis_cardinality::<DiffLineKind>()`.
        // A full-cover diff observes every kind, so the support size
        // equals the axis cardinality. Direct witness of the trait-
        // uniform `is_full_cover() ⇒ distinct_cells() ==
        // axis_cardinality::<A>()` law on AxisHistogram, lifted to the
        // diff altitude.
        for diff in dominant_kind_fixtures() {
            if diff.kinds_full_cover() {
                assert_eq!(
                    diff.present_kinds().len(),
                    crate::axis_cardinality::<DiffLineKind>(),
                    "full-cover diff must observe every DiffLineKind",
                );
            }
        }
    }

    #[test]
    fn kinds_full_cover_implies_line_count_bounded_below_by_axis_cardinality() {
        // Line-count lower-bound characterization: `kinds_full_cover()
        // ⇒ self.lines.len() >= axis_cardinality::<DiffLineKind>()`. A
        // full-cover diff observes at least one line per kind, so the
        // line count is bounded below by the axis cardinality (three on
        // the DiffLineKind axis). Directly witnessed on the fixture set.
        for diff in dominant_kind_fixtures() {
            if diff.kinds_full_cover() {
                assert!(
                    diff.lines.len() >= crate::axis_cardinality::<DiffLineKind>(),
                    "full-cover diff must have >= axis_cardinality lines (was {})",
                    diff.lines.len(),
                );
            }
        }
    }

    #[test]
    fn kinds_full_cover_skewed_three_cell_fixture_is_true() {
        // Direct pin: a strictly-ordered three-cell case with Removed=1,
        // Added=2, Context=3 has every kind observed — `kinds_full_cover`
        // reads `true`, orthogonal to `kinds_balanced_skewed_three_cell_fixture_is_false`
        // which reads `false` on the identical fixture. Every kind
        // observed but at strictly-distinct counts: full-cover is the
        // coverage boundary, not the uniformity boundary.
        let diff = ConfigDiff {
            lines: vec![
                DiffLine::Removed("r".into()),
                DiffLine::Added("a1".into()),
                DiffLine::Added("a2".into()),
                DiffLine::Context("c1".into()),
                DiffLine::Context("c2".into()),
                DiffLine::Context("c3".into()),
            ],
        };
        assert!(diff.kinds_full_cover());
        assert!(!diff.kinds_balanced());
    }

    #[test]
    fn kinds_full_cover_agrees_with_open_coded_all_positive_walk() {
        // Parity against the exact hand-rolled full-cover walk this
        // lift replaces: walk every cell of the histogram and check
        // every count is positive. Mirrors the parity pin
        // `kinds_balanced_agrees_with_open_coded_uniform_walk` on the
        // balanced-predicate surface. Note the walk uses `hist.iter()`
        // which iterates over the closed axis's ALL cells in
        // declaration order — a full-cover diff has every cell nonzero
        // regardless of order.
        for diff in dominant_kind_fixtures() {
            let via_seam = diff.kinds_full_cover();
            let hist = diff.kind_histogram();
            let hand_rolled = hist.iter().all(|(_, c)| c > 0);
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn diff_line_kind_ord_matches_all_declaration_order() {
        // The derived Ord on DiffLineKind is declaration-order lex
        // over ALL: `Removed < Added < Context`. A BTreeMap keyed on
        // the diff-cell kind (per-cell rebuild-summary histograms
        // keyed over a stable axis, attestation manifests recording
        // the diff-cell cardinality mix of a ConfigDiff between two
        // tiers, structured-diagnostic legends bucketing per-cell
        // counters in declaration order) emits rows in that order
        // deterministically without a hand-rolled comparator at the
        // renderer.
        //
        // Two-leg pin: (1) ALL is a strictly-increasing chain under
        // Ord, (2) cmp/partial_cmp agree with the array-index lex
        // over ALL on every pair (and reflexivity holds). Idiom-peer
        // of the same pin on WatchEventClass (commit `94f8a8b`),
        // EnvMetadataTagKind (commit `b556b75`), FigmentNameTagKind
        // (commit `64a47e7`), FigmentSourceKind (commit `5df265c`),
        // and ConfigSourceKind (commit `e0b96d1`).
        use std::cmp::Ordering;
        for window in DiffLineKind::ALL.windows(2) {
            assert!(
                window[0] < window[1],
                "DiffLineKind::ALL must be strictly increasing under Ord, \
                 but {:?} >= {:?}",
                window[0],
                window[1],
            );
        }
        for (i, &a) in DiffLineKind::ALL.iter().enumerate() {
            for (j, &b) in DiffLineKind::ALL.iter().enumerate() {
                let expected = i.cmp(&j);
                assert_eq!(
                    a.cmp(&b),
                    expected,
                    "DiffLineKind::cmp must match ALL-index lex for ({a:?}, {b:?})",
                );
                assert_eq!(
                    a.partial_cmp(&b),
                    Some(expected),
                    "DiffLineKind::partial_cmp must agree with cmp for ({a:?}, {b:?})",
                );
                if i == j {
                    assert_eq!(a.cmp(&b), Ordering::Equal, "Ord must be reflexive on {a:?}",);
                }
            }
        }
    }

    #[test]
    fn diff_line_kind_btreemap_emits_in_declaration_order() {
        // The compounding payoff of the Ord derive at a typed
        // consumer site: a BTreeMap<DiffLineKind, _> emits keys
        // in declaration order on `iter()` / `into_iter()`
        // regardless of insertion order, matching
        // `DiffLineKind::ALL`. Idiom-peer of the same pin on
        // WatchEventClass (commit `94f8a8b`), EnvMetadataTagKind
        // (commit `b556b75`), FigmentNameTagKind (commit `64a47e7`),
        // FigmentSourceKind (commit `5df265c`), and ConfigSourceKind
        // (commit `e0b96d1`).
        use std::collections::BTreeMap;
        let mut counts: BTreeMap<DiffLineKind, u32> = BTreeMap::new();
        counts.insert(DiffLineKind::Context, 3);
        counts.insert(DiffLineKind::Removed, 1);
        counts.insert(DiffLineKind::Added, 2);
        let observed: Vec<DiffLineKind> = counts.keys().copied().collect();
        assert_eq!(
            observed,
            DiffLineKind::ALL.to_vec(),
            "BTreeMap<DiffLineKind, _> must emit keys in ALL declaration order",
        );
    }

    #[test]
    fn diff_line_kind_display_matches_as_str() {
        // Display writes the canonical lowercase label as_str returns,
        // byte-for-byte. The two surfaces stay aligned by construction
        // — a future rename of either must update the other in
        // lockstep. Idiom-peer of the same pin on WatchEventClass
        // (commit `94f8a8b`), EnvMetadataTagKind (commit `b556b75`),
        // FigmentNameTagKind (commit `64a47e7`), and FigmentSourceKind
        // (commit `5df265c`).
        for k in DiffLineKind::ALL.iter().copied() {
            assert_eq!(
                format!("{k}"),
                k.as_str(),
                "Display must agree with as_str for {k:?}",
            );
        }
    }

    #[test]
    fn diff_line_kind_from_str_round_trips_over_every_variant() {
        // Display → FromStr identity round-trip over every variant.
        // FromStr lowers through ClosedAxisLabel::from_canonical_str,
        // so any future override of that trait method is held to this
        // law at the inherent FromStr surface as well.
        for k in DiffLineKind::ALL {
            let rendered = k.to_string();
            let parsed: DiffLineKind = rendered
                .parse()
                .expect("FromStr must round-trip Display output");
            assert_eq!(parsed, *k, "FromStr must round-trip {k:?}");
        }
    }

    #[test]
    fn diff_line_kind_from_str_is_case_insensitive() {
        // FromStr lowers through ClosedAxisLabel::from_canonical_str
        // which uses eq_ignore_ascii_case over ALL — uppercase and
        // mixed-case scalars an operator might type into a CLI flag
        // or structured-log filter parse pointwise to the same
        // variant.
        assert_eq!(
            "REMOVED".parse::<DiffLineKind>().unwrap(),
            DiffLineKind::Removed,
        );
        assert_eq!(
            "Added".parse::<DiffLineKind>().unwrap(),
            DiffLineKind::Added,
        );
        assert_eq!(
            "cOnTeXt".parse::<DiffLineKind>().unwrap(),
            DiffLineKind::Context,
        );
        assert_eq!(
            "rEmOvEd".parse::<DiffLineKind>().unwrap(),
            DiffLineKind::Removed,
        );
    }

    #[test]
    fn diff_line_kind_from_str_unknown_kind_error_carries_label_verbatim() {
        // Unrecognized labels reject through ShikumiError::Parse with
        // the offending substring embedded verbatim in the rendered
        // message — same verbatim-rejection discipline as
        // WatchEventClass's FromStr surface (commit `94f8a8b`),
        // EnvMetadataTagKind's FromStr surface (commit `b556b75`),
        // FigmentNameTagKind's FromStr surface (commit `64a47e7`),
        // FigmentSourceKind's FromStr surface (commit `5df265c`),
        // ConfigSourceKind's FromStr surface (commit `e0b96d1`),
        // FormatProvenance's FromStr surface (commit `2c7654c`), and
        // ParseFormatCoordinatesError (commit `06a2f42`).
        for bad in &["changed", "deleted", "modified", "", "  removed"] {
            let err = bad
                .parse::<DiffLineKind>()
                .expect_err("non-canonical label must reject");
            let rendered = err.to_string();
            assert!(
                rendered.contains(bad),
                "rendered error must contain the offending label verbatim: \
                 input={bad:?}, rendered={rendered:?}",
            );
        }
    }

    #[test]
    fn diff_line_kind_serde_yaml_round_trips_over_every_variant() {
        // Serde Serialize → Deserialize identity round-trip over every
        // variant through serde_yaml. Closes the (Serialize,
        // Deserialize) idiom-peer of the (Display, FromStr) stdlib
        // pair on the diff-cell axis primitive. A consumer struct
        // holding a DiffLineKind field under
        // #[derive(Serialize, Deserialize)] (e.g. an attestation
        // manifest recording the diff-cell kind of a `ConfigDiff`
        // sample) round-trips without a consumer-side rename helper.
        for k in DiffLineKind::ALL {
            let yaml = serde_yaml::to_string(k).expect("Serialize must succeed");
            let parsed: DiffLineKind =
                serde_yaml::from_str(&yaml).expect("Deserialize must accept Serialize output");
            assert_eq!(parsed, *k, "serde_yaml round-trip must preserve {k:?}");
        }
    }

    #[test]
    fn diff_line_kind_serde_json_round_trips_over_every_variant() {
        // Serde Serialize → Deserialize identity round-trip over every
        // variant through serde_json. The two formats render the
        // canonical scalar identically modulo wire ceremony (YAML's
        // bare scalar vs. JSON's quoted string), so the round-trip
        // law composes pointwise — a future divergence in either
        // Serialize impl surfaces here.
        for k in DiffLineKind::ALL {
            let json = serde_json::to_string(k).expect("Serialize must succeed");
            let parsed: DiffLineKind =
                serde_json::from_str(&json).expect("Deserialize must accept Serialize output");
            assert_eq!(parsed, *k, "serde_json round-trip must preserve {k:?}");
        }
    }

    #[test]
    fn diff_line_kind_serde_yaml_is_case_insensitive() {
        // Deserialize lowers through FromStr which lowers through
        // ClosedAxisLabel::from_canonical_str (eq_ignore_ascii_case),
        // so uppercase or mixed-case scalars parse pointwise. A
        // manifest field authored by an operator typing the canonical
        // name with different casing parses without a consumer-side
        // case-fold helper.
        let cases: &[(&str, DiffLineKind)] = &[
            ("Removed", DiffLineKind::Removed),
            ("ADDED", DiffLineKind::Added),
            ("CoNtExT", DiffLineKind::Context),
            ("rEmOvEd", DiffLineKind::Removed),
        ];
        for (input, expected) in cases {
            let parsed: DiffLineKind =
                serde_yaml::from_str(input).expect("case-insensitive Deserialize must succeed");
            assert_eq!(
                parsed, *expected,
                "serde_yaml must parse case-insensitively for input {input:?}",
            );
        }
    }

    #[test]
    fn diff_line_kind_serde_yaml_unknown_kind_error_carries_label_verbatim() {
        // An unrecognized diff-cell kind label surfaces at the serde
        // error site with the offending substring verbatim in the
        // rendered message, lifted through ShikumiError::Parse's
        // Display impl. Same verbatim-rejection discipline as
        // WatchEventClass's serde surface (commit `94f8a8b`),
        // EnvMetadataTagKind's serde surface (commit `b556b75`),
        // FigmentNameTagKind's serde surface (commit `64a47e7`),
        // FigmentSourceKind's serde surface (commit `5df265c`),
        // ConfigSourceKind's serde surface (commit `e0b96d1`), and
        // FormatProvenance's serde surface (commit `2c7654c`).
        for bad in &["changed", "deleted", "modified", "noop"] {
            let err = serde_yaml::from_str::<DiffLineKind>(bad)
                .expect_err("non-canonical label must reject");
            let rendered = err.to_string();
            assert!(
                rendered.contains(bad),
                "rendered serde error must contain the offending label verbatim: \
                 input={bad:?}, rendered={rendered:?}",
            );
        }
    }

    #[test]
    fn diff_line_kind_serde_yaml_emission_is_bare_scalar() {
        // Concrete-position pin on DiffLineKind's YAML emission:
        // every variant renders as a bare lowercase scalar (no
        // quotes, no tag prefix). Routes through
        // Serializer::collect_str → Display → as_str, so the wire
        // shape is exactly `format!("{k}")` followed by serde_yaml's
        // newline terminator. Pins the serde idiom-peer of the
        // Display surface byte-for-byte at concrete positions across
        // every variant. Idiom-peer of
        // `watch_event_class_serde_yaml_emission_is_bare_scalar`
        // (commit `94f8a8b`).
        assert_eq!(
            serde_yaml::to_string(&DiffLineKind::Removed).unwrap(),
            "removed\n",
        );
        assert_eq!(
            serde_yaml::to_string(&DiffLineKind::Added).unwrap(),
            "added\n",
        );
        assert_eq!(
            serde_yaml::to_string(&DiffLineKind::Context).unwrap(),
            "context\n",
        );
    }
}

// ── Progressive-discovery fold + typed provenance coverage ──────────
#[cfg(test)]
mod progressive_tests {
    use super::*;
    use crate::ConfigSource;
    use figment::value::{Dict, Value};
    use serde::{Deserialize, Serialize};

    // A config where `discovered()` detects `a` + `d`, and
    // `prescribed_default()` is built ON discovered(): it re-emits `a`
    // unchanged, curates `b`, and overrides `d`. `c` never rises above the
    // bare floor. This is the canonical last-changer fixture.
    #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
    struct Prog {
        a: u32,
        b: u32,
        c: u32,
        d: u32,
    }

    impl TieredConfig for Prog {
        fn bare() -> Self {
            Self {
                a: 0,
                b: 0,
                c: 0,
                d: 0,
            }
        }
        fn discovered() -> Self {
            Self {
                a: 10,
                b: 0,
                c: 0,
                d: 5,
            }
        }
        fn prescribed_default() -> Self {
            Self {
                a: 10,
                b: 20,
                c: 0,
                d: 7,
            }
        }
    }

    #[test]
    fn progressive_value_folds_all_tiers() {
        let r = Prog::resolve_progressive();
        assert_eq!(
            *r.value(),
            Prog {
                a: 10,
                b: 20,
                c: 0,
                d: 7
            }
        );
    }

    #[test]
    fn progressive_provenance_credits_each_leaf_to_its_producing_tier() {
        let r = Prog::resolve_progressive();
        let p = r.provenance();
        // a: detected at Discovered, re-emitted unchanged by prescribed → Discovered.
        assert_eq!(
            p.provenance_of(&["a"]).unwrap().tier(),
            ConfigTierKind::Discovered
        );
        // b: curated at prescribed → Default.
        assert_eq!(
            p.provenance_of(&["b"]).unwrap().tier(),
            ConfigTierKind::Default
        );
        // c: never rose above the floor → Bare.
        assert_eq!(
            p.provenance_of(&["c"]).unwrap().tier(),
            ConfigTierKind::Bare
        );
        // d: detected 5 at Discovered, OVERRIDDEN to 7 at prescribed → Default.
        assert_eq!(
            p.provenance_of(&["d"]).unwrap().tier(),
            ConfigTierKind::Default
        );
    }

    #[test]
    fn progressive_discovery_shows_through_where_prescribed_does_not_override() {
        // The gap-2 seal: resolve_tier(Default) == prescribed_default() (no
        // discovery); resolve_progressive folds discovered() UNDER prescribed,
        // so a detected value survives where prescribed didn't touch it.
        let r = Prog::resolve_progressive();
        assert_eq!(r.value().a, 10, "discovered a=10 shows through");
        assert_eq!(
            r.provenance().provenance_of(&["a"]).unwrap().tier(),
            ConfigTierKind::Discovered,
        );
        // The legacy single-tier path is unchanged.
        assert_eq!(
            Prog::resolve_tier(ConfigTier::Default),
            Prog::prescribed_default()
        );
    }

    #[test]
    fn progressive_provenance_is_complete_over_every_leaf() {
        let r = Prog::resolve_progressive();
        // Every field of the resolved config has a provenance entry (bare()
        // seeds every leaf) — completeness by construction of the fold.
        assert_eq!(r.provenance().len(), 4);
        for leaf in [["a"], ["b"], ["c"], ["d"]] {
            assert!(
                r.provenance().provenance_of(&leaf).is_some(),
                "leaf {leaf:?} must have provenance"
            );
        }
        assert!(!r.provenance().is_empty());
    }

    #[test]
    fn progressive_higher_tier_beats_lower_on_override() {
        // d: discovered=5, prescribed=7 → the higher tier's value wins.
        let r = Prog::resolve_progressive();
        assert_eq!(r.value().d, 7);
        assert_eq!(
            r.provenance().provenance_of(&["d"]).unwrap().tier(),
            ConfigTierKind::Default
        );
    }

    #[test]
    fn progressive_overlay_file_beats_prescribed_and_carries_file_provenance() {
        let mut d = Dict::new();
        d.insert("b".to_owned(), Value::from(99_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::file("/etc/prog.yaml", d)]);
        assert_eq!(r.value().b, 99, "file overlay beats prescribed b=20");
        let prov = r.provenance().provenance_of(&["b"]).unwrap();
        assert_eq!(prov.tier(), ConfigTierKind::Custom);
        assert_eq!(prov.source(), &ConfigSource::File("/etc/prog.yaml".into()));
        // a untouched by the overlay → still Discovered.
        assert_eq!(
            r.provenance().provenance_of(&["a"]).unwrap().tier(),
            ConfigTierKind::Discovered
        );
    }

    #[test]
    fn progressive_fold_reorders_a_misordered_low_tier_overlay() {
        // A caller-supplied overlay carrying a LOW-tier provenance is sorted
        // to its tier rank BEFORE the fold, so it cannot beat a higher tier:
        // a Bare-tagged overlay setting a=999 lands below Discovered's a=10.
        let mut d = Dict::new();
        d.insert("a".to_owned(), Value::from(999_u32));
        let sneaky = ProgressiveLayer::new(
            Provenance::new(ConfigTierKind::Bare, ConfigSource::Defaults),
            d,
        );
        let r = Prog::resolve_progressive_with(&[sneaky]);
        assert_eq!(
            r.value().a,
            10,
            "a low-tier overlay cannot beat the Discovered tier"
        );
        assert_eq!(
            r.provenance().provenance_of(&["a"]).unwrap().tier(),
            ConfigTierKind::Discovered
        );
    }

    #[test]
    fn progressive_contributing_tiers_in_precedence_order() {
        let r = Prog::resolve_progressive();
        // Bare (c), Discovered (a), Default (b, d) all survive.
        assert_eq!(
            r.provenance().contributing_tiers(),
            vec![
                ConfigTierKind::Bare,
                ConfigTierKind::Discovered,
                ConfigTierKind::Default
            ],
        );
    }

    #[test]
    fn progressive_entries_iterate_lexicographically() {
        let r = Prog::resolve_progressive();
        let paths: Vec<Vec<String>> = r.provenance().entries().map(|(p, _)| p.to_vec()).collect();
        assert_eq!(
            paths,
            vec![
                vec!["a".to_string()],
                vec!["b".to_string()],
                vec!["c".to_string()],
                vec!["d".to_string()],
            ],
        );
    }

    #[test]
    fn provenance_map_entries_return_type_is_nameable_provenance_map_entries() {
        // Pin the sharpen at the type-signature level: a struct field bound
        // on `ProvenanceMapEntries<'a>` holds the handle across a return.
        // This test compiles iff the sharpen holds; if `entries()` ever
        // regresses back to `impl Trait`, this ceases to compile because
        // `impl Trait` return types are unnameable at struct-field bounds.
        struct Held<'a> {
            walker: ProvenanceMapEntries<'a>,
        }
        fn hold(map: &ProvenanceMap) -> Held<'_> {
            Held {
                walker: map.entries(),
            }
        }
        let r = Prog::resolve_progressive();
        let mut h = hold(r.provenance());
        assert!(h.walker.next().is_some());
    }

    #[test]
    fn provenance_map_entries_clone_preserves_static_traits() {
        // A static bound accepting Iterator + DoubleEndedIterator +
        // ExactSizeIterator + FusedIterator + Clone verifies the full
        // trait algebra survives the sharpen at compile time — the
        // tier-level dual of the same triple-trait pair pinned on the
        // discovered-altitude siblings, with ExactSizeIterator added
        // because the projection preserves element count (unlike the
        // filtered discovered-side iters). Then a runtime cross-walk
        // asserts the cloned walker yields the same (path, provenance)
        // pair stream as the original.
        fn assert_algebra<'a, I>(_: &I)
        where
            I: Iterator<Item = (&'a [String], &'a Provenance)>
                + DoubleEndedIterator
                + ExactSizeIterator
                + std::iter::FusedIterator
                + Clone,
        {
        }
        let r = Prog::resolve_progressive();
        let it = r.provenance().entries();
        assert_algebra(&it);
        let cloned = it.clone();
        let a: Vec<Vec<String>> = it.map(|(p, _)| p.to_vec()).collect();
        let b: Vec<Vec<String>> = cloned.map(|(p, _)| p.to_vec()).collect();
        assert_eq!(a, b);
    }

    #[test]
    fn provenance_map_entries_next_back_walks_specific_to_coarse() {
        // Pin the DoubleEndedIterator impl at the runtime level: the tail
        // cursor walks the sorted BTreeMap in reverse, yielding leaves
        // from lexicographically last to first. Catches a regression to
        // a single-ended state machine.
        let r = Prog::resolve_progressive();
        let mut it = r.provenance().entries();
        let (last, _) = it.next_back().unwrap();
        assert_eq!(last, &["d".to_string()][..]);
        let (before_last, _) = it.next_back().unwrap();
        assert_eq!(before_last, &["c".to_string()][..]);
        let (head, _) = it.next().unwrap();
        assert_eq!(head, &["a".to_string()][..]);
        // Exhaust: the two remaining pulls from opposite ends meet at the
        // last surviving element `b`, then both cursors report `None`.
        let (mid, _) = it.next_back().unwrap();
        assert_eq!(mid, &["b".to_string()][..]);
        assert!(it.next().is_none());
        assert!(it.next_back().is_none());
    }

    #[test]
    fn provenance_map_entries_len_matches_remaining_pulls() {
        // Pin the ExactSizeIterator impl: `len()` reports the exact
        // remaining count at every seam. The projection
        // `(&Vec<String>, &Provenance) → (&[String], &Provenance)` is
        // element-preserving (unlike the filter-based discovered-side
        // iters), so `len()` is honored at the type level.
        let r = Prog::resolve_progressive();
        let mut it = r.provenance().entries();
        assert_eq!(it.len(), 4);
        it.next();
        assert_eq!(it.len(), 3);
        it.next_back();
        assert_eq!(it.len(), 2);
        it.next();
        it.next_back();
        assert_eq!(it.len(), 0);
        assert!(it.next().is_none());
    }

    #[test]
    fn provenance_map_entries_debug_impl_names_the_struct() {
        // Pin the derived Debug impl at the format-string level: the
        // rendered output names the struct (`ProvenanceMapEntries`).
        // The inner `BTreeMap::Iter` forwards its own Debug, which
        // renders every remaining (path, provenance) pair — enough
        // to distinguish "just started" from "half-way through"
        // without a manual impl.
        let r = Prog::resolve_progressive();
        let it = r.provenance().entries();
        let s = format!("{it:?}");
        assert!(
            s.contains("ProvenanceMapEntries"),
            "Debug output should name the struct type, got: {s}"
        );
    }

    #[test]
    fn progressive_pair_is_atomic_via_into_parts() {
        let (value, prov) = Prog::resolve_progressive().into_parts();
        assert_eq!(value.a, 10);
        assert_eq!(
            prov.provenance_of(&["a"]).unwrap().tier(),
            ConfigTierKind::Discovered
        );
    }

    // -------- IntoIterator / FromIterator / Extend on ProvenanceMap --------

    #[test]
    fn into_iter_ref_forwards_to_entries_pointwise() {
        // `for entry in &map` yields the same pair stream as `map.entries()` —
        // the borrow-side idiomatic dual is a name change, not a shape
        // change. Pins the tier-level `IntoIterator for &ProvenanceMap`
        // impl at the runtime level.
        let r = Prog::resolve_progressive();
        let via_entries: Vec<Vec<String>> =
            r.provenance().entries().map(|(p, _)| p.to_vec()).collect();
        let via_into_iter_ref: Vec<Vec<String>> = r
            .provenance()
            .into_iter()
            .map(|(p, _)| p.to_vec())
            .collect();
        assert_eq!(via_entries, via_into_iter_ref);
    }

    #[test]
    fn into_iter_owned_yields_same_paths_and_provenance_as_entries() {
        // The consume-side dual of the borrow-side entries walk: owning
        // pulls yield `(Vec<String>, Provenance)` in the same lex order,
        // with each provenance equal to what the borrowing walk showed.
        let r = Prog::resolve_progressive();
        let borrowed: Vec<(Vec<String>, Provenance)> = r
            .provenance()
            .entries()
            .map(|(p, prov)| (p.to_vec(), prov.clone()))
            .collect();
        let owned: Vec<(Vec<String>, Provenance)> = r.provenance().clone().into_iter().collect();
        assert_eq!(borrowed, owned);
    }

    #[test]
    fn into_iter_owned_len_matches_provenance_map_len() {
        // ExactSizeIterator on the consuming walker reports the same
        // leaf count as the map — the trait-level parity of
        // `ProvenanceMapEntries::len()` on the consume-side surface.
        let r = Prog::resolve_progressive();
        let n = r.provenance().len();
        let it = r.provenance().clone().into_iter();
        assert_eq!(it.len(), n);
    }

    #[test]
    fn into_iter_owned_next_back_walks_specific_to_coarse() {
        // The DoubleEnded impl on the consuming walker walks the sorted
        // BTreeMap in reverse — the tier-level peer of the same pin on
        // the borrowing ProvenanceMapEntries.
        let r = Prog::resolve_progressive();
        let mut it = r.provenance().clone().into_iter();
        let (last, _) = it.next_back().unwrap();
        assert_eq!(last, vec!["d".to_string()]);
        let (before_last, _) = it.next_back().unwrap();
        assert_eq!(before_last, vec!["c".to_string()]);
        let (head, _) = it.next().unwrap();
        assert_eq!(head, vec!["a".to_string()]);
        let (mid, _) = it.next_back().unwrap();
        assert_eq!(mid, vec!["b".to_string()]);
        assert!(it.next().is_none());
        assert!(it.next_back().is_none());
    }

    #[test]
    fn from_iter_collect_recovers_provenance_map() {
        // The construction-side dual of IntoIterator for &ProvenanceMap:
        // reading the map through `.entries()`, cloning each pair, and
        // `.collect()`-ing back into `ProvenanceMap` recovers the original
        // verbatim. The `FromIterator` seam lets consumers build synthetic
        // provenance maps for tests, mocks, and diagnostics without
        // reaching into a private inner field.
        let r = Prog::resolve_progressive();
        let source: ProvenanceMap = r.provenance().clone();
        let round: ProvenanceMap = source
            .entries()
            .map(|(p, prov)| (p.to_vec(), prov.clone()))
            .collect();
        assert_eq!(source, round);
    }

    #[test]
    fn from_iter_empty_source_is_default() {
        // `.collect()`-ing an empty stream yields the default (empty) map —
        // the same neutral element every keyed collection's `FromIterator`
        // + `Default` pair honors.
        let empty: ProvenanceMap = std::iter::empty::<(Vec<String>, Provenance)>().collect();
        assert_eq!(empty, ProvenanceMap::default());
        assert!(empty.is_empty());
        assert_eq!(empty.len(), 0);
    }

    #[test]
    fn from_iter_last_write_wins_on_duplicate_paths() {
        // Duplicate paths in the source resolve last-write-wins — the same
        // `BTreeMap`-insertion discipline the discovered-side
        // `FromIterator for LayerAttribution` honors on its owned key.
        let path = vec!["k".to_string()];
        let first = Provenance::computed(ConfigTierKind::Bare);
        let second = Provenance::computed(ConfigTierKind::Discovered);
        let map: ProvenanceMap = vec![(path.clone(), first), (path.clone(), second.clone())]
            .into_iter()
            .collect();
        assert_eq!(map.len(), 1);
        assert_eq!(map.provenance_of_owned(&path), Some(&second));
    }

    #[test]
    fn extend_adds_new_paths_and_overwrites_at_conflicts() {
        // `Extend` mirrors `FromIterator`'s last-write-wins semantics but
        // grows the map in place. New paths land as fresh entries; a pair
        // at an existing path overwrites, matching what a caller would get
        // by rebuilding via `FromIterator`. Extending with an empty source
        // is a no-op.
        let a = vec!["a".to_string()];
        let b = vec!["b".to_string()];
        let bare = Provenance::computed(ConfigTierKind::Bare);
        let disc = Provenance::computed(ConfigTierKind::Discovered);
        let mut map: ProvenanceMap = vec![(a.clone(), bare.clone())].into_iter().collect();
        assert_eq!(map.len(), 1);
        map.extend(vec![(b.clone(), disc.clone()), (a.clone(), disc.clone())]);
        assert_eq!(map.len(), 2);
        assert_eq!(map.provenance_of_owned(&a), Some(&disc));
        assert_eq!(map.provenance_of_owned(&b), Some(&disc));
        map.extend(std::iter::empty::<(Vec<String>, Provenance)>());
        assert_eq!(map.len(), 2);
    }

    #[test]
    fn into_iter_owned_debug_impl_names_the_struct() {
        // Pin the derived Debug impl at the format-string level: the
        // rendered output names the struct (`ProvenanceMapIntoIter`),
        // matching the same guarantee `ProvenanceMapEntries`'s Debug
        // carries on the borrowing surface.
        let r = Prog::resolve_progressive();
        let it = r.provenance().clone().into_iter();
        let s = format!("{it:?}");
        assert!(
            s.contains("ProvenanceMapIntoIter"),
            "Debug output should name the struct type, got: {s}"
        );
    }

    #[test]
    fn into_iter_owned_return_type_is_nameable_provenance_map_into_iter() {
        // Pin the sharpen at the type-signature level: a struct field
        // bound on `ProvenanceMapIntoIter` holds the handle across a
        // return. This test compiles iff the concrete type is nameable
        // at the API boundary — an `impl Trait` return would fail here.
        struct Held {
            walker: ProvenanceMapIntoIter,
        }
        fn hold(map: ProvenanceMap) -> Held {
            Held {
                walker: map.into_iter(),
            }
        }
        let r = Prog::resolve_progressive();
        let mut h = hold(r.provenance().clone());
        assert!(h.walker.next().is_some());
    }

    #[test]
    fn owned_into_iter_last_returns_trailing_entry() {
        // `.last()` is overridden to route through `next_back` on the
        // underlying `BTreeMap::IntoIter`, so the trailing entry lands
        // in `O(log n)` instead of draining the whole stream. Pin the
        // return value against the last lex-ordered path.
        let r = Prog::resolve_progressive();
        let it = r.provenance().clone().into_iter();
        let (last_path, _) = it.last().unwrap();
        assert_eq!(last_path, vec!["d".to_string()]);
    }

    // ── ProvenanceMap::tier_histogram — cube-native per-tier
    //    leaf-count histogram over the ConfigTierKind closed axis ──

    #[test]
    fn tier_histogram_total_matches_provenance_map_len() {
        // Every leaf projects to exactly one tier cell, so the histogram
        // total is the total leaf count verbatim.
        let r = Prog::resolve_progressive();
        let hist = r.provenance().tier_histogram();
        assert_eq!(hist.total(), r.provenance().len());
        assert_eq!(hist.total(), 4); // Prog has 4 leaves a,b,c,d
    }

    #[test]
    fn tier_histogram_per_tier_count_matches_entries_walk() {
        // Prog fixture: a → Discovered, b → Default, c → Bare, d → Default.
        // Pin the four per-cell counts through the shikumi cube-native
        // per-cell lookup, matching the entries-walk group-by verbatim.
        let r = Prog::resolve_progressive();
        let hist = r.provenance().tier_histogram();
        assert_eq!(hist.count(ConfigTierKind::Bare), 1); // c
        assert_eq!(hist.count(ConfigTierKind::Discovered), 1); // a
        assert_eq!(hist.count(ConfigTierKind::Default), 2); // b, d
        assert_eq!(hist.count(ConfigTierKind::Custom), 0); // no operator overlay
        // The trait-uniform equality against the entries-walk group-by,
        // as documented in the doc-comment invariant table.
        for tier in ConfigTierKind::ALL.iter().copied() {
            let manual = r
                .provenance()
                .entries()
                .filter(|(_, p)| p.tier() == tier)
                .count();
            assert_eq!(
                hist.count(tier),
                manual,
                "per-tier bucket must equal manual entries-walk tally on {tier:?}",
            );
        }
    }

    #[test]
    fn tier_histogram_observed_matches_contributing_tiers_in_precedence_order() {
        // The pin that lets `contributing_tiers` route through the
        // histogram instead of hand-rolling `Vec::contains` + sort:
        // `observed()` yields the histogram's support in closed-axis
        // declaration order, which is `ConfigTier` precedence order.
        let r = Prog::resolve_progressive();
        let observed: Vec<ConfigTierKind> = r.provenance().tier_histogram().observed().collect();
        assert_eq!(observed, r.provenance().contributing_tiers());
        assert_eq!(
            observed,
            vec![
                ConfigTierKind::Bare,
                ConfigTierKind::Discovered,
                ConfigTierKind::Default,
            ],
        );
    }

    #[test]
    fn contributing_tiers_matches_tier_histogram_observed() {
        // The reverse pin: after routing `contributing_tiers` through
        // `tier_histogram().observed().collect()`, the two seams stay
        // pointwise equivalent under every fixture in this module.
        for provenance_map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram: Vec<ConfigTierKind> =
                provenance_map.tier_histogram().observed().collect();
            assert_eq!(provenance_map.contributing_tiers(), via_histogram);
        }
    }

    #[test]
    fn tier_histogram_dominant_cell_names_widest_tier() {
        // In the Prog fixture Default wins the most leaves (b + d = 2);
        // the histogram's argmax picks Default without a per-consumer
        // scan. The tier-level peer of
        // `LayerAttribution::dominant_layer` on the discovered algebra.
        let r = Prog::resolve_progressive();
        assert_eq!(
            r.provenance().tier_histogram().dominant_cell(),
            Some(ConfigTierKind::Default),
        );
    }

    #[test]
    fn tier_histogram_unobserved_names_the_absent_tiers() {
        // Prog fixture has no operator overlay, so `Custom` is the sole
        // unobserved tier cell. The coverage-gap partition on the
        // shikumi cube-native primitive answers "which tier was never
        // heard from?" at one named site.
        let r = Prog::resolve_progressive();
        let unobserved: Vec<ConfigTierKind> =
            r.provenance().tier_histogram().unobserved().collect();
        assert_eq!(unobserved, vec![ConfigTierKind::Custom]);
    }

    #[test]
    fn tier_histogram_is_empty_iff_provenance_map_is_empty() {
        // The empty-boundary invariant: an empty ProvenanceMap yields
        // the monoid-identity histogram, and vice versa. Peer of the
        // `ConfigDiff::kind_histogram` empty-boundary law on the diff
        // altitude.
        let empty = ProvenanceMap::default();
        assert!(empty.is_empty());
        assert!(empty.tier_histogram().is_empty());
        assert_eq!(empty.tier_histogram().total(), 0);
        assert_eq!(empty.contributing_tiers(), Vec::<ConfigTierKind>::new());

        let r = Prog::resolve_progressive();
        assert!(!r.provenance().is_empty());
        assert!(!r.provenance().tier_histogram().is_empty());
    }

    #[test]
    fn tier_histogram_distinct_cells_matches_contributing_tiers_len() {
        // The support-cardinality invariant on the histogram's
        // support-vs-total partition: distinct_cells equals the number
        // of contributing tiers. Any future re-implementation of either
        // seam must keep this equality — pinned uniformly.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.tier_histogram().distinct_cells(),
                map.contributing_tiers().len(),
            );
        }
    }

    // ── ProvenanceMap::absent_tiers — unobserved-cells peer of
    //    contributing_tiers on the tier altitude ──

    #[test]
    fn absent_tiers_matches_tier_histogram_unobserved_pointwise() {
        // The coverage-gap pin: `absent_tiers` routes through
        // `tier_histogram().unobserved().collect()`, so the two seams
        // must stay pointwise equivalent under every fixture. Catches
        // any future drift where either implementation stops projecting
        // through the shared cube-native primitive.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram: Vec<ConfigTierKind> = map.tier_histogram().unobserved().collect();
            assert_eq!(map.absent_tiers(), via_histogram);
        }
    }

    #[test]
    fn absent_tiers_prog_fixture_is_custom_only() {
        // Prog carries no operator overlay: Bare, Discovered, and Default
        // each produce ≥1 leaf, so Custom is the sole coverage-gap cell.
        // The named seam answers the operator's "which tier was never
        // heard from?" question at one call — no `ConfigTierKind::ALL`
        // walk + `Vec::contains` in the fleet dashboard.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().absent_tiers(), vec![ConfigTierKind::Custom]);
    }

    #[test]
    fn absent_tiers_empty_map_is_full_axis() {
        // An empty ProvenanceMap has no leaves and therefore no
        // contributing tiers — every cell of `ConfigTierKind::ALL` lies
        // in the coverage gap. The empty-map / full-coverage-gap
        // boundary of the observed / unobserved partition.
        let empty = ProvenanceMap::default();
        assert_eq!(empty.absent_tiers(), ConfigTierKind::ALL.to_vec());
    }

    #[test]
    fn absent_tiers_iterates_in_declaration_order() {
        // The coverage-gap iter walks `ConfigTierKind::ALL` in
        // declaration order (`Bare → Discovered → Default → Custom`)
        // and yields only the cells with zero count. Pinned here on the
        // empty map, whose gap is the entire axis — the emitted order
        // matches `ConfigTierKind::ALL` verbatim.
        let empty = ProvenanceMap::default();
        assert_eq!(
            empty.absent_tiers(),
            vec![
                ConfigTierKind::Bare,
                ConfigTierKind::Discovered,
                ConfigTierKind::Default,
                ConfigTierKind::Custom,
            ],
        );
    }

    #[test]
    fn absent_tiers_len_matches_unobserved_cells() {
        // The coverage-gap-cardinality invariant on the histogram's
        // support-vs-gap partition: `absent_tiers().len()` equals
        // `tier_histogram().unobserved_cells()` pointwise across every
        // fixture. Any future re-implementation of either seam must
        // keep this equality.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.absent_tiers().len(),
                map.tier_histogram().unobserved_cells(),
            );
        }
    }

    #[test]
    fn absent_tiers_and_contributing_tiers_partition_axis() {
        // The support / coverage-gap partition on the closed axis:
        // every cell of `ConfigTierKind::ALL` lies in exactly one of
        // (observed, unobserved), so the two Vec lengths sum to the
        // axis cardinality. Pinned across every fixture in the module.
        let axis_size = crate::axis_cardinality::<ConfigTierKind>();
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let observed = map.contributing_tiers();
            let absent = map.absent_tiers();
            assert_eq!(observed.len() + absent.len(), axis_size);
            // Disjointness: no cell appears in both.
            for tier in &observed {
                assert!(
                    !absent.contains(tier),
                    "tier {tier:?} appears in both contributing and absent",
                );
            }
            // Union covers the axis: every cell of `ALL` is in one side.
            for cell in ConfigTierKind::ALL {
                assert!(
                    observed.contains(cell) || absent.contains(cell),
                    "tier {cell:?} appears in neither contributing nor absent",
                );
            }
        }
    }

    #[test]
    fn absent_tiers_is_empty_iff_is_full_cover() {
        // The coverage-gap is empty iff every tier contributed ≥1 leaf.
        // Pinned on the Prog fixture (Custom is absent, so not full
        // cover) and cross-verified against
        // `tier_histogram().is_full_cover()`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.absent_tiers().is_empty(),
                map.tier_histogram().is_full_cover(),
            );
        }
        // Direct pin: Prog has no Custom overlay → not full cover, and
        // the coverage-gap is nonempty.
        let prog = Prog::resolve_progressive();
        assert!(!prog.provenance().tier_histogram().is_full_cover());
        assert!(!prog.provenance().absent_tiers().is_empty());
    }

    #[test]
    fn absent_tiers_is_strictly_ascending_by_axis_ordinal() {
        // Structural sort pin: the coverage-gap walks the closed axis
        // in declaration order, so `absent_tiers()` is strictly
        // ascending by `crate::axis_ordinal` — the dedup + sort every
        // hand-rolled walk would have to spell explicitly comes for
        // free from the closed-axis discipline.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let absent = map.absent_tiers();
            for pair in absent.windows(2) {
                assert!(
                    crate::axis_ordinal(pair[0]) < crate::axis_ordinal(pair[1]),
                    "absent_tiers must be strictly ascending: {absent:?}",
                );
            }
        }
    }

    #[test]
    fn absent_tiers_full_cover_yields_empty() {
        // The full-cover positive case: a ProvenanceMap containing
        // ≥1 leaf on every tier has an empty coverage-gap. Constructed
        // by overlaying a Custom operator layer on Prog (which already
        // spans Bare + Discovered + Default) — every tier now
        // contributes at least one leaf, so `absent_tiers()` is empty
        // and `tier_histogram()` is full-cover.
        let mut d = Dict::new();
        d.insert("b".to_owned(), Value::from(99_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::file("/etc/prog.yaml", d)]);
        assert!(r.provenance().tier_histogram().is_full_cover());
        assert_eq!(r.provenance().absent_tiers(), Vec::<ConfigTierKind>::new());
        // And symmetrically, the observed peer equals `ConfigTierKind::ALL`
        // (in declaration order) at full cover.
        assert_eq!(
            r.provenance().contributing_tiers(),
            ConfigTierKind::ALL.to_vec(),
        );
    }

    #[test]
    fn absent_tiers_agrees_with_open_coded_coverage_gap_walk() {
        // Parity against the exact `ConfigTierKind::ALL.iter().filter(|t|
        // !contributing_tiers().contains(t))` walk this lift replaces —
        // both the named seam and the hand-rolled coverage-gap must
        // pointwise agree over every fixture in the module.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.absent_tiers();
            let contributing = map.contributing_tiers();
            let hand_rolled: Vec<ConfigTierKind> = ConfigTierKind::ALL
                .iter()
                .copied()
                .filter(|t| !contributing.contains(t))
                .collect();
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── ProvenanceMap::contributing_tiers_count — support-size scalar
    //    peer of contributing_tiers on the tier altitude ──

    #[test]
    fn contributing_tiers_count_matches_tier_histogram_distinct_cells_pointwise() {
        // The support-size pin: `contributing_tiers_count` routes through
        // `tier_histogram().distinct_cells()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through the
        // shared cube-native primitive. Peer of
        // `contributing_tiers_matches_tier_histogram_observed` on the
        // observed-cells-vector side of the same primitive.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().distinct_cells();
            assert_eq!(map.contributing_tiers_count(), via_histogram);
        }
    }

    #[test]
    fn contributing_tiers_count_equals_contributing_tiers_len_pointwise() {
        // The Vec-peer identity: the scalar-count seam equals the length
        // of the observed-cells `Vec` peer. Any future re-implementation
        // of either seam must keep this equality — pinned uniformly. Peer
        // to `tier_histogram_distinct_cells_matches_contributing_tiers_len`
        // on the histogram side.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.contributing_tiers_count(),
                map.contributing_tiers().len(),
            );
        }
    }

    #[test]
    fn contributing_tiers_count_and_absent_tiers_len_partition_axis_cardinality() {
        // The partition law: the scalar dual of
        // `absent_tiers_and_contributing_tiers_partition_axis`. Every
        // tier cell lies in exactly one of {contributing, absent}, so the
        // two scalars sum to the axis cardinality without remainder on
        // every fixture — including the empty map (`0 + 4 == 4`) and any
        // full-cover map (`4 + 0 == 4`).
        use crate::cube::axis_cardinality;
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.contributing_tiers_count() + map.absent_tiers().len(),
                axis_cardinality::<ConfigTierKind>(),
            );
        }
    }

    #[test]
    fn contributing_tiers_count_is_zero_iff_map_is_empty() {
        // The empty-boundary equivalence: a zero-support fold has zero
        // leaves and vice versa. Peer to `dominant_tier_empty_map_is_none`
        // / `absent_tiers_empty_map_is_full_axis` on the empty-boundary
        // side of the tier altitude, and the tier-altitude peer of the
        // `AxisHistogram::is_empty` primitive one altitude down.
        let empty = ProvenanceMap::default();
        assert_eq!(empty.contributing_tiers_count(), 0);
        assert!(empty.is_empty());

        // The Prog fixture is non-empty: three of the four tiers
        // (Bare, Discovered, Default) contribute, so the support-size
        // scalar reads a non-zero value.
        let r = Prog::resolve_progressive();
        assert!(!r.provenance().is_empty());
        assert!(r.provenance().contributing_tiers_count() > 0);
    }

    #[test]
    fn contributing_tiers_count_is_at_least_one_on_nonempty_map() {
        // The lower-bound invariant: the support of a non-empty map
        // carries at least the singleton of the first-leaf tier. Peer to
        // `peak_tier_count_is_at_least_one_on_nonempty_map` and
        // `trough_tier_count_is_at_least_one_on_nonempty_map` on the
        // modal-count side of the tier altitude.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            assert!(!map.is_empty());
            assert!(map.contributing_tiers_count() >= 1);
        }
    }

    #[test]
    fn contributing_tiers_count_is_bounded_by_axis_cardinality() {
        // The upper-bound invariant: the support of a closed-axis
        // histogram is at most the axis cardinality (the observed-cells
        // set is a subset of `ConfigTierKind::ALL`). Peer to the
        // trait-uniform `distinct_cells() <= axis_cardinality()` law on
        // `AxisHistogram` one altitude down.
        use crate::cube::axis_cardinality;
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert!(map.contributing_tiers_count() <= axis_cardinality::<ConfigTierKind>());
        }
    }

    #[test]
    fn contributing_tiers_count_is_bounded_by_tier_histogram_total() {
        // The support ≤ total invariant: every distinct cell contributes
        // at least one observation to the total, so the support size is
        // bounded above by the total observation count. Peer to the
        // trait-uniform `distinct_cells() <= total()` law on
        // `AxisHistogram` one altitude down.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert!(map.contributing_tiers_count() <= map.tier_histogram().total());
        }
    }

    #[test]
    fn contributing_tiers_count_equals_axis_cardinality_iff_is_full_cover() {
        // The full-cover boundary equivalence: the support size equals
        // the axis cardinality iff every tier contributed ≥1 leaf iff
        // the coverage gap is empty. Peer to
        // `absent_tiers_is_empty_iff_is_full_cover` on the coverage-gap
        // side and the tier-altitude lift of the trait-uniform
        // `is_full_cover() ⇔ distinct_cells() == axis_cardinality()`
        // law on `AxisHistogram`.
        use crate::cube::axis_cardinality;
        // Full-cover fixture: a Custom overlay on Prog (Bare + Discovered
        // + Default already contribute) touches ONLY `b` so the other
        // leaves keep their prior attribution — every tier now contributes
        // at least one leaf, so `tier_histogram()` reaches full cover.
        let mut d = Dict::new();
        d.insert("b".to_owned(), Value::from(99_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::file("/etc/prog.yaml", d)]);
        assert!(r.provenance().tier_histogram().is_full_cover());
        assert_eq!(
            r.provenance().contributing_tiers_count(),
            axis_cardinality::<ConfigTierKind>(),
        );

        // Non-full-cover: Prog fixture has no operator overlay, so
        // Custom is absent — support strictly less than axis cardinality.
        let r = Prog::resolve_progressive();
        assert!(!r.provenance().tier_histogram().is_full_cover());
        assert!(r.provenance().contributing_tiers_count() < axis_cardinality::<ConfigTierKind>(),);
    }

    #[test]
    fn contributing_tiers_count_is_one_iff_has_singular_support() {
        // The singleton-support boundary equivalence: the support size
        // equals 1 iff exactly one tier contributes iff the histogram
        // has singular support. Peer to
        // `AxisHistogram::has_singular_support` one altitude down.
        //
        // Singleton-support fixture: a single Default layer overrides
        // every leaf so only Default contributes.
        let mut d = Dict::new();
        d.insert("a".to_owned(), Value::from(11_u32));
        d.insert("b".to_owned(), Value::from(22_u32));
        d.insert("c".to_owned(), Value::from(33_u32));
        d.insert("d".to_owned(), Value::from(44_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::new(
            Provenance::computed(ConfigTierKind::Default),
            d,
        )]);
        assert!(r.provenance().tier_histogram().has_singular_support());
        assert_eq!(r.provenance().contributing_tiers_count(), 1);

        // Non-singleton-support: Prog fixture spans three tiers, so the
        // support size is > 1 and singular_support reads false.
        let r = Prog::resolve_progressive();
        assert!(!r.provenance().tier_histogram().has_singular_support());
        assert!(r.provenance().contributing_tiers_count() > 1);
    }

    #[test]
    fn contributing_tiers_count_of_one_implies_dominant_equals_recessive() {
        // The support-collapse degenerate: a singleton-support fold has
        // the modal and anti-modal cells coincide on the sole observed
        // tier. The scalar-count peer witnesses the collapse without
        // needing to name which cell survives. Peer to
        // `recessive_tier_singleton_support_agrees_with_dominant_tier`
        // on the cell side of the same collapse.
        let mut d = Dict::new();
        d.insert("a".to_owned(), Value::from(11_u32));
        d.insert("b".to_owned(), Value::from(22_u32));
        d.insert("c".to_owned(), Value::from(33_u32));
        d.insert("d".to_owned(), Value::from(44_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::new(
            Provenance::computed(ConfigTierKind::Default),
            d,
        )]);
        assert_eq!(r.provenance().contributing_tiers_count(), 1);
        assert_eq!(
            r.provenance().dominant_tier(),
            r.provenance().recessive_tier()
        );
    }

    #[test]
    fn contributing_tiers_count_agrees_with_open_coded_nonzero_walk() {
        // Parity against the exact
        // `ConfigTierKind::ALL.iter().filter(|t|
        // tier_histogram().count(*t) > 0).count()` walk this lift
        // replaces — both the named seam and the hand-rolled
        // nonzero-cell scan must pointwise agree over every fixture in
        // the module. Pins the load-bearing `>0` filter that keeps the
        // naive `.iter().count()` from silently counting zero-count
        // absent cells on any non-full-cover histogram.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.contributing_tiers_count();
            let hist = map.tier_histogram();
            let hand_rolled = ConfigTierKind::ALL
                .iter()
                .copied()
                .filter(|t| hist.count(*t) > 0)
                .count();
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn contributing_tiers_count_prog_fixture_is_three() {
        // Direct fixture pin: Prog attributes 4 leaves across 3 tiers
        // (Discovered, Default×2, Bare), so the support size reads 3.
        // Peer to `dominant_tier_prog_fixture_is_default` on the same
        // fixture and altitude.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().contributing_tiers_count(), 3);
    }

    #[test]
    fn contributing_tiers_count_nested_fixture_is_two() {
        // Direct fixture pin: Nested attributes 3 leaves across 2 tiers
        // (Discovered, Default×2), so the support size reads 2 — one
        // tier fewer than Prog because Nested's third leaf shares
        // Default with its second. Peer to
        // `dominant_tier_nested_fixture_is_default` on the same fixture
        // and altitude.
        let r = Nested::resolve_progressive();
        assert_eq!(r.provenance().contributing_tiers_count(), 2);
    }

    // ── ProvenanceMap::absent_tiers_count — coverage-gap-size scalar
    //    peer on the tier altitude ──

    #[test]
    fn absent_tiers_count_matches_tier_histogram_unobserved_cells_pointwise() {
        // The coverage-gap-size pin: `absent_tiers_count` routes through
        // `tier_histogram().unobserved_cells()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Tier-altitude
        // coverage-gap peer of
        // `absent_kinds_count_matches_kind_histogram_unobserved_cells_pointwise`
        // on the diff altitude, and support-side peer of
        // `contributing_tiers_count_matches_tier_histogram_distinct_cells_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().unobserved_cells();
            assert_eq!(
                map.absent_tiers_count(),
                via_histogram,
                "absent_tiers_count must equal tier_histogram().unobserved_cells() pointwise",
            );
        }
    }

    #[test]
    fn absent_tiers_count_equals_absent_tiers_len_pointwise() {
        // The Vec-peer identity: the scalar-count seam equals the length
        // of the coverage-gap `Vec` peer. Any future re-implementation of
        // either seam must keep this equality — pinned uniformly.
        // Tier-altitude coverage-gap peer of
        // `absent_kinds_count_equals_absent_kinds_len_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(map.absent_tiers_count(), map.absent_tiers().len());
        }
    }

    #[test]
    fn contributing_tiers_count_and_absent_tiers_count_partition_axis_cardinality() {
        // The fully-scalar partition law: both sides now the scalar-count
        // peers, no `.len()` on either. Every tier cell lies in exactly
        // one of (observed, unobserved). The scalar dual of
        // `absent_tiers_and_contributing_tiers_partition_axis` closed on
        // both sides. Sits alongside
        // `contributing_tiers_count_and_absent_tiers_len_partition_axis_cardinality`
        // which still uses `.len()` on the coverage-gap side.
        use crate::cube::axis_cardinality;
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.contributing_tiers_count() + map.absent_tiers_count(),
                axis_cardinality::<ConfigTierKind>(),
            );
        }
    }

    #[test]
    fn absent_tiers_count_equals_axis_cardinality_minus_contributing_tiers_count() {
        // The algebraic rearrangement: the coverage-gap size equals the
        // axis cardinality minus the support size, useful for consumers
        // that already hold the support-size scalar. Tier-altitude peer
        // of `absent_kinds_count_equals_axis_cardinality_minus_present_kinds_count`.
        use crate::cube::axis_cardinality;
        let axis_size = axis_cardinality::<ConfigTierKind>();
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.absent_tiers_count(),
                axis_size - map.contributing_tiers_count(),
            );
        }
    }

    #[test]
    fn absent_tiers_count_is_axis_cardinality_iff_map_is_empty() {
        // The empty-map / full-coverage-gap boundary equivalence: an
        // empty map has every tier absent (the coverage gap is the whole
        // axis), and a non-empty map has at least one tier observed so
        // the coverage-gap is strictly smaller. The scalar peer of
        // `absent_tiers_empty_map_is_full_axis` and the tier-altitude peer
        // of `absent_kinds_count_is_axis_cardinality_iff_diff_is_empty`.
        use crate::cube::axis_cardinality;
        let axis_size = axis_cardinality::<ConfigTierKind>();

        let empty = ProvenanceMap::default();
        assert!(empty.is_empty());
        assert_eq!(empty.absent_tiers_count(), axis_size);

        // Non-empty fixtures: at least one tier surfaces, so the
        // coverage-gap is strictly less than the axis cardinality.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            assert!(!map.is_empty());
            assert!(map.absent_tiers_count() < axis_size);
        }
    }

    #[test]
    fn absent_tiers_count_is_zero_iff_is_full_cover() {
        // The full-cover boundary equivalence in coverage-gap form: the
        // coverage gap is empty iff every tier contributed ≥1 leaf iff
        // the histogram is full-cover. The tier-altitude scalar-count
        // coverage-gap peer of `AxisHistogram::is_full_cover` and peer of
        // `absent_kinds_count_is_zero_iff_is_full_cover` on the diff
        // altitude.

        // Full-cover: a Custom overlay on Prog (Bare + Discovered + Default
        // already contribute) touches ONLY `b` so the other leaves keep
        // their prior attribution — every tier now contributes at least
        // one leaf, so `tier_histogram()` reaches full cover.
        let mut d = Dict::new();
        d.insert("b".to_owned(), Value::from(99_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::file("/etc/prog.yaml", d)]);
        assert!(r.provenance().tier_histogram().is_full_cover());
        assert_eq!(r.provenance().absent_tiers_count(), 0);

        // Non-full-cover: Prog fixture has no operator overlay, so
        // Custom is absent — coverage gap is nonempty.
        let r = Prog::resolve_progressive();
        assert!(!r.provenance().tier_histogram().is_full_cover());
        assert!(r.provenance().absent_tiers_count() > 0);

        // Empty map: coverage gap is the entire axis, so it's strictly
        // greater than 0.
        let empty = ProvenanceMap::default();
        assert!(!empty.tier_histogram().is_full_cover());
        assert!(empty.absent_tiers_count() > 0);
    }

    #[test]
    fn absent_tiers_count_is_bounded_by_axis_cardinality() {
        // The upper-bound invariant: the coverage gap of a closed-axis
        // histogram is at most the axis cardinality (the unobserved-cells
        // set is a subset of `ConfigTierKind::ALL`). Tier-altitude peer of
        // the trait-uniform `unobserved_cells() <= axis_cardinality()` law
        // on `AxisHistogram` one altitude down.
        use crate::cube::axis_cardinality;
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert!(map.absent_tiers_count() <= axis_cardinality::<ConfigTierKind>());
        }
    }

    #[test]
    fn absent_tiers_count_is_at_least_one_when_not_full_cover() {
        // A non-full-cover fold carries at least one absent tier. The
        // coverage-gap-side lower bound on non-full-cover, dual to
        // `contributing_tiers_count_is_at_least_one_on_nonempty_map` on
        // the observed side, and peer of
        // `absent_kinds_count_is_at_least_one_when_not_full_cover` on
        // the diff altitude.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            if map.tier_histogram().is_full_cover() {
                continue;
            }
            assert!(map.absent_tiers_count() >= 1);
        }
    }

    #[test]
    fn absent_tiers_count_is_axis_cardinality_minus_one_iff_has_singular_support() {
        // The singleton-support boundary in coverage-gap form: when
        // exactly one tier is observed, exactly `axis_cardinality - 1`
        // are absent. Tier-altitude coverage-gap peer of
        // `contributing_tiers_count_is_one_iff_has_singular_support` and
        // `absent_kinds_count_is_axis_cardinality_minus_one_iff_has_singular_support`.
        use crate::cube::axis_cardinality;
        let axis_size = axis_cardinality::<ConfigTierKind>();

        // Singleton-support: a single Default layer overrides every leaf
        // so only Default contributes — three tiers absent.
        let mut d = Dict::new();
        d.insert("a".to_owned(), Value::from(11_u32));
        d.insert("b".to_owned(), Value::from(22_u32));
        d.insert("c".to_owned(), Value::from(33_u32));
        d.insert("d".to_owned(), Value::from(44_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::new(
            Provenance::computed(ConfigTierKind::Default),
            d,
        )]);
        assert!(r.provenance().tier_histogram().has_singular_support());
        assert_eq!(r.provenance().absent_tiers_count(), axis_size - 1);

        // Non-singleton-support: Prog spans three tiers so coverage-gap
        // is strictly less than `axis_cardinality - 1`.
        let r = Prog::resolve_progressive();
        assert!(!r.provenance().tier_histogram().has_singular_support());
        assert!(r.provenance().absent_tiers_count() < axis_size - 1);

        // Empty map: no support at all, coverage gap is the full axis
        // (strictly greater than `axis_cardinality - 1`).
        let empty = ProvenanceMap::default();
        assert!(!empty.tier_histogram().has_singular_support());
        assert!(empty.absent_tiers_count() > axis_size - 1);
    }

    #[test]
    fn absent_tiers_count_agrees_with_open_coded_zero_walk() {
        // Parity against the exact `ConfigTierKind::ALL.iter().filter(|t|
        // tier_histogram().count(*t) == 0).count()` walk this lift
        // replaces on the coverage-gap side. Tier-altitude peer of
        // `absent_kinds_count_agrees_with_open_coded_zero_walk`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.absent_tiers_count();
            let hist = map.tier_histogram();
            let hand_rolled = ConfigTierKind::ALL
                .iter()
                .copied()
                .filter(|t| hist.count(*t) == 0)
                .count();
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn absent_tiers_count_empty_map_is_axis_cardinality() {
        // Direct fixture pin: an empty ProvenanceMap has full coverage
        // gap so `absent_tiers_count` reads the axis cardinality
        // (4 = |{Bare, Discovered, Default, Custom}|).
        use crate::cube::axis_cardinality;
        let empty = ProvenanceMap::default();
        assert_eq!(
            empty.absent_tiers_count(),
            axis_cardinality::<ConfigTierKind>(),
        );
    }

    #[test]
    fn absent_tiers_count_full_cover_is_zero() {
        // Direct fixture pin: a ProvenanceMap containing ≥1 leaf on every
        // tier has an empty coverage gap so `absent_tiers_count` reads 0.
        // Peer of `absent_kinds_count_full_cover_is_zero` on the diff
        // altitude.
        let mut d = Dict::new();
        d.insert("b".to_owned(), Value::from(99_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::file("/etc/prog.yaml", d)]);
        assert_eq!(r.provenance().absent_tiers_count(), 0);
    }

    #[test]
    fn absent_tiers_count_prog_fixture_is_one() {
        // Direct fixture pin: Prog attributes 4 leaves across 3 tiers
        // (Bare, Discovered, Default), so Custom is the sole coverage-gap
        // cell and `absent_tiers_count` reads 1. Coverage-gap peer of
        // `contributing_tiers_count_prog_fixture_is_three` on the same
        // fixture and altitude.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().absent_tiers_count(), 1);
    }

    #[test]
    fn absent_tiers_count_nested_fixture_is_two() {
        // Direct fixture pin: Nested attributes 3 leaves across 2 tiers
        // (Discovered, Default), so Bare and Custom are the coverage-gap
        // cells and `absent_tiers_count` reads 2. Coverage-gap peer of
        // `contributing_tiers_count_nested_fixture_is_two` on the same
        // fixture and altitude.
        let r = Nested::resolve_progressive();
        assert_eq!(r.provenance().absent_tiers_count(), 2);
    }

    #[test]
    fn dominant_tier_matches_tier_histogram_dominant_cell_pointwise() {
        // The modal-cell pin: `dominant_tier` routes through
        // `tier_histogram().dominant_cell()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().dominant_cell();
            assert_eq!(map.dominant_tier(), via_histogram);
        }
    }

    #[test]
    fn dominant_tier_prog_fixture_is_default() {
        // Prog attributes 4 leaves: a→Discovered, b→Default, c→Bare,
        // d→Default. Default holds 2 of 4, uniquely dominant on the
        // 4-cell tier axis. Direct pin — the named seam answers the
        // operator's *"which tier dominated this resolved fold?"*
        // question at one call, no `max_by_key` walk in the dashboard.
        let r = Prog::resolve_progressive();
        assert_eq!(
            r.provenance().dominant_tier(),
            Some(ConfigTierKind::Default)
        );
    }

    #[test]
    fn dominant_tier_nested_fixture_is_default() {
        // Nested attributes 3 leaves: win.w→Discovered, win.h→Default,
        // theme→Default. Default holds 2 of 3, uniquely dominant on the
        // tier axis under nested per-leaf attribution — the modal cell
        // reads through the seam whether the fixture is flat or nested.
        let r = Nested::resolve_progressive();
        assert_eq!(
            r.provenance().dominant_tier(),
            Some(ConfigTierKind::Default)
        );
    }

    #[test]
    fn dominant_tier_empty_map_is_none() {
        // An empty ProvenanceMap has no leaves and therefore no modal
        // tier — the empty-map / empty-histogram boundary of the
        // dominant-cell projection. Peer to
        // `absent_tiers_empty_map_is_full_axis` (the same boundary on
        // the coverage-gap side).
        let empty = ProvenanceMap::default();
        assert_eq!(empty.dominant_tier(), None);
    }

    #[test]
    fn dominant_tier_is_some_iff_map_is_nonempty() {
        // Cross-surface pin: the presence-of-modal-cell predicate
        // agrees with the non-emptiness of the underlying map.
        // Structural completeness of the `(is_empty, dominant_tier)`
        // boundary — a well-formed fold with ≥1 leaf always has a
        // modal cell, and an empty fold never does.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(map.dominant_tier().is_some(), !map.is_empty());
        }
    }

    #[test]
    fn dominant_tier_is_member_of_contributing_tiers() {
        // Structural pin: whenever `dominant_tier()` is `Some(t)`, `t`
        // must appear in `contributing_tiers()` (the modal cell is by
        // definition observed). The support / dominance partition on
        // the tier altitude reads consistently between the two named
        // seams.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let dominant = map
                .dominant_tier()
                .expect("non-empty map has dominant tier");
            assert!(
                map.contributing_tiers().contains(&dominant),
                "dominant tier {dominant:?} must appear in contributing_tiers",
            );
        }
    }

    #[test]
    fn dominant_tier_is_not_member_of_absent_tiers() {
        // Structural pin: whenever `dominant_tier()` is `Some(t)`, `t`
        // must NOT appear in `absent_tiers()` — the modal cell lies on
        // the observed side of the observed / coverage-gap partition.
        // Disjointness pin between the two named seams.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let dominant = map
                .dominant_tier()
                .expect("non-empty map has dominant tier");
            assert!(
                !map.absent_tiers().contains(&dominant),
                "dominant tier {dominant:?} must not appear in absent_tiers",
            );
        }
    }

    #[test]
    fn dominant_tier_count_equals_peak_count_on_nonempty_map() {
        // The (dominant_cell, peak_count) modal-pair invariant lifted
        // to the tier altitude: the observation count of the dominant
        // tier equals the histogram's peak count. Pins the fused form
        // of the modal-pair the AxisHistogram surface carries as
        // (dominant_cell(), peak_count()).
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let hist = map.tier_histogram();
            let dominant = map
                .dominant_tier()
                .expect("non-empty map has dominant tier");
            assert_eq!(hist.count(dominant), hist.peak_count());
        }
    }

    #[test]
    fn dominant_tier_ties_broken_by_declaration_order() {
        // Structural tie-breaking pin: on a uniform per-tier fold
        // (each of the four `ConfigTierKind` cells contributing
        // exactly one leaf), `dominant_tier` reports
        // `Some(ConfigTierKind::Bare)` — the first cell in
        // `ConfigTierKind::ALL` declaration order. Constructed by
        // overlaying a Custom operator layer on Prog (which spans
        // Bare→Discovered→Default with 4 leaves distributed 1/1/2)
        // that steals the second Default-tier leaf (b) into Custom,
        // yielding a 1-leaf-per-tier full-cover fold. Any future
        // switch to a nondeterministic `max_by_key` walk (which
        // silently picks the LAST tied cell) would flip this pin to
        // `Some(Custom)` — the seam names the tiebreak once.
        let mut d = Dict::new();
        d.insert("b".to_owned(), Value::from(99_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::file("/etc/prog.yaml", d)]);
        // Sanity: this construction produces the intended tier-count
        // distribution (each tier owns exactly one leaf).
        let hist = r.provenance().tier_histogram();
        assert_eq!(hist.count(ConfigTierKind::Bare), 1);
        assert_eq!(hist.count(ConfigTierKind::Discovered), 1);
        assert_eq!(hist.count(ConfigTierKind::Default), 1);
        assert_eq!(hist.count(ConfigTierKind::Custom), 1);
        assert!(hist.is_full_cover());
        // Tiebreak lands on the first cell in declaration order.
        assert_eq!(r.provenance().dominant_tier(), Some(ConfigTierKind::Bare));
    }

    #[test]
    fn dominant_tier_agrees_with_open_coded_argmax_walk() {
        // Parity against the exact `hist.iter().filter(|&(_, c)| c > 0)
        // .max_by(count-then-declaration-order)` walk this lift replaces
        // — both the named seam and the hand-rolled argmax must
        // pointwise agree over every fixture in the module. The
        // hand-rolled form spells the declaration-order tiebreak
        // explicitly (fold-forward with strict `>` inequality — the
        // first tied cell wins, mirroring `AxisHistogram::dominant_cell`
        // — rather than `max_by_key`'s LAST-tied-cell semantics).
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.dominant_tier();
            let hist = map.tier_histogram();
            let mut iter = hist.iter().filter(|&(_, c)| c > 0);
            let hand_rolled = iter.next().map(|first| {
                iter.fold(
                    first,
                    |best, current| {
                        if current.1 > best.1 { current } else { best }
                    },
                )
                .0
            });
            assert_eq!(via_seam, hand_rolled);
        }
    }

    #[test]
    fn dominant_tier_uniform_cover_picks_first_cell() {
        // Trait-uniform invariant: on a full-cover fold where every
        // tier observes the same nonzero count, the dominant cell is
        // the first cell of `ConfigTierKind::ALL` — the declaration-
        // order tiebreak reduces to `Some(Bare)`. Peer of the trait-
        // uniform `axis_histogram_dominant_cell_axis_cover_picks_first_*`
        // laws in cube tests.
        // Direct construction via `FromIterator`: one leaf per tier,
        // full-cover with uniform count 1. `dominant_cell` then reduces
        // to *"first cell of `ConfigTierKind::ALL`"* — the pin lives in
        // the tiered.rs surface for the ProvenanceMap-scoped seam, not
        // just the cube-generic trait law.
        let m: ProvenanceMap = ConfigTierKind::ALL
            .iter()
            .copied()
            .map(|t| (vec![t.as_str().to_owned()], Provenance::computed(t)))
            .collect();
        assert!(m.tier_histogram().is_full_cover());
        assert_eq!(m.dominant_tier(), Some(ConfigTierKind::Bare));
    }

    // ---- ProvenanceMap::peak_tier_count — modal-cell scalar-count peer
    //      of ProvenanceMap::tier_histogram on the tier altitude, fusing
    //      with dominant_tier into the (cell, count) modal pair ----

    #[test]
    fn peak_tier_count_matches_tier_histogram_peak_count_pointwise() {
        // The scalar-count pin: `peak_tier_count` routes through
        // `tier_histogram().peak_count()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through the
        // shared cube-native primitive. Peer of
        // `dominant_tier_matches_tier_histogram_dominant_cell_pointwise`
        // on the count side.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().peak_count();
            assert_eq!(map.peak_tier_count(), via_histogram);
        }
    }

    #[test]
    fn peak_tier_count_prog_fixture_is_two() {
        // Prog attributes 4 leaves: a→Discovered, b→Default, c→Bare,
        // d→Default. Counts: Bare=1, Discovered=1, Default=2, Custom=0.
        // The peak lands on Default at count 2. Direct pin — the named
        // seam answers the operator's *"how many leaves did the dominant
        // tier collect?"* at one call, no `peak_count` re-derivation in
        // the dashboard.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().peak_tier_count(), 2);
    }

    #[test]
    fn peak_tier_count_nested_fixture_is_two() {
        // Nested attributes 3 leaves: win.w→Discovered, win.h→Default,
        // theme→Default. Counts: Bare=0, Discovered=1, Default=2,
        // Custom=0. The peak lands on Default at count 2 — the scalar
        // reads through the seam whether the fixture is flat or nested.
        let r = Nested::resolve_progressive();
        assert_eq!(r.provenance().peak_tier_count(), 2);
    }

    #[test]
    fn peak_tier_count_empty_map_is_zero() {
        // An empty ProvenanceMap has no leaves and therefore no peak —
        // the empty-map / empty-histogram boundary of the scalar-count
        // projection reads `0` (matching the [`AxisHistogram::peak_count`]
        // empty convention one altitude down, and the `Self::len` empty
        // convention on the same altitude). Peer to
        // `dominant_tier_empty_map_is_none` on the cell side — the fused
        // pair `(dominant_tier(), peak_tier_count())` reads `(None, 0)`
        // uniformly on the empty map.
        let empty = ProvenanceMap::default();
        assert_eq!(empty.peak_tier_count(), 0);
    }

    #[test]
    fn peak_tier_count_is_zero_iff_map_is_empty() {
        // Cross-surface pin: the zero-peak predicate agrees with the
        // emptiness of the underlying map. Structural completeness of
        // the `(is_empty, peak_tier_count == 0)` boundary — a well-formed
        // fold with ≥1 leaf always has a positive peak, and an empty
        // fold always has zero peak. The count-side dual of
        // `dominant_tier_is_some_iff_map_is_nonempty`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(map.peak_tier_count() == 0, map.is_empty());
        }
    }

    #[test]
    fn peak_tier_count_equals_count_at_dominant_tier_on_nonempty_map() {
        // The (dominant_cell, peak_count) modal-pair invariant lifted to
        // the tier altitude on the ProvenanceMap surface: the scalar-
        // count reads pointwise identical to `count(dominant_tier)`.
        // Peer of `dominant_tier_count_equals_peak_count_on_nonempty_map`
        // — that test pins the histogram-side identity
        // `hist.count(dominant_tier) == hist.peak_count()`; this test
        // pins the ProvenanceMap-side identity `count(dominant_tier) ==
        // peak_tier_count()` at the fused-pair seam.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let hist = map.tier_histogram();
            let dominant = map
                .dominant_tier()
                .expect("non-empty map has dominant tier");
            assert_eq!(hist.count(dominant), map.peak_tier_count());
        }
    }

    #[test]
    fn peak_tier_count_equals_dominant_tier_map_or_count() {
        // The fused-pair identity `peak_tier_count() ==
        // dominant_tier().map_or(0, |t| tier_histogram().count(t))` on
        // every input — the count projection of the (dominant_tier,
        // peak_tier_count) modal pair reads through the seam uniformly
        // across the empty-map / non-empty-map partition. Includes the
        // empty map (`None.map_or(0, …) == 0 == peak_tier_count`) —
        // this is the pin that the fused-pair identity is boundary-
        // complete.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let hist = map.tier_histogram();
            let via_fused_pair = map.dominant_tier().map_or(0, |t| hist.count(t));
            assert_eq!(map.peak_tier_count(), via_fused_pair);
        }
    }

    #[test]
    fn peak_tier_count_is_bounded_by_len() {
        // Structural bound `peak_tier_count() <= len()` on every input —
        // the peak is bounded above by the total leaf count (every tier
        // contributes at most every leaf, the others contribute zero).
        // Lifted from the trait-uniform `peak_count() <= total()` law on
        // AxisHistogram.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert!(
                map.peak_tier_count() <= map.len(),
                "peak_tier_count()={p} must be <= len()={n}",
                p = map.peak_tier_count(),
                n = map.len(),
            );
        }
    }

    #[test]
    fn peak_tier_count_equals_len_iff_at_most_one_contributing_tier() {
        // Structural bound `peak_tier_count() == len()` iff
        // `contributing_tiers().len() <= 1` — the peak equals the total
        // exactly when zero or one tier is observed. Zero: empty map,
        // both zero. One: singleton-support fold, every leaf on the same
        // tier. Two or more: peak strictly below total. Lifted from the
        // trait-uniform `peak_count() == total()` law on AxisHistogram.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.peak_tier_count() == map.len(),
                map.contributing_tiers().len() <= 1,
                "peak_tier_count == len iff contributing_tiers.len() <= 1 (peak={p}, len={n}, contribs={c})",
                p = map.peak_tier_count(),
                n = map.len(),
                c = map.contributing_tiers().len(),
            );
        }
    }

    #[test]
    fn peak_tier_count_is_at_least_one_on_nonempty_map() {
        // Structural pin: whenever `!is_empty()`, `peak_tier_count() >=
        // 1` — a non-empty map always has at least one leaf on the
        // dominant tier. Combined with the `<= len()` bound above, this
        // pins `1 <= peak_tier_count() <= len()` on every non-empty map.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            assert!(
                map.peak_tier_count() >= 1,
                "non-empty map must have peak_tier_count >= 1 (peak={p})",
                p = map.peak_tier_count(),
            );
        }
    }

    #[test]
    fn peak_tier_count_uniform_cover_is_one() {
        // Trait-uniform invariant lifted to the ProvenanceMap surface:
        // on a full-cover fold where every tier observes the same
        // nonzero count of one, the peak count is `1`. Direct
        // construction: one leaf per tier, full-cover with uniform count
        // 1. Peer of `dominant_tier_uniform_cover_picks_first_cell` on
        // the count side (that test pins the *cell*; this test pins the
        // *count*). Together the pair `(dominant_tier, peak_tier_count)`
        // reads `(Some(Bare), 1)` on the uniform-cover fold.
        let m: ProvenanceMap = ConfigTierKind::ALL
            .iter()
            .copied()
            .map(|t| (vec![t.as_str().to_owned()], Provenance::computed(t)))
            .collect();
        assert!(m.tier_histogram().is_full_cover());
        assert_eq!(m.peak_tier_count(), 1);
    }

    #[test]
    fn peak_tier_count_singleton_support_equals_len() {
        // Singleton-support degenerate: when only one tier contributes,
        // every leaf lands on that tier, so the peak equals the total.
        // Direct construction: three leaves, all on `Default`. The
        // scalar peer of the singleton-support cell degenerate
        // `dominant_tier() == recessive_tier()` in
        // `recessive_tier_singleton_support_agrees_with_dominant_tier`
        // — that test pins the *cell*; this test pins the *count*
        // through the `peak_tier_count() == len()` equality on the
        // singleton-support boundary.
        let m: ProvenanceMap = ["a", "b", "c"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Default),
                )
            })
            .collect();
        assert_eq!(m.contributing_tiers().len(), 1);
        assert_eq!(m.peak_tier_count(), m.len());
        assert_eq!(m.peak_tier_count(), 3);
    }

    #[test]
    fn peak_tier_count_agrees_with_open_coded_max_over_axis_walk() {
        // Parity against the exact `hist.iter().map(|(_, c)| c).max()`
        // walk this lift replaces — both the named seam and the hand-
        // rolled max must pointwise agree over every fixture in the
        // module. The `.max().unwrap_or(0)` idiom mirrors the empty-
        // histogram convention on `AxisHistogram::peak_count` one
        // altitude down (both read 0 on empty).
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.peak_tier_count();
            let hand_rolled = map
                .tier_histogram()
                .iter()
                .map(|(_, c)| c)
                .max()
                .unwrap_or(0);
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ---- ProvenanceMap::recessive_tier — anti-modal-cell scalar peer
    //      of ProvenanceMap::tier_histogram on the tier altitude ----

    #[test]
    fn recessive_tier_matches_tier_histogram_recessive_cell_pointwise() {
        // The anti-modal-cell pin: `recessive_tier` routes through
        // `tier_histogram().recessive_cell()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Peer of
        // `dominant_tier_matches_tier_histogram_dominant_cell_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().recessive_cell();
            assert_eq!(map.recessive_tier(), via_histogram);
        }
    }

    #[test]
    fn recessive_tier_prog_fixture_is_bare() {
        // Prog attributes 4 leaves: a→Discovered, b→Default, c→Bare,
        // d→Default. Counts: Bare=1, Discovered=1, Default=2, Custom=0.
        // The argmin over the support {Bare, Discovered, Default} ties
        // at 1 between Bare and Discovered; declaration-order tiebreak
        // picks the earlier cell → `Some(Bare)`. Direct pin — the named
        // seam answers the operator's *"which tier is the runt of this
        // resolved fold?"* question at one call, no `min_by_key` walk
        // in the dashboard.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().recessive_tier(), Some(ConfigTierKind::Bare));
    }

    #[test]
    fn recessive_tier_nested_fixture_is_discovered() {
        // Nested attributes 3 leaves: win.w→Discovered, win.h→Default,
        // theme→Default. Counts: Bare=0, Discovered=1, Default=2,
        // Custom=0. The argmin over the support {Discovered, Default}
        // is uniquely Discovered at count 1 — no tie, no declaration-
        // order fallback needed.
        let r = Nested::resolve_progressive();
        assert_eq!(
            r.provenance().recessive_tier(),
            Some(ConfigTierKind::Discovered)
        );
    }

    #[test]
    fn recessive_tier_empty_map_is_none() {
        // An empty ProvenanceMap has no leaves and therefore no
        // anti-modal tier — the empty-map / empty-histogram boundary of
        // the recessive-cell projection. Peer to
        // `dominant_tier_empty_map_is_none` on the modal side.
        let empty = ProvenanceMap::default();
        assert_eq!(empty.recessive_tier(), None);
    }

    #[test]
    fn recessive_tier_is_some_iff_map_is_nonempty() {
        // Cross-surface pin: the presence-of-anti-modal-cell predicate
        // agrees with the non-emptiness of the underlying map.
        // Structural completeness of the `(is_empty, recessive_tier)`
        // boundary — a well-formed fold with ≥1 leaf always has an
        // anti-modal cell, and an empty fold never does. Peer of
        // `dominant_tier_is_some_iff_map_is_nonempty`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(map.recessive_tier().is_some(), !map.is_empty());
        }
    }

    #[test]
    fn recessive_tier_is_some_iff_dominant_tier_is_some() {
        // Cross-projection pin lifted from the trait-uniform
        // `recessive_cell().is_some() == dominant_cell().is_some()` law
        // on AxisHistogram: both projections operate over the same
        // nonzero support, so they agree on presence at every input.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(
                map.recessive_tier().is_some(),
                map.dominant_tier().is_some(),
            );
        }
    }

    #[test]
    fn recessive_tier_is_member_of_contributing_tiers() {
        // Structural pin: whenever `recessive_tier()` is `Some(t)`, `t`
        // must appear in `contributing_tiers()` (the anti-modal cell is
        // taken over the support, so it is by definition observed).
        // The support / anti-modal-cell partition on the tier altitude
        // reads consistently between the two named seams. Peer of
        // `dominant_tier_is_member_of_contributing_tiers`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let recessive = map
                .recessive_tier()
                .expect("non-empty map has recessive tier");
            assert!(
                map.contributing_tiers().contains(&recessive),
                "recessive tier {recessive:?} must appear in contributing_tiers",
            );
        }
    }

    #[test]
    fn recessive_tier_is_not_member_of_absent_tiers() {
        // Structural pin: whenever `recessive_tier()` is `Some(t)`, `t`
        // must NOT appear in `absent_tiers()` — the anti-modal cell lies
        // on the observed side of the observed / coverage-gap partition
        // by construction (argmin taken over the nonzero support).
        // Disjointness pin between the two named seams. Peer of
        // `dominant_tier_is_not_member_of_absent_tiers`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let recessive = map
                .recessive_tier()
                .expect("non-empty map has recessive tier");
            assert!(
                !map.absent_tiers().contains(&recessive),
                "recessive tier {recessive:?} must not appear in absent_tiers",
            );
        }
    }

    #[test]
    fn recessive_tier_count_equals_trough_count_on_nonempty_map() {
        // The (recessive_cell, trough_count) anti-modal-pair invariant
        // lifted to the tier altitude: the observation count of the
        // recessive tier equals the histogram's trough count over the
        // support. Peer of `dominant_tier_count_equals_peak_count_on_nonempty_map`
        // on the anti-modal side, and the trough-of-support analogue of
        // the (dominant_cell, peak_count) modal pair.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let hist = map.tier_histogram();
            let recessive = map
                .recessive_tier()
                .expect("non-empty map has recessive tier");
            assert_eq!(hist.count(recessive), hist.trough_count());
        }
    }

    #[test]
    fn recessive_tier_count_bounded_by_dominant_tier_count() {
        // Structural bound lifted from the trait-uniform
        // `count(recessive_cell) <= count(dominant_cell)` law on
        // AxisHistogram: the trough-of-support is bounded above by the
        // peak-of-support at every fixture. Cross-projection pin
        // between `recessive_tier` and `dominant_tier`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let hist = map.tier_histogram();
            let recessive = map
                .recessive_tier()
                .expect("non-empty map has recessive tier");
            let dominant = map
                .dominant_tier()
                .expect("non-empty map has dominant tier");
            assert!(
                hist.count(recessive) <= hist.count(dominant),
                "count(recessive={recessive:?})={r} must be <= count(dominant={dominant:?})={d}",
                r = hist.count(recessive),
                d = hist.count(dominant),
            );
        }
    }

    #[test]
    fn recessive_tier_ties_broken_by_declaration_order() {
        // Structural tie-breaking pin: on a uniform per-tier fold
        // (each of the four `ConfigTierKind` cells contributing exactly
        // one leaf), `recessive_tier` reports
        // `Some(ConfigTierKind::Bare)` — the first cell in
        // `ConfigTierKind::ALL` declaration order (the singleton-modality
        // degenerate where the modal and anti-modal cells coincide).
        // Constructed by overlaying a Custom operator layer on Prog
        // (which spans Bare→Discovered→Default with 4 leaves distributed
        // 1/1/2) that steals the second Default-tier leaf (b) into
        // Custom, yielding a 1-leaf-per-tier full-cover fold. Any
        // future switch to a nondeterministic `min_by_key` walk over
        // the full axis (which would silently pick a zero-count cell
        // over the closed axis) would flip this pin — the seam names
        // the tiebreak once.
        let mut d = Dict::new();
        d.insert("b".to_owned(), Value::from(99_u32));
        let r = Prog::resolve_progressive_with(&[ProgressiveLayer::file("/etc/prog.yaml", d)]);
        // Sanity: this construction produces the intended tier-count
        // distribution (each tier owns exactly one leaf).
        let hist = r.provenance().tier_histogram();
        assert_eq!(hist.count(ConfigTierKind::Bare), 1);
        assert_eq!(hist.count(ConfigTierKind::Discovered), 1);
        assert_eq!(hist.count(ConfigTierKind::Default), 1);
        assert_eq!(hist.count(ConfigTierKind::Custom), 1);
        assert!(hist.is_full_cover());
        // Tiebreak lands on the first cell in declaration order —
        // pointwise identical to `dominant_tier` on the same uniform
        // input (the singleton-modality degenerate).
        assert_eq!(r.provenance().recessive_tier(), Some(ConfigTierKind::Bare));
        assert_eq!(
            r.provenance().recessive_tier(),
            r.provenance().dominant_tier()
        );
    }

    #[test]
    fn recessive_tier_singleton_support_agrees_with_dominant_tier() {
        // Singleton-support degenerate lifted from the trait-uniform
        // `distinct_cells() == 1 → dominant_cell() == recessive_cell()`
        // law on AxisHistogram: when only one tier contributes, that
        // tier is both the modal and the anti-modal cell. Direct
        // construction: three leaves, all on `Default`.
        let m: ProvenanceMap = ["a", "b", "c"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Default),
                )
            })
            .collect();
        assert_eq!(m.contributing_tiers().len(), 1);
        assert_eq!(m.recessive_tier(), m.dominant_tier());
        assert_eq!(m.recessive_tier(), Some(ConfigTierKind::Default));
    }

    #[test]
    fn recessive_tier_agrees_with_open_coded_argmin_walk() {
        // Parity against the exact `hist.iter().filter(|&(_, c)| c > 0)
        // .min_by(count-then-declaration-order)` walk this lift replaces
        // — both the named seam and the hand-rolled argmin must
        // pointwise agree over every fixture in the module. The
        // hand-rolled form spells the declaration-order tiebreak
        // explicitly (fold-forward with strict `<` inequality — the
        // first tied cell wins, mirroring `AxisHistogram::recessive_cell`
        // — rather than `min_by_key`'s FIRST-tied-cell semantics which
        // agrees by coincidence but drifts under any reversed
        // comparison).
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.recessive_tier();
            let hist = map.tier_histogram();
            let mut iter = hist.iter().filter(|&(_, c)| c > 0);
            let hand_rolled = iter.next().map(|first| {
                iter.fold(
                    first,
                    |best, current| {
                        if current.1 < best.1 { current } else { best }
                    },
                )
                .0
            });
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ---- ProvenanceMap::trough_tier_count — anti-modal-cell scalar-count
    //      peer of ProvenanceMap::tier_histogram on the tier altitude,
    //      fusing with recessive_tier into the (cell, count) anti-modal
    //      pair and closing the (dominant, recessive) × (cell, count) 2×2
    //      scalar grid on the tier altitude ----

    #[test]
    fn trough_tier_count_matches_tier_histogram_trough_count_pointwise() {
        // The scalar-count pin: `trough_tier_count` routes through
        // `tier_histogram().trough_count()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through the
        // shared cube-native primitive. Peer of
        // `recessive_tier_matches_tier_histogram_recessive_cell_pointwise`
        // on the count side, and of
        // `peak_tier_count_matches_tier_histogram_peak_count_pointwise` on
        // the anti-modal side.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().trough_count();
            assert_eq!(map.trough_tier_count(), via_histogram);
        }
    }

    #[test]
    fn trough_tier_count_prog_fixture_is_one() {
        // Prog attributes 4 leaves: a→Discovered, b→Default, c→Bare,
        // d→Default. Counts: Bare=1, Discovered=1, Default=2, Custom=0.
        // The trough over the support {Bare, Discovered, Default} lands
        // at count 1 (tied between Bare and Discovered — the tie-break
        // picks the *cell*, but the scalar count is `1` either way).
        // Direct pin — the named seam answers the operator's *"how many
        // leaves did the runt tier collect?"* at one call, no
        // `trough_count` re-derivation in the dashboard.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().trough_tier_count(), 1);
    }

    #[test]
    fn trough_tier_count_nested_fixture_is_one() {
        // Nested attributes 3 leaves: win.w→Discovered, win.h→Default,
        // theme→Default. Counts: Bare=0, Discovered=1, Default=2,
        // Custom=0. The trough over the support {Discovered, Default} is
        // uniquely Discovered at count 1 — the scalar reads through the
        // seam whether the fixture is flat or nested.
        let r = Nested::resolve_progressive();
        assert_eq!(r.provenance().trough_tier_count(), 1);
    }

    #[test]
    fn trough_tier_count_empty_map_is_zero() {
        // An empty ProvenanceMap has no leaves and therefore no trough
        // — the empty-map / empty-histogram boundary of the scalar-count
        // projection reads `0` (matching the [`AxisHistogram::trough_count`]
        // empty convention one altitude down, and the `Self::len` empty
        // convention on the same altitude). Peer to
        // `recessive_tier_empty_map_is_none` on the cell side and
        // `peak_tier_count_empty_map_is_zero` on the modal side — the
        // fused quad `(dominant_tier, peak_tier_count, recessive_tier,
        // trough_tier_count)` reads `(None, 0, None, 0)` uniformly on the
        // empty map.
        let empty = ProvenanceMap::default();
        assert_eq!(empty.trough_tier_count(), 0);
    }

    #[test]
    fn trough_tier_count_is_zero_iff_map_is_empty() {
        // Cross-surface pin: the zero-trough predicate agrees with the
        // emptiness of the underlying map. Structural completeness of
        // the `(is_empty, trough_tier_count == 0)` boundary — a
        // well-formed fold with ≥1 leaf always has a positive trough (the
        // argmin is taken over the *support*), and an empty fold always
        // has zero trough. The count-side dual of
        // `recessive_tier_is_some_iff_map_is_nonempty` and the anti-modal
        // dual of `peak_tier_count_is_zero_iff_map_is_empty`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert_eq!(map.trough_tier_count() == 0, map.is_empty());
        }
    }

    #[test]
    fn trough_tier_count_equals_count_at_recessive_tier_on_nonempty_map() {
        // The (recessive_cell, trough_count) anti-modal-pair invariant
        // lifted to the tier altitude on the ProvenanceMap surface: the
        // scalar-count reads pointwise identical to
        // `count(recessive_tier)`. Peer of
        // `recessive_tier_count_equals_trough_count_on_nonempty_map` —
        // that test pins the histogram-side identity
        // `hist.count(recessive_tier) == hist.trough_count()`; this test
        // pins the ProvenanceMap-side identity `count(recessive_tier) ==
        // trough_tier_count()` at the fused-pair seam.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let hist = map.tier_histogram();
            let recessive = map
                .recessive_tier()
                .expect("non-empty map has recessive tier");
            assert_eq!(hist.count(recessive), map.trough_tier_count());
        }
    }

    #[test]
    fn trough_tier_count_equals_recessive_tier_map_or_count() {
        // The fused-pair identity `trough_tier_count() ==
        // recessive_tier().map_or(0, |t| tier_histogram().count(t))` on
        // every input — the count projection of the (recessive_tier,
        // trough_tier_count) anti-modal pair reads through the seam
        // uniformly across the empty-map / non-empty-map partition.
        // Includes the empty map (`None.map_or(0, …) == 0 ==
        // trough_tier_count`) — this is the pin that the fused-pair
        // identity is boundary-complete. Peer of
        // `peak_tier_count_equals_dominant_tier_map_or_count` on the
        // anti-modal side.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let hist = map.tier_histogram();
            let via_fused_pair = map.recessive_tier().map_or(0, |t| hist.count(t));
            assert_eq!(map.trough_tier_count(), via_fused_pair);
        }
    }

    #[test]
    fn trough_tier_count_is_bounded_by_peak_tier_count() {
        // Structural bound `trough_tier_count() <= peak_tier_count()` on
        // every input — the trough is bounded above by the peak. Lifted
        // from the trait-uniform `trough_count() <= peak_count()` law on
        // AxisHistogram. The empty-map case reads `0 <= 0`; the
        // non-empty case reads the trough-of-support bounded above by the
        // peak-of-support. Closes the `(trough, peak)` scalar lattice on
        // the tier altitude — both projections read through the same
        // seam pair.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert!(
                map.trough_tier_count() <= map.peak_tier_count(),
                "trough_tier_count()={t} must be <= peak_tier_count()={p}",
                t = map.trough_tier_count(),
                p = map.peak_tier_count(),
            );
        }
    }

    #[test]
    fn trough_tier_count_equals_peak_tier_count_iff_at_most_one_contributing_tier() {
        // Structural bound `trough_tier_count() == peak_tier_count()` iff
        // `contributing_tiers().len() <= 1` — the trough equals the peak
        // exactly when zero or one tier is observed. Zero: empty map,
        // both zero. One: singleton-support fold, both equal `len()`.
        // Two or more with distinct counts: trough strictly below peak.
        // The uniform-cover multi-tier case (two or more tiers, all with
        // the same count) is not exercised by the two fixtures here
        // (both Prog and Nested carry distinct counts across their
        // observed tiers), but the pin is structurally sound: whenever
        // support > 1 with distinct counts, trough < peak. Peer of
        // `peak_tier_count_equals_len_iff_at_most_one_contributing_tier`
        // on the trough-side identity.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let equal_when_at_most_one = map.trough_tier_count() == map.peak_tier_count();
            let at_most_one_contributing = map.contributing_tiers().len() <= 1;
            // Weakest direction (holds on every fixture used here):
            // support <= 1 → trough == peak.
            if at_most_one_contributing {
                assert!(
                    equal_when_at_most_one,
                    "at_most_one_contributing → trough == peak (trough={t}, peak={p})",
                    t = map.trough_tier_count(),
                    p = map.peak_tier_count(),
                );
            }
        }
    }

    #[test]
    fn trough_tier_count_is_at_least_one_on_nonempty_map() {
        // Structural pin: whenever `!is_empty()`, `trough_tier_count() >=
        // 1` — the argmin is taken over the histogram's *support*
        // (nonzero cells), so a non-empty map always has at least one
        // leaf on the recessive tier. Combined with the `<=
        // peak_tier_count()` bound above, this pins `1 <=
        // trough_tier_count() <= peak_tier_count() <= len()` on every
        // non-empty map — the complete inequality chain on the tier
        // altitude scalar-count surface. Peer of
        // `peak_tier_count_is_at_least_one_on_nonempty_map`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            assert!(
                map.trough_tier_count() >= 1,
                "non-empty map must have trough_tier_count >= 1 (trough={t})",
                t = map.trough_tier_count(),
            );
        }
    }

    #[test]
    fn trough_tier_count_uniform_cover_is_one() {
        // Trait-uniform invariant lifted to the ProvenanceMap surface:
        // on a full-cover fold where every tier observes the same
        // nonzero count of one, the trough count is `1` (and equals the
        // peak — the singleton-modality count-side degenerate). Direct
        // construction: one leaf per tier, full-cover with uniform count
        // 1. Peer of `peak_tier_count_uniform_cover_is_one` — together
        // the pair `(peak_tier_count, trough_tier_count)` reads `(1, 1)`
        // on the uniform-cover fold, and the quad `(dominant_tier,
        // peak_tier_count, recessive_tier, trough_tier_count)` reads
        // `(Some(Bare), 1, Some(Bare), 1)` — the tie-break picks the
        // first-declared cell on both projections.
        let m: ProvenanceMap = ConfigTierKind::ALL
            .iter()
            .copied()
            .map(|t| (vec![t.as_str().to_owned()], Provenance::computed(t)))
            .collect();
        assert!(m.tier_histogram().is_full_cover());
        assert_eq!(m.trough_tier_count(), 1);
        assert_eq!(m.trough_tier_count(), m.peak_tier_count());
    }

    #[test]
    fn trough_tier_count_singleton_support_equals_len() {
        // Singleton-support degenerate: when only one tier contributes,
        // every leaf lands on that tier, so the trough equals the total
        // (and equals the peak — the singleton-support count-side
        // degenerate). Direct construction: three leaves, all on
        // `Default`. The scalar peer of the singleton-support cell
        // degenerate `dominant_tier() == recessive_tier()` in
        // `recessive_tier_singleton_support_agrees_with_dominant_tier`
        // — that test pins the *cell*; this test pins the *count*
        // through the `trough_tier_count() == len()` equality on the
        // singleton-support boundary. Peer of
        // `peak_tier_count_singleton_support_equals_len`.
        let m: ProvenanceMap = ["a", "b", "c"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Default),
                )
            })
            .collect();
        assert_eq!(m.contributing_tiers().len(), 1);
        assert_eq!(m.trough_tier_count(), m.len());
        assert_eq!(m.trough_tier_count(), 3);
        assert_eq!(m.trough_tier_count(), m.peak_tier_count());
    }

    #[test]
    fn trough_tier_count_agrees_with_open_coded_min_over_support_walk() {
        // Parity against the exact `hist.iter().filter(|&(_, c)| c > 0)
        // .map(|(_, c)| c).min().unwrap_or(0)` walk this lift replaces
        // — both the named seam and the hand-rolled min over the support
        // must pointwise agree over every fixture in the module. The
        // `.filter(c > 0)` step is essential: without it the argmin
        // would silently pick a zero-count cell (any tier the fold did
        // not credit), shadowing the *rarest observed* count with a
        // "trivial minimum" over the full axis. The `.min().unwrap_or(0)`
        // idiom mirrors the empty-histogram convention on
        // `AxisHistogram::trough_count` one altitude down (both read 0
        // on empty). Peer of
        // `peak_tier_count_agrees_with_open_coded_max_over_axis_walk` on
        // the anti-modal side (that walk does NOT filter, since
        // `AxisHistogram::peak_count` operates over the full axis — the
        // trough side does, since a zero-count cell would otherwise
        // dominate the min).
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.trough_tier_count();
            let hand_rolled = map
                .tier_histogram()
                .iter()
                .filter(|&(_, c)| c > 0)
                .map(|(_, c)| c)
                .min()
                .unwrap_or(0);
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── ProvenanceMap::tier_spread — scalar-dispersion peer on the tier
    //    altitude, fusing peak_tier_count and trough_tier_count into one
    //    dispersion scalar and climbing the "spread across altitudes"
    //    projection from the diff altitude to the tier altitude ──

    #[test]
    fn tier_spread_matches_tier_histogram_spread_pointwise() {
        // The scalar-dispersion pin: `tier_spread` routes through
        // `tier_histogram().spread()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through
        // the shared cube-native primitive. Tier-altitude peer of
        // `kind_spread_matches_kind_histogram_spread_pointwise` on the
        // diff altitude in the "spread across altitudes" projection.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().spread();
            assert_eq!(map.tier_spread(), via_histogram);
        }
    }

    #[test]
    fn tier_spread_equals_peak_minus_trough_pointwise() {
        // The fused-pair pin: `tier_spread == peak_tier_count -
        // trough_tier_count` on every fixture. The subtraction is
        // underflow-safe because `peak_tier_count >= trough_tier_count`
        // holds structurally on every map (lifted from the trait-
        // uniform `peak_count >= trough_count` law on AxisHistogram).
        // Closes the identity of the scalar-dispersion peer against
        // the two count seams it fuses. Tier-altitude peer of
        // `kind_spread_equals_peak_minus_trough_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let peak = map.peak_tier_count();
            let trough = map.trough_tier_count();
            assert!(
                peak >= trough,
                "peak_tier_count ({peak}) must be >= trough_tier_count ({trough}) \
                 for tier_spread to be underflow-safe",
            );
            assert_eq!(map.tier_spread(), peak - trough);
        }
    }

    #[test]
    fn tier_spread_prog_fixture_is_one() {
        // Prog attributes 4 leaves: a→Discovered, b→Default, c→Bare,
        // d→Default. Counts: Bare=1, Discovered=1, Default=2, Custom=0.
        // Peak lands on Default at 2; trough over support {Bare,
        // Discovered, Default} lands at 1. Spread = 2 - 1 = 1. Direct
        // pin — the paired `(peak_tier_count, trough_tier_count,
        // tier_spread)` dispersion triple reads `(2, 1, 1)`. Peer of
        // `peak_tier_count_prog_fixture_is_two` and
        // `trough_tier_count_prog_fixture_is_one` on the same fixture.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().peak_tier_count(), 2);
        assert_eq!(r.provenance().trough_tier_count(), 1);
        assert_eq!(r.provenance().tier_spread(), 1);
    }

    #[test]
    fn tier_spread_nested_fixture_is_one() {
        // Nested attributes 3 leaves: win.w→Discovered, win.h→Default,
        // theme→Default. Counts: Bare=0, Discovered=1, Default=2,
        // Custom=0. Peak lands on Default at 2; trough over support
        // {Discovered, Default} lands at 1. Spread = 2 - 1 = 1. Direct
        // pin — the scalar reads through the seam whether the fixture
        // is flat or nested.
        let r = Nested::resolve_progressive();
        assert_eq!(r.provenance().peak_tier_count(), 2);
        assert_eq!(r.provenance().trough_tier_count(), 1);
        assert_eq!(r.provenance().tier_spread(), 1);
    }

    #[test]
    fn tier_spread_empty_map_is_zero() {
        // An empty ProvenanceMap has no leaves and therefore zero spread
        // — reads `0` per the AxisHistogram::spread empty convention one
        // altitude down; the `(peak_tier_count, trough_tier_count,
        // tier_spread)` triple reads `(0, 0, 0)` uniformly on the empty
        // map. Peer of `peak_tier_count_empty_map_is_zero` and
        // `trough_tier_count_empty_map_is_zero`.
        let empty = ProvenanceMap::default();
        assert_eq!(empty.peak_tier_count(), 0);
        assert_eq!(empty.trough_tier_count(), 0);
        assert_eq!(empty.tier_spread(), 0);
        assert!(empty.is_empty());
    }

    #[test]
    fn tier_spread_singleton_support_is_zero() {
        // Singleton-support pin: every leaf lands on the same tier, so
        // the dominant tier is both peak and trough of the support, and
        // the spread is zero — the balanced-tier-counts boundary on the
        // singleton-support side. Tier-altitude peer of the trait-
        // uniform `spread() == 0 on singleton support` law on
        // AxisHistogram, and diff-altitude peer of
        // `kind_spread_singleton_support_is_zero`.
        let m: ProvenanceMap = ["a", "b", "c"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Default),
                )
            })
            .collect();
        assert_eq!(m.contributing_tiers().len(), 1);
        assert_eq!(m.tier_spread(), 0);
    }

    #[test]
    fn tier_spread_uniform_cover_is_zero() {
        // Uniform-cover pin: every observed tier contributes the same
        // nonzero count (one leaf each here), so peak == trough == 1
        // and the spread is zero — the balanced-tier-counts boundary
        // on the uniform-cover side. Peer of
        // `peak_tier_count_uniform_cover_is_one` and
        // `trough_tier_count_uniform_cover_is_one` on the count sides,
        // and diff-altitude peer of `kind_spread_uniform_cover_is_zero`.
        let m: ProvenanceMap = ConfigTierKind::ALL
            .iter()
            .copied()
            .map(|t| (vec![t.as_str().to_owned()], Provenance::computed(t)))
            .collect();
        assert!(m.tier_histogram().is_full_cover());
        assert_eq!(m.peak_tier_count(), 1);
        assert_eq!(m.trough_tier_count(), 1);
        assert_eq!(m.tier_spread(), 0);
    }

    #[test]
    fn tier_spread_is_zero_iff_peak_equals_trough() {
        // Structural-skew boundary: `tier_spread() == 0` iff every
        // observed tier carries the same count — the balanced-tier-
        // counts shape. On every fixture, the predicate agrees with
        // the scalar-pair form `peak_tier_count == trough_tier_count`
        // pointwise. The empty map, the singleton-support fold, and
        // every uniform-cover fold all read `true`; every skewed fold
        // reads `false`. Peer of
        // `kind_spread_is_zero_iff_at_most_one_present_kind_or_uniform_cover`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let spread_zero = map.tier_spread() == 0;
            let counts_equal = map.peak_tier_count() == map.trough_tier_count();
            assert_eq!(
                spread_zero,
                counts_equal,
                "tier_spread == 0 must agree with peak_tier_count == trough_tier_count \
                 for map with peak={p}, trough={t}, spread={s}",
                p = map.peak_tier_count(),
                t = map.trough_tier_count(),
                s = map.tier_spread(),
            );
        }
    }

    #[test]
    fn tier_spread_agrees_with_modal_pair_equality_on_nonempty_map() {
        // Cross-surface pin: on every non-empty map, `tier_spread() ==
        // 0` agrees with `dominant_tier() == recessive_tier()` — the
        // modal-pair equality form of the balanced-tier-counts
        // predicate. Lifted from the trait-uniform
        // `spread() == 0 <=> dominant_cell() == recessive_cell()` law
        // on AxisHistogram (non-empty case). The empty-map case is
        // separately pinned on both surfaces. Tier-altitude peer of
        // `kind_spread_agrees_with_modal_pair_equality_on_nonempty_diff`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
        ] {
            let spread_zero = map.tier_spread() == 0;
            let modal_pair_equal = map.dominant_tier() == map.recessive_tier();
            assert_eq!(
                spread_zero, modal_pair_equal,
                "tier_spread == 0 must agree with dominant_tier == recessive_tier \
                 on non-empty map",
            );
        }
    }

    #[test]
    fn tier_spread_bounded_above_by_peak_tier_count() {
        // Structural bound: `tier_spread() <= peak_tier_count()` on
        // every fixture — the trough is non-negative, so the
        // subtraction is bounded above by the minuend. Lifted from the
        // trait-uniform `spread() <= peak_count()` law on
        // AxisHistogram. Equality holds exactly when the trough is
        // zero — i.e. on the empty map (both sides read 0). Peer of
        // `kind_spread_bounded_above_by_peak_kind_count`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert!(
                map.tier_spread() <= map.peak_tier_count(),
                "tier_spread ({s}) must not exceed peak_tier_count ({p})",
                s = map.tier_spread(),
                p = map.peak_tier_count(),
            );
        }
    }

    #[test]
    fn tier_spread_equals_peak_iff_map_is_empty() {
        // Equality-case pin of the `tier_spread <= peak_tier_count`
        // bound: equality holds iff the trough is zero, which by
        // `trough_tier_count == 0 <=> is_empty()` holds iff the map is
        // empty. The two projections agree on the (0, 0) empty corner
        // and disagree strictly on every non-empty map (where the
        // trough is >= 1, so `spread < peak`). Peer of
        // `kind_spread_equals_peak_iff_diff_is_empty`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let equality = map.tier_spread() == map.peak_tier_count();
            let is_empty = map.is_empty();
            assert_eq!(
                equality,
                is_empty,
                "tier_spread == peak_tier_count must agree with is_empty() \
                 for map with peak={p}, trough={t}, spread={s}",
                p = map.peak_tier_count(),
                t = map.trough_tier_count(),
                s = map.tier_spread(),
            );
        }
    }

    #[test]
    fn tier_spread_bounded_above_by_len() {
        // Composition bound: `tier_spread() <= self.len()` on every
        // fixture — chaining `tier_spread <= peak_tier_count` (previous
        // pin) with `peak_tier_count <= len()` (documented on
        // `peak_tier_count_is_bounded_by_len`). The scalar dispersion
        // of a resolved fold is bounded above by the total leaf count.
        // Peer of `kind_spread_bounded_above_by_lines_len`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            assert!(
                map.tier_spread() <= map.len(),
                "tier_spread ({s}) must not exceed len ({n})",
                s = map.tier_spread(),
                n = map.len(),
            );
        }
    }

    #[test]
    fn tier_spread_singleton_support_multi_leaf_is_zero() {
        // Direct pin at a singleton-support fold with three leaves all
        // on `Default`. Peak == trough == 3 == len; spread == 0. The
        // dispersion scalar reads zero on every singleton-support fold
        // regardless of the leaf count — the "one tier owns everything"
        // shape is trivially balanced by construction. Peer of
        // `peak_tier_count_singleton_support_equals_len` and
        // `trough_tier_count_singleton_support_equals_len`.
        let m: ProvenanceMap = ["a", "b", "c"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Default),
                )
            })
            .collect();
        assert_eq!(m.peak_tier_count(), 3);
        assert_eq!(m.trough_tier_count(), 3);
        assert_eq!(m.tier_spread(), 0);
    }

    #[test]
    fn tier_spread_agrees_with_open_coded_max_minus_min_walk() {
        // Parity against the exact `hist.iter().map(|(_, c)| c).max()
        // .unwrap_or(0) - hist.iter().filter(|&(_, c)| c > 0)
        // .map(|(_, c)| c).min().unwrap_or(0)` walk this lift replaces
        // — both the named seam and the hand-rolled dispersion must
        // pointwise agree over every fixture. The `.filter(c > 0)` on
        // the min side is essential (mirroring `trough_count`'s support
        // discipline); the `.max()` on the peak side operates over the
        // full axis (mirroring `peak_count`). The subtraction is
        // underflow-safe on the histogram because `peak >= trough`
        // holds structurally. Peer of
        // `kind_spread_agrees_with_open_coded_max_minus_min_walk`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.tier_spread();
            let hist = map.tier_histogram();
            let peak = hist.iter().map(|(_, c)| c).max().unwrap_or(0);
            let trough = hist
                .iter()
                .filter(|&(_, c)| c > 0)
                .map(|(_, c)| c)
                .min()
                .unwrap_or(0);
            assert_eq!(via_seam, peak - trough);
        }
    }

    // ── ProvenanceMap::tiers_balanced — balanced-tier-counts boolean
    //    predicate on the tier altitude, lifting is_uniform_count from the
    //    histogram surface and climbing the "balanced across altitudes"
    //    projection from the diff altitude ──

    #[test]
    fn tiers_balanced_matches_tier_histogram_is_uniform_count_pointwise() {
        // The routing pin: `tiers_balanced` routes through
        // `tier_histogram().is_uniform_count()`, so the two seams must
        // stay pointwise equivalent under every fixture. Catches any
        // future drift where either implementation stops projecting
        // through the shared cube-native primitive. Tier-altitude peer of
        // `kinds_balanced_matches_kind_histogram_is_uniform_count_pointwise`
        // on the diff altitude in the "balanced across altitudes"
        // projection.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().is_uniform_count();
            assert_eq!(map.tiers_balanced(), via_histogram);
        }
    }

    #[test]
    fn tiers_balanced_agrees_with_tier_spread_zero_pointwise() {
        // The defining equivalence on the scalar-spread surface at the
        // tier altitude: `tiers_balanced() == (tier_spread() == 0)` on
        // every fixture. The balanced-boundary of the fused
        // `(peak_tier_count, trough_tier_count, tier_spread)` dispersion
        // triple as a named boolean predicate. Lifted from the trait-
        // uniform `is_uniform_count() == (spread() == 0)` law on
        // AxisHistogram. Peer of
        // `kinds_balanced_agrees_with_kind_spread_zero_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let balanced = map.tiers_balanced();
            let spread_zero = map.tier_spread() == 0;
            assert_eq!(
                balanced,
                spread_zero,
                "tiers_balanced ({balanced}) must agree with tier_spread == 0 \
                 (spread={s}) for map",
                s = map.tier_spread(),
            );
        }
    }

    #[test]
    fn tiers_balanced_agrees_with_peak_equals_trough_pointwise() {
        // The structural form on the underlying scalar pair:
        // `tiers_balanced() == (peak_tier_count() == trough_tier_count())`
        // on every fixture. Pins the balanced-tier-counts predicate
        // against the direct scalar-pair equality form. Peer of
        // `kinds_balanced_agrees_with_peak_equals_trough_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let balanced = map.tiers_balanced();
            let peak = map.peak_tier_count();
            let trough = map.trough_tier_count();
            assert_eq!(
                balanced,
                peak == trough,
                "tiers_balanced ({balanced}) must agree with peak_tier_count == \
                 trough_tier_count ({peak} == {trough}) for map",
            );
        }
    }

    #[test]
    fn tiers_balanced_agrees_with_modal_pair_equality_pointwise() {
        // The modal-pair form: `tiers_balanced() == (dominant_tier() ==
        // recessive_tier())` on every fixture — including the empty map
        // where both branches reduce to `None == None`, every singleton-
        // support fold where both reduce to `Some(t) == Some(t)`, every
        // uniform per-tier fold where both reduce to `Some(first) ==
        // Some(first)` (after declaration-order tie-break on both sides),
        // and every skewed fold where both read `false`. Lifted from the
        // trait-uniform `is_uniform_count() == (dominant_cell() ==
        // recessive_cell())` law on AxisHistogram. Peer of
        // `kinds_balanced_agrees_with_modal_pair_equality_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let balanced = map.tiers_balanced();
            let modal_pair_equal = map.dominant_tier() == map.recessive_tier();
            assert_eq!(
                balanced, modal_pair_equal,
                "tiers_balanced ({balanced}) must agree with \
                 dominant_tier == recessive_tier for map",
            );
        }
    }

    #[test]
    fn tiers_balanced_empty_map_is_true() {
        // Vacuous-uniformity boundary: the empty map has no observed
        // cells, so the universal "every observed cell carries the same
        // count" reads `true` over the empty support — matching
        // AxisHistogram::is_uniform_count's empty convention one altitude
        // down and `tier_spread == 0` on the empty case. Peer of
        // `kinds_balanced_empty_diff_is_true` and
        // `tier_spread_empty_map_is_zero`.
        let empty = ProvenanceMap::default();
        assert!(empty.is_empty());
        assert!(empty.tiers_balanced());
        assert_eq!(empty.tier_spread(), 0);
    }

    #[test]
    fn tiers_balanced_singleton_support_is_true() {
        // Singleton-support pin: every leaf lands on the same tier, so
        // the one observed tier's count is both peak and trough of the
        // support — trivially balanced. Peer of
        // `kinds_balanced_singleton_support_is_true` and
        // `tier_spread_singleton_support_is_zero`.
        let m: ProvenanceMap = ["a", "b", "c", "d"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Default),
                )
            })
            .collect();
        assert_eq!(m.contributing_tiers().len(), 1);
        assert!(m.tiers_balanced());
    }

    #[test]
    fn tiers_balanced_uniform_cover_is_true() {
        // Uniform-cover pin: every observed tier contributes the same
        // nonzero count (one leaf each across all four ConfigTierKind
        // cells), so peak == trough == 1 and the balanced-tier-counts
        // predicate reads `true`. Peer of
        // `kinds_balanced_uniform_cover_is_true` and
        // `tier_spread_uniform_cover_is_zero`.
        let m: ProvenanceMap = ConfigTierKind::ALL
            .iter()
            .copied()
            .map(|t| (vec![t.as_str().to_owned()], Provenance::computed(t)))
            .collect();
        assert!(m.tier_histogram().is_full_cover());
        assert!(m.tiers_balanced());
    }

    #[test]
    fn tiers_balanced_prog_fixture_is_false() {
        // Direct pin: the Prog fold attributes 4 leaves as
        // {Bare:1, Discovered:1, Default:2, Custom:0}. Peak == 2 lands on
        // Default; trough over support == 1 on {Bare, Discovered}. Spread
        // == 1, so `tiers_balanced` reads `false`. Peer of
        // `kinds_balanced_context_dominated_fixture_is_false` on the boolean
        // side. Direct scalar-shape pin against the concrete Prog fixture.
        let r = Prog::resolve_progressive();
        assert_eq!(r.provenance().tier_spread(), 1);
        assert!(!r.provenance().tiers_balanced());
    }

    #[test]
    fn tiers_balanced_nested_fixture_is_false() {
        // Direct pin: the Nested fold attributes 3 leaves as
        // {Bare:0, Discovered:1, Default:2, Custom:0}. Peak == 2 lands on
        // Default; trough over support == 1 on {Discovered}. Spread == 1,
        // so `tiers_balanced` reads `false`. Peer of
        // `kinds_balanced_added_dominated_fixture_is_false` on the boolean
        // side. The predicate reads through the seam whether the fixture
        // is flat or nested.
        let r = Nested::resolve_progressive();
        assert_eq!(r.provenance().tier_spread(), 1);
        assert!(!r.provenance().tiers_balanced());
    }

    #[test]
    fn tiers_balanced_singleton_support_multi_leaf_is_true() {
        // Singleton-support multi-leaf pin: 5 leaves all on Custom, one
        // observed tier at count 5 — peak == trough == 5, balanced reads
        // `true`. Distinct peak from the 4-leaf singleton fixture above so
        // any misread that reintroduces a `tier_spread == 0` inline idiom
        // silently underflows on a fixture at a different peak. Peer of
        // `kinds_balanced_singleton_multi_line_is_true`.
        let m: ProvenanceMap = ["a", "b", "c", "d", "e"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Custom),
                )
            })
            .collect();
        assert_eq!(m.peak_tier_count(), 5);
        assert_eq!(m.trough_tier_count(), 5);
        assert!(m.tiers_balanced());
    }

    #[test]
    fn tiers_balanced_implies_at_most_one_contributing_tier_or_uniform_cover() {
        // Structural characterization: on every fixture, `tiers_balanced`
        // holds when the map has support size 0 or 1, or every observed
        // tier carries the same nonzero count. The contrapositive reads:
        // `!tiers_balanced() ⇒ contributing_tiers().len() >= 2` with at
        // least two distinct counts. Direct witness of the trait-uniform
        // `distinct_cells() <= 1 ⇒ is_uniform_count()` law on
        // AxisHistogram, lifted to the tier altitude. Peer of
        // `kinds_balanced_implies_at_most_one_present_kind_or_uniform_cover`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            if map.contributing_tiers().len() <= 1 {
                assert!(
                    map.tiers_balanced(),
                    "map with contributing_tiers.len() = {} must be tiers_balanced",
                    map.contributing_tiers().len(),
                );
            }
        }
    }

    #[test]
    fn tiers_balanced_false_implies_map_is_nonempty() {
        // Contrapositive of the vacuous-uniformity implication:
        // `!tiers_balanced() ⇒ !self.is_empty()`. A skewed fold has at
        // least two distinct positive counts, so the map is non-empty.
        // Directly witnessed on the fixture set. Peer of
        // `kinds_balanced_false_implies_diff_is_nonempty`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            if !map.tiers_balanced() {
                assert!(
                    !map.is_empty(),
                    "non-balanced map must be non-empty (len={})",
                    map.len(),
                );
            }
        }
    }

    #[test]
    fn tiers_balanced_false_implies_at_least_two_contributing_tiers() {
        // Contrapositive of the singleton-support implication:
        // `!tiers_balanced() ⇒ contributing_tiers().len() >= 2`. A skewed
        // fold observes at least two distinct tiers with differing counts.
        // Lifted from the trait-uniform `!is_uniform_count() ⇒
        // distinct_cells() >= 2` law on AxisHistogram. Peer of
        // `kinds_balanced_false_implies_at_least_two_present_kinds`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            if !map.tiers_balanced() {
                assert!(
                    map.contributing_tiers().len() >= 2,
                    "non-balanced map must observe >= 2 contributing tiers (was {})",
                    map.contributing_tiers().len(),
                );
            }
        }
    }

    #[test]
    fn tiers_balanced_skewed_three_cell_fixture_is_false() {
        // Direct pin: a strictly-ordered three-cell fold with
        // Discovered=1, Default=2, Custom=3 — peak 3, trough 1, spread 2
        // — reads `false`. Every count distinct, no tie-breaking on
        // either side of the modal-count pair. Peer of
        // `kinds_balanced_skewed_three_cell_fixture_is_false`.
        let m: ProvenanceMap = [
            ("d", ConfigTierKind::Discovered),
            ("e1", ConfigTierKind::Default),
            ("e2", ConfigTierKind::Default),
            ("c1", ConfigTierKind::Custom),
            ("c2", ConfigTierKind::Custom),
            ("c3", ConfigTierKind::Custom),
        ]
        .into_iter()
        .map(|(k, t)| (vec![k.to_owned()], Provenance::computed(t)))
        .collect();
        assert_eq!(m.peak_tier_count(), 3);
        assert_eq!(m.trough_tier_count(), 1);
        assert!(!m.tiers_balanced());
    }

    #[test]
    fn tiers_balanced_agrees_with_open_coded_uniform_walk() {
        // Parity against the exact hand-rolled uniform-count walk this
        // lift replaces: pull the nonzero counts and check they all
        // agree. Empty support reads `true` vacuously. Mirrors the parity
        // pin `kinds_balanced_agrees_with_open_coded_uniform_walk` on the
        // diff altitude.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.tiers_balanced();
            let hist = map.tier_histogram();
            let mut nonzero = hist.iter().map(|(_, c)| c).filter(|&c| c > 0);
            let hand_rolled = match nonzero.next() {
                None => true,
                Some(first) => nonzero.all(|c| c == first),
            };
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── ProvenanceMap::tiers_full_cover — full-cover-tier-counts boolean
    //    predicate on the tier altitude, lifting is_full_cover from the
    //    histogram surface and climbing the "full-cover across altitudes"
    //    projection from the diff altitude ──

    #[test]
    fn tiers_full_cover_matches_tier_histogram_is_full_cover_pointwise() {
        // The routing pin: `tiers_full_cover` routes through
        // `tier_histogram().is_full_cover()`, so the two seams must stay
        // pointwise equivalent under every fixture. Catches any future
        // drift where either implementation stops projecting through the
        // shared cube-native primitive. Tier-altitude peer of
        // `kinds_full_cover_matches_kind_histogram_is_full_cover_pointwise`
        // on the diff altitude in the "full-cover across altitudes"
        // projection.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_histogram = map.tier_histogram().is_full_cover();
            assert_eq!(map.tiers_full_cover(), via_histogram);
        }
    }

    #[test]
    fn tiers_full_cover_agrees_with_absent_tiers_empty_pointwise() {
        // The defining equivalence on the coverage-gap-Vec surface at the
        // tier altitude: `tiers_full_cover() == absent_tiers().is_empty()`
        // on every fixture. The full-cover-boundary of the fused
        // `(absent_tiers, absent_tiers_count)` coverage-gap peers as a
        // named boolean predicate. Lifted from the trait-uniform
        // `is_full_cover() == unobserved().next().is_none()` law on
        // AxisHistogram. Peer of
        // `kinds_full_cover_agrees_with_absent_kinds_empty_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let full_cover = map.tiers_full_cover();
            let gap_empty = map.absent_tiers().is_empty();
            assert_eq!(
                full_cover, gap_empty,
                "tiers_full_cover ({full_cover}) must agree with \
                 absent_tiers().is_empty() ({gap_empty}) for map",
            );
        }
    }

    #[test]
    fn tiers_full_cover_agrees_with_absent_tiers_count_zero_pointwise() {
        // The coverage-gap-scalar form:
        // `tiers_full_cover() == (absent_tiers_count() == 0)` on every
        // fixture. Pins the full-cover-tier-counts predicate against the
        // scalar-zero equality form on the coverage-gap side. Peer of
        // `kinds_full_cover_agrees_with_absent_kinds_count_zero_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let full_cover = map.tiers_full_cover();
            let count_zero = map.absent_tiers_count() == 0;
            assert_eq!(
                full_cover,
                count_zero,
                "tiers_full_cover ({full_cover}) must agree with \
                 absent_tiers_count == 0 (count={c}) for map",
                c = map.absent_tiers_count(),
            );
        }
    }

    #[test]
    fn tiers_full_cover_agrees_with_contributing_tiers_count_equals_axis_cardinality_pointwise() {
        // The support-scalar form: `tiers_full_cover() ==
        // (contributing_tiers_count() == axis_cardinality::<ConfigTierKind>())`
        // on every fixture — the dual-side surfacing of the same boolean
        // across the (observed, unobserved) partition. Lifted from the
        // trait-uniform `is_full_cover() == (distinct_cells() ==
        // axis_cardinality::<A>())` law on AxisHistogram. Peer of
        // `kinds_full_cover_agrees_with_present_kinds_count_equals_axis_cardinality_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let full_cover = map.tiers_full_cover();
            let support_full =
                map.contributing_tiers_count() == crate::axis_cardinality::<ConfigTierKind>();
            assert_eq!(
                full_cover, support_full,
                "tiers_full_cover ({full_cover}) must agree with \
                 contributing_tiers_count == axis_cardinality for map",
            );
        }
    }

    #[test]
    fn tiers_full_cover_agrees_with_contributing_tiers_len_equals_axis_cardinality_pointwise() {
        // The support-Vec form: `tiers_full_cover() == (contributing_tiers().len()
        // == axis_cardinality::<ConfigTierKind>())` on every fixture. Pins
        // the predicate against the `Vec<ConfigTierKind>` length form
        // consumers reach for when they already hold the support vector.
        // Peer of
        // `kinds_full_cover_agrees_with_present_kinds_len_equals_axis_cardinality_pointwise`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let full_cover = map.tiers_full_cover();
            let support_len_full =
                map.contributing_tiers().len() == crate::axis_cardinality::<ConfigTierKind>();
            assert_eq!(
                full_cover, support_len_full,
                "tiers_full_cover ({full_cover}) must agree with \
                 contributing_tiers().len() == axis_cardinality for map",
            );
        }
    }

    #[test]
    fn tiers_full_cover_empty_map_is_false() {
        // Empty-map boundary: the empty map has no observed cells, so the
        // coverage gap equals every cell of `ConfigTierKind::ALL`
        // (four-cell axis, no zero-cardinality degenerate case) —
        // `tiers_full_cover` reads `false`. Dual of
        // `tiers_balanced_empty_map_is_true`: the empty map is on the
        // opposite side of the full-cover boundary from the balanced
        // boundary. Matches `is_full_cover` reading `false` on the empty
        // histogram over a non-zero-cardinality axis one altitude down.
        // Peer of `kinds_full_cover_empty_diff_is_false`.
        let empty = ProvenanceMap::default();
        assert!(empty.is_empty());
        assert!(!empty.tiers_full_cover());
        assert_eq!(
            empty.absent_tiers_count(),
            crate::axis_cardinality::<ConfigTierKind>()
        );
    }

    #[test]
    fn tiers_full_cover_singleton_support_is_false() {
        // Singleton-support pin: every leaf lands on the same tier, so
        // one observed cell out of four leaves three cells in the
        // coverage gap — `tiers_full_cover` reads `false`. Peer of
        // `tiers_balanced_singleton_support_is_true` on the opposite
        // side of the boundary: singleton-support is trivially balanced
        // but never full-cover on a four-cell axis. Peer of
        // `kinds_full_cover_singleton_support_is_false` on the diff
        // altitude.
        let m: ProvenanceMap = ["a", "b", "c", "d"]
            .iter()
            .copied()
            .map(|k| {
                (
                    vec![k.to_owned()],
                    Provenance::computed(ConfigTierKind::Default),
                )
            })
            .collect();
        assert_eq!(m.contributing_tiers().len(), 1);
        assert!(!m.tiers_full_cover());
    }

    #[test]
    fn tiers_full_cover_uniform_cover_is_true() {
        // Uniform-cover pin: every tier contributes one leaf, so every
        // cell of `ConfigTierKind::ALL` receives at least one
        // observation — `tiers_full_cover` reads `true`. Peer of
        // `tiers_balanced_uniform_cover_is_true` on the same fixture:
        // the uniform four-tier cover is on the `true` side of BOTH the
        // balanced-tier-counts and full-cover-tier-counts boundaries.
        // Peer of `kinds_full_cover_uniform_cover_is_true` on the diff
        // altitude.
        let m: ProvenanceMap = ConfigTierKind::ALL
            .iter()
            .copied()
            .map(|t| (vec![t.as_str().to_owned()], Provenance::computed(t)))
            .collect();
        assert!(m.tiers_full_cover());
        assert!(m.tiers_balanced());
    }

    #[test]
    fn tiers_full_cover_prog_fixture_is_false() {
        // Direct pin against the concrete Prog fixture: the Prog fold
        // attributes 4 leaves as {Bare:1, Discovered:1, Default:2,
        // Custom:0}. Custom is absent from the support, so the coverage
        // gap is non-empty and `tiers_full_cover` reads `false`. Peer of
        // `tiers_balanced_prog_fixture_is_false` on the orthogonal
        // boundary — both boundaries read `false` on this fixture, but
        // for different structural reasons (Custom absent vs. counts
        // skewed).
        let r = Prog::resolve_progressive();
        assert!(!r.provenance().tiers_full_cover());
        assert!(
            r.provenance()
                .absent_tiers()
                .contains(&ConfigTierKind::Custom)
        );
    }

    #[test]
    fn tiers_full_cover_nested_fixture_is_false() {
        // Direct pin against the concrete Nested fixture: the Nested
        // fold attributes 3 leaves as {Bare:0, Discovered:1, Default:2,
        // Custom:0}. Both Bare and Custom are absent from the support,
        // so the coverage gap has size 2 and `tiers_full_cover` reads
        // `false`. Peer of `tiers_balanced_nested_fixture_is_false` on
        // the orthogonal boundary.
        let r = Nested::resolve_progressive();
        assert!(!r.provenance().tiers_full_cover());
        assert_eq!(r.provenance().absent_tiers_count(), 2);
    }

    #[test]
    fn tiers_full_cover_three_tier_cover_is_false() {
        // Three-tier cover pin: a fold observing Bare + Discovered +
        // Default but never Custom leaves one cell in the coverage gap
        // — `tiers_full_cover` reads `false`. Direct witness that the
        // three-tier-observed shape (any support of size 3) is on the
        // `false` side of the full-cover boundary. Peer of
        // `kinds_full_cover_added_removed_only_is_false` (a two-of-three
        // cover on the diff altitude) at the tier altitude (three-of-
        // four cover).
        let m: ProvenanceMap = [
            ("b", ConfigTierKind::Bare),
            ("d", ConfigTierKind::Discovered),
            ("e", ConfigTierKind::Default),
        ]
        .into_iter()
        .map(|(k, t)| (vec![k.to_owned()], Provenance::computed(t)))
        .collect();
        assert_eq!(m.contributing_tiers().len(), 3);
        assert!(!m.tiers_full_cover());
        assert!(m.absent_tiers().contains(&ConfigTierKind::Custom));
    }

    #[test]
    fn tiers_full_cover_implies_map_is_nonempty() {
        // Contrapositive of the empty-map boundary: `tiers_full_cover()
        // ⇒ !self.is_empty()`. A full-cover fold observes at least one
        // leaf per tier, so the map is non-empty. Directly witnessed on
        // the fixture set. Peer of
        // `kinds_full_cover_implies_diff_is_nonempty` on the same
        // structural implication.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            if map.tiers_full_cover() {
                assert!(
                    !map.is_empty(),
                    "full-cover map must be non-empty (len={})",
                    map.len(),
                );
            }
        }
    }

    #[test]
    fn tiers_full_cover_implies_contributing_tiers_equals_axis_cardinality() {
        // Structural characterization: `tiers_full_cover() ⇒
        // contributing_tiers().len() == axis_cardinality::<ConfigTierKind>()`.
        // A full-cover fold observes every tier, so the support size
        // equals the axis cardinality. Direct witness of the trait-
        // uniform `is_full_cover() ⇒ distinct_cells() ==
        // axis_cardinality::<A>()` law on AxisHistogram, lifted to the
        // tier altitude. Peer of
        // `kinds_full_cover_implies_present_kinds_equals_axis_cardinality`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            if map.tiers_full_cover() {
                assert_eq!(
                    map.contributing_tiers().len(),
                    crate::axis_cardinality::<ConfigTierKind>(),
                    "full-cover map must observe every ConfigTierKind",
                );
            }
        }
    }

    #[test]
    fn tiers_full_cover_implies_leaf_count_bounded_below_by_axis_cardinality() {
        // Leaf-count lower-bound characterization: `tiers_full_cover()
        // ⇒ self.len() >= axis_cardinality::<ConfigTierKind>()`. A
        // full-cover fold observes at least one leaf per tier, so the
        // leaf count is bounded below by the axis cardinality (four on
        // the ConfigTierKind axis). Directly witnessed on the fixture
        // set. Peer of
        // `kinds_full_cover_implies_line_count_bounded_below_by_axis_cardinality`.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            if map.tiers_full_cover() {
                assert!(
                    map.len() >= crate::axis_cardinality::<ConfigTierKind>(),
                    "full-cover map must have >= axis_cardinality leaves (was {})",
                    map.len(),
                );
            }
        }
    }

    #[test]
    fn tiers_full_cover_skewed_four_cell_fixture_is_true() {
        // Direct pin: a strictly-ordered four-cell case with Bare=1,
        // Discovered=2, Default=3, Custom=4 has every tier observed —
        // `tiers_full_cover` reads `true`, orthogonal to
        // `tiers_balanced` which reads `false` on the identical fixture
        // (peak 4, trough 1, spread 3). Every tier observed but at
        // strictly-distinct counts: full-cover is the coverage boundary,
        // not the uniformity boundary. Peer of
        // `kinds_full_cover_skewed_three_cell_fixture_is_true` at the
        // tier altitude.
        let m: ProvenanceMap = [
            ("b1", ConfigTierKind::Bare),
            ("d1", ConfigTierKind::Discovered),
            ("d2", ConfigTierKind::Discovered),
            ("e1", ConfigTierKind::Default),
            ("e2", ConfigTierKind::Default),
            ("e3", ConfigTierKind::Default),
            ("c1", ConfigTierKind::Custom),
            ("c2", ConfigTierKind::Custom),
            ("c3", ConfigTierKind::Custom),
            ("c4", ConfigTierKind::Custom),
        ]
        .into_iter()
        .map(|(k, t)| (vec![k.to_owned()], Provenance::computed(t)))
        .collect();
        assert!(m.tiers_full_cover());
        assert!(!m.tiers_balanced());
    }

    #[test]
    fn tiers_full_cover_agrees_with_open_coded_all_positive_walk() {
        // Parity against the exact hand-rolled full-cover walk this lift
        // replaces: walk every cell of the histogram and check every
        // count is positive. Mirrors the parity pin
        // `kinds_full_cover_agrees_with_open_coded_all_positive_walk` on
        // the diff altitude. Note the walk uses `hist.iter()` which
        // iterates over the closed axis's ALL cells in declaration order
        // — a full-cover fold has every cell nonzero regardless of order.
        for map in [
            Prog::resolve_progressive().provenance().clone(),
            Nested::resolve_progressive().provenance().clone(),
            ProvenanceMap::default(),
        ] {
            let via_seam = map.tiers_full_cover();
            let hist = map.tier_histogram();
            let hand_rolled = hist.iter().all(|(_, c)| c > 0);
            assert_eq!(via_seam, hand_rolled);
        }
    }

    // ── Nested per-leaf attribution ──

    #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
    struct Win {
        w: u32,
        h: u32,
    }
    #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
    struct Nested {
        win: Win,
        theme: u32,
    }
    impl TieredConfig for Nested {
        fn bare() -> Self {
            Self {
                win: Win { w: 0, h: 0 },
                theme: 0,
            }
        }
        fn discovered() -> Self {
            Self {
                win: Win { w: 100, h: 0 },
                theme: 0,
            }
        }
        fn prescribed_default() -> Self {
            Self {
                win: Win { w: 100, h: 50 },
                theme: 7,
            }
        }
    }

    #[test]
    fn progressive_attributes_nested_leaves_independently() {
        let r = Nested::resolve_progressive();
        assert_eq!(r.value().win.w, 100);
        assert_eq!(r.value().win.h, 50);
        // win.w detected → Discovered; win.h curated → Default; sibling leaves
        // under `win` keep independent credit.
        assert_eq!(
            r.provenance().provenance_of(&["win", "w"]).unwrap().tier(),
            ConfigTierKind::Discovered,
        );
        assert_eq!(
            r.provenance().provenance_of(&["win", "h"]).unwrap().tier(),
            ConfigTierKind::Default,
        );
        assert_eq!(
            r.provenance().provenance_of(&["theme"]).unwrap().tier(),
            ConfigTierKind::Default,
        );
    }

    // ── discovered_from_layers — the low-ceremony kanchi seam ──

    struct AxisLayer {
        key: &'static str,
        val: u32,
    }
    impl DiscoveryLayer for AxisLayer {
        fn name(&self) -> &'static str {
            "axis"
        }
        fn discover(&self) -> Dict {
            let mut d = Dict::new();
            d.insert(self.key.to_owned(), Value::from(self.val));
            d
        }
    }

    // A config whose `discovered()` is wired DECLARATIVELY from layers (the
    // gap-1 seam), and whose `prescribed_default()` is built on discovered()
    // — the mado pattern, without the hand-rolled struct literal.
    #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
    struct Seam {
        a: u32,
        b: u32,
    }
    impl TieredConfig for Seam {
        fn bare() -> Self {
            Self { a: 0, b: 0 }
        }
        fn discovered() -> Self {
            Self::discovered_from_layers(&[&AxisLayer { key: "a", val: 42 }])
        }
        fn prescribed_default() -> Self {
            let mut s = Self::discovered();
            s.b = 2;
            s
        }
    }

    #[test]
    fn discovered_from_layers_overlays_detected_axes_on_bare() {
        let d = Seam::discovered();
        assert_eq!(d.a, 42, "detected axis a overlays bare");
        assert_eq!(d.b, 0, "an axis no layer set keeps the bare floor");
    }

    #[test]
    fn discovered_from_layers_empty_stack_is_bare() {
        // Totality: no layers (or an undetectable axis) degenerates to bare.
        assert_eq!(Seam::discovered_from_layers(&[]), Seam::bare());
    }

    #[test]
    fn seam_progressive_shows_detected_axis_through_prescribed() {
        let r = Seam::resolve_progressive();
        assert_eq!(*r.value(), Seam { a: 42, b: 2 });
        assert_eq!(
            r.provenance().provenance_of(&["a"]).unwrap().tier(),
            ConfigTierKind::Discovered,
        );
        assert_eq!(
            r.provenance().provenance_of(&["b"]).unwrap().tier(),
            ConfigTierKind::Default,
        );
    }

    // ── Provenance primitive surface ──

    #[test]
    fn provenance_display_is_typed() {
        assert_eq!(
            Provenance::computed(ConfigTierKind::Discovered).to_string(),
            "discovered"
        );
        assert_eq!(
            Provenance::file("/x.yaml").to_string(),
            "custom (file: /x.yaml)"
        );
        assert_eq!(Provenance::env("APP_").to_string(), "custom (env: APP_)");
    }

    #[test]
    fn provenance_tier_ordinal_reuses_closed_axis_order() {
        // Precedence reuses the const ConfigTierKind ClosedAxis declaration
        // order — Bare < Discovered < Default < Custom.
        assert!(
            Provenance::computed(ConfigTierKind::Bare).tier_ordinal()
                < Provenance::computed(ConfigTierKind::Discovered).tier_ordinal()
        );
        assert!(
            Provenance::computed(ConfigTierKind::Discovered).tier_ordinal()
                < Provenance::computed(ConfigTierKind::Default).tier_ordinal()
        );
        assert!(
            Provenance::computed(ConfigTierKind::Default).tier_ordinal()
                < Provenance::file("/x").tier_ordinal()
        );
    }
}