shikumi 0.1.168

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
//! 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(),
        }
    }

    /// The distinct tiers that produced ≥1 surviving effective leaf, in
    /// [`ConfigTier`] precedence order — the post-fold dual of "which tiers'
    /// opinions survived".
    #[must_use]
    pub fn contributing_tiers(&self) -> Vec<ConfigTierKind> {
        let mut seen: Vec<ConfigTierKind> = Vec::new();
        for prov in self.inner.values() {
            if !seen.contains(&prov.tier) {
                seen.push(prov.tier);
            }
        }
        seen.sort_by_key(|k| crate::axis_ordinal(*k));
        seen
    }
}

/// 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<'_> {}

// ── 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))
    }
}

#[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),
            ],
        );
    }

    #[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
        );
    }

    // ── 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()
        );
    }
}