shikumi 0.1.92

Shikumi (仕組み) — config discovery, hot-reload, and ArcSwap store for Nix-managed desktop apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
//! Observable reload failure summary.
//!
//! [`ReloadFailure`] is the typed, [`Clone`]-able shape that
//! [`crate::ConfigStore`] publishes when a reload — manual
//! ([`crate::ConfigStore::reload`]) or hot-reload (the watcher in
//! [`crate::ConfigStore::load_and_watch`]) — fails. The slot is cleared
//! atomically when a subsequent reload succeeds, so observers get a
//! "most recent unrecovered failure" hint, not a history.
//!
//! [`crate::ShikumiError`] itself is not [`Clone`] (it boxes
//! `figment::Error`, which is not Clone). `ReloadFailure` is the
//! cross-thread observable form: a typed value that captures the
//! display string and the [`crate::ConfigSource`] chain at the moment
//! the failure was caught.

use std::fmt;

use crate::error::{
    AttributionAxis, AttributionConfidence, AttributionCoordinates, AttributionNameKindCoordinates,
    AttributionRule, AttributionSourceKindCoordinates, ErrorLocalizationCoordinates,
    FailingSourceAttribution, FieldPathLocalization, ShikumiError, ShikumiErrorKind,
    dotted_field_path,
};
use crate::source::{ConfigSource, ConfigSourceKind, FigmentNameTagKind, FigmentSourceKind};

/// A clone-able summary of the most recent reload failure on a
/// [`crate::ConfigStore`].
///
/// Pairs with [`crate::ConfigStore::generation`]: when an observer sees
/// the generation has not advanced past a checkpoint and a
/// [`ReloadFailure`] is present, the failure is the reason the
/// expected publish did not happen.
///
/// `#[non_exhaustive]` so future fidelity work (per-field path,
/// file/line spans, source provenance for non-`Extract` variants)
/// lands additively.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ReloadFailure {
    /// Human-readable display of the underlying error, captured via
    /// [`std::fmt::Display`] at the moment the failure was caught.
    pub message: String,
    /// Closed-enum kind of the underlying [`ShikumiError`] that caused
    /// this reload failure, captured from
    /// [`crate::ShikumiError::kind`] at the moment the failure was
    /// caught. Total over the [`ReloadFailure`] surface — every captured
    /// failure has exactly one kind, regardless of whether attribution
    /// could be resolved.
    ///
    /// Surfaces the [`ShikumiErrorKind`] partition on the cross-thread
    /// observable envelope so consumers reading
    /// [`crate::ConfigStore::last_reload_error`] can bucket reload
    /// failures by error class (per-kind alert thresholds, per-kind
    /// dashboards, per-kind retry policies) with one closed-enum read
    /// instead of grepping the [`Self::message`] string. Pairs with
    /// [`Self::attribution_rule`] (rule axis, partial), [`Self::layer_kind`]
    /// (layer-kind axis, partial), and [`Self::attribution_confidence`]
    /// (confidence axis, partial) to give observers the full
    /// (kind × layer-kind × rule × confidence) projection of every
    /// captured failure as four typed reads.
    pub kind: ShikumiErrorKind,
    /// Provider chain in merge order at the moment of failure.
    /// Populated for [`crate::ShikumiError::Extract`]; empty for
    /// variants that do not record a chain (see
    /// [`crate::ShikumiError::sources`]).
    pub sources: Vec<ConfigSource>,
    /// Dotted field path of the offending key at the moment of failure,
    /// captured from [`crate::ShikumiError::field_path`]. Populated for
    /// extraction failures that figment could localize (e.g. a type
    /// mismatch on a typed field renders as `["count"]`); empty for
    /// non-figment-bearing variants and figment errors without a key
    /// context.
    pub field_path: Vec<String>,
    /// Specific [`ConfigSource`] in [`Self::sources`] that produced the
    /// offending value, captured from
    /// [`crate::ShikumiError::failing_source`] at the moment the failure
    /// was caught. Owned [`ConfigSource`] so the slot survives any
    /// borrow on the originating error.
    ///
    /// `None` for non-`Extract` failures, for `Extract` failures whose
    /// figment error did not carry per-value `Metadata`, and when the
    /// metadata could not be matched to any entry in the recorded
    /// chain. Pairs with [`Self::sources`] (full chain),
    /// [`Self::field_path`] (offending key),
    /// [`Self::attribution_rule`] (why the layer was blamed), and
    /// [`Self::layer_kind`] (file/env/defaults class of the blamed
    /// layer): when present, the tuple pins
    /// `(which-layer × which-field × which-rule × which-kind)` for
    /// the specific failure.
    pub failing_source: Option<ConfigSource>,
    /// The [`AttributionRule`] under which [`Self::failing_source`]
    /// was attributed, captured from
    /// [`crate::ShikumiError::failing_attribution`] at the moment the
    /// failure was caught. `Some(_)` exactly when
    /// [`Self::failing_source`] is `Some(_)`; `None` otherwise.
    ///
    /// Distinguishes *exact* attribution
    /// ([`AttributionRule::FileBySource`] /
    /// [`AttributionRule::FileByMetadataName`] /
    /// [`AttributionRule::EnvByPrefix`]) from *fallback* attribution
    /// ([`AttributionRule::EnvByUniqueness`] /
    /// [`AttributionRule::DefaultsByCodeUniqueness`]) for observers
    /// that want to weight the two differently in dashboards or
    /// alerting policies.
    pub attribution_rule: Option<AttributionRule>,
}

impl ReloadFailure {
    /// Capture a [`ReloadFailure`] from a [`ShikumiError`] reference.
    ///
    /// The error itself is not consumed — only its display string,
    /// recorded source chain (if any), and dotted field path (if any)
    /// are copied. This is the one canonical constructor; both
    /// [`crate::ConfigStore::reload`] and the
    /// [`crate::ConfigStore::load_and_watch`] watcher closure use it on
    /// the failure path.
    #[must_use]
    pub fn from_error(err: &ShikumiError) -> Self {
        let attribution = err.failing_attribution();
        Self {
            message: err.to_string(),
            kind: err.kind(),
            sources: err.sources().map(<[_]>::to_vec).unwrap_or_default(),
            field_path: err.field_path().map(<[_]>::to_vec).unwrap_or_default(),
            failing_source: attribution.map(|a| a.source.clone()),
            attribution_rule: attribution.map(|a| a.rule),
        }
    }

    /// [`ShikumiErrorKind`] of the underlying error this failure was
    /// captured from — convenience accessor over [`Self::kind`] (the
    /// public field). Total over the [`ReloadFailure`] surface (no
    /// [`Option`]): every captured failure has exactly one kind, peer to
    /// the way every [`ShikumiError`] always answers
    /// [`ShikumiError::kind`].
    ///
    /// Surfaces the kind axis on the cross-thread observable envelope so
    /// observers (dashboards, alerting policies, structured-log routers)
    /// route on error class without re-deriving from [`Self::message`]
    /// or destructuring the underlying [`ShikumiError`]. The accessor
    /// is the structural peer of [`Self::attribution_confidence`] and
    /// [`Self::layer_kind`] — typed projection over the captured
    /// failure surface — but its return type is
    /// [`ShikumiErrorKind`] (not `Option<_>`), because every error has
    /// a kind even when no attribution can be resolved.
    ///
    /// Composes orthogonally with [`Self::layer_kind`] (over the
    /// (file × env × defaults) axis) and
    /// [`Self::attribution_confidence`] (over the (exact × fallback)
    /// axis): together the three accessors close the
    /// (kind × layer-kind × confidence) projection over the failure
    /// surface. The kind axis is the only one of the three that is
    /// always populated; the other two answer
    /// `None` for non-attributed failures.
    #[must_use]
    pub fn kind(&self) -> ShikumiErrorKind {
        self.kind
    }

    /// Confidence class of [`Self::attribution_rule`], or `None`
    /// when no attribution was recorded — strict superset of
    /// [`Self::attribution_rule`]`.map(AttributionRule::confidence)`,
    /// surfaced as a typed accessor so observers (dashboards,
    /// alerting policies) don't re-derive the exact-vs-fallback
    /// partition at every site.
    ///
    /// Returns `Some(_)` exactly when [`Self::attribution_rule`] is
    /// `Some(_)`; `None` otherwise. Pairs with
    /// [`Self::failing_source`] (which layer), [`Self::layer_kind`]
    /// (which kind of layer), and [`Self::attribution_rule`] (why
    /// named) to give observers the (which-layer × which-kind ×
    /// which-rule × how-confident) attribution quadruple in four
    /// closed-enum reads.
    #[must_use]
    pub fn attribution_confidence(&self) -> Option<AttributionConfidence> {
        self.attribution_rule.map(AttributionRule::confidence)
    }

    /// [`ConfigSourceKind`] of the layer blamed for the failure, or
    /// `None` when no attribution was recorded — strict superset of
    /// [`Self::attribution_rule`]`.map(AttributionRule::layer_kind)`,
    /// surfaced as a typed accessor so observers (dashboards,
    /// alerting policies, structured-log routers) don't re-derive
    /// the (file × env × defaults) partition at every site.
    ///
    /// Returns `Some(_)` exactly when [`Self::attribution_rule`] is
    /// `Some(_)` (equivalently: when [`Self::failing_source`] is
    /// `Some(_)`); `None` otherwise. Equal to
    /// `self.failing_source.as_ref().map(ConfigSource::kind)` by
    /// construction — the cross-primitive
    /// `attr.rule.layer_kind() == attr.source.kind()` invariant from
    /// [`crate::FailingSourceAttribution`] propagates through
    /// [`Self::from_error`] into this slot, pinned end-to-end by
    /// `layer_kind_agrees_with_failing_source_kind_when_attributed`.
    ///
    /// Composes with [`Self::attribution_confidence`]: orthogonal
    /// projections over the rule space along the
    /// (file × env × defaults) and (exact × fallback) axes
    /// respectively. Observers reading
    /// `Arc<ReloadFailure>` from
    /// [`crate::ConfigStore::last_reload_error`] route on layer-kind
    /// without destructuring the rule, and weight fallback
    /// attributions visibly via the confidence accessor — both
    /// reads land as one closed-enum match each.
    #[must_use]
    pub fn layer_kind(&self) -> Option<ConfigSourceKind> {
        self.attribution_rule.map(AttributionRule::layer_kind)
    }

    /// [`AttributionAxis`] of the rule that named the blamed layer,
    /// or `None` when no attribution was recorded — strict superset
    /// of [`Self::attribution_rule`]`.map(AttributionRule::metadata_axis)`,
    /// surfaced as a typed accessor so observers (dashboards,
    /// alerting policies, attestation manifests) don't re-derive the
    /// (`metadata.source` × `metadata.name`) partition at every
    /// observation site.
    ///
    /// Returns `Some(_)` exactly when [`Self::attribution_rule`] is
    /// `Some(_)` (equivalently: when [`Self::failing_source`] is
    /// `Some(_)`); `None` otherwise. Composes with
    /// [`Self::layer_kind`] (file × env × defaults) and
    /// [`Self::attribution_confidence`] (exact × fallback) as the
    /// third orthogonal projection over the rule space, giving
    /// observers the (axis × layer-kind × confidence) coordinates
    /// of every attributed failure as three closed-enum reads.
    ///
    /// Operationally distinguishes attributions driven by figment's
    /// typed source classification (structurally stable —
    /// [`AttributionAxis::MetadataSource`]) from attributions driven
    /// by parsing figment's human-readable provider-name string
    /// (string-shape-dependent — [`AttributionAxis::MetadataName`]).
    /// Observers that want to weight name-axis attributions visibly
    /// weaker than source-axis ones — peer to weighting
    /// [`AttributionConfidence::Fallback`] weaker than
    /// [`AttributionConfidence::Exact`] — read this accessor.
    #[must_use]
    pub fn metadata_axis(&self) -> Option<AttributionAxis> {
        self.attribution_rule.map(AttributionRule::metadata_axis)
    }

    /// [`FigmentSourceKind`] structurally pinned by
    /// [`Self::attribution_rule`], or `None` when no attribution was
    /// recorded *or* when the recorded attribution is name-axis
    /// (where the rule's identity does not constrain
    /// `figment::Metadata::source`) — strict superset of
    /// [`Self::attribution_rule`]`.and_then(AttributionRule::figment_source_kind)`,
    /// surfaced as a typed accessor so observers (dashboards,
    /// alerting policies, attestation manifests) don't re-derive the
    /// (`Source::File` × `Source::Code` × `Source::Custom` × no-rule
    /// × name-axis) partition at every observation site.
    ///
    /// Two-stage `None` discipline: (1) `None` when no attribution
    /// was recorded ([`Self::attribution_rule`] is [`None`]),
    /// (2) `None` when the recorded attribution is name-axis
    /// ([`Self::metadata_axis`] is
    /// [`Some(AttributionAxis::MetadataName)`]) — neither path pins a
    /// figment-Source-axis cell. Source-axis attributions
    /// ([`AttributionRule::FileBySource`] →
    /// [`Some(FigmentSourceKind::File)`],
    /// [`AttributionRule::DefaultsByCodeUniqueness`] →
    /// [`Some(FigmentSourceKind::Code)`]) surface a [`Some`] cell
    /// directly. Operationally distinguishes "no provenance at all"
    /// from "name-axis provenance whose figment Source kind was not
    /// retained" — observers cannot recover figment's `Source`
    /// classification off the cross-thread envelope, but they can
    /// route on whether the attribution rule already pinned it.
    ///
    /// Composes with [`Self::metadata_axis`] as a refinement on the
    /// source-axis cells: when `Some`, the projection is
    /// [`Some`] exactly when [`Self::metadata_axis`] returns
    /// [`Some(AttributionAxis::MetadataSource)`]. Pinned by
    /// `figment_source_kind_some_iff_metadata_axis_metadata_source`.
    /// Composes with [`Self::layer_kind`] as a partial diagonal: when
    /// `Some`, `(figment_source_kind, layer_kind) ∈ {(File, File),
    /// (Code, Defaults)}` — pinned by
    /// `figment_source_kind_agrees_with_layer_kind_pointwise_when_some`.
    #[must_use]
    pub fn figment_source_kind(&self) -> Option<FigmentSourceKind> {
        self.attribution_rule
            .and_then(AttributionRule::figment_source_kind)
    }

    /// [`FigmentNameTagKind`] structurally pinned by
    /// [`Self::attribution_rule`], or `None` when no attribution was
    /// recorded *or* when the recorded attribution is source-axis
    /// (where the rule's identity does not constrain
    /// `figment::Metadata::name`) — strict superset of
    /// [`Self::attribution_rule`]`.and_then(AttributionRule::figment_name_tag_kind)`,
    /// surfaced as a typed accessor so observers (dashboards,
    /// alerting policies, attestation manifests) don't re-derive the
    /// (rule → figment-name-tag-kind) partial projection at every
    /// observation site.
    ///
    /// Symmetric peer of [`Self::figment_source_kind`] on the
    /// figment-`Metadata::name` axis — the two accessors close the
    /// cross-thread observable form's figment-metadata kind universe.
    /// Before this accessor, the name-axis-side classification could
    /// not survive the borrowed-tag → owned-envelope boundary: the
    /// underlying [`FigmentNameTag`] is lifetime-parameterized
    /// (allocation-free but unable to cross thread boundaries or
    /// persist in [`ReloadFailure`]), so observers reading
    /// [`crate::ConfigStore::last_reload_error`] could only reach the
    /// figment-name-axis kind by retaining the live [`ShikumiError`]
    /// (impossible — [`ShikumiError`] is not [`Clone`]) or by
    /// re-parsing [`Self::message`] for the originating tag shape (a
    /// drift-prone string surface). The lifted accessor surfaces the
    /// `'static` [`FigmentNameTagKind`] discriminant through the
    /// captured rule slot.
    ///
    /// Two-stage `None` discipline mirroring [`Self::figment_source_kind`]:
    /// (1) `None` when no attribution was recorded
    /// ([`Self::attribution_rule`] is [`None`]),
    /// (2) `None` when the recorded attribution is source-axis
    /// ([`Self::metadata_axis`] is
    /// [`Some(AttributionAxis::MetadataSource)`]) — neither path pins a
    /// figment-name-axis cell. Name-axis attributions
    /// ([`AttributionRule::FileByMetadataName`] →
    /// [`Some(FigmentNameTagKind::Format)`],
    /// [`AttributionRule::EnvByPrefix`] /
    /// [`AttributionRule::EnvByUniqueness`] →
    /// [`Some(FigmentNameTagKind::Env)`]) surface a [`Some`] cell directly.
    /// Operationally distinguishes "no provenance at all" from
    /// "source-axis provenance whose figment name-tag kind was not
    /// retained" — observers cannot recover figment's `Metadata::name`
    /// classification off the cross-thread envelope, but they can
    /// route on whether the attribution rule already pinned it.
    ///
    /// Composes with [`Self::metadata_axis`] as a refinement on the
    /// name-axis cells: when [`Some`], the projection is [`Some`]
    /// exactly when [`Self::metadata_axis`] returns
    /// [`Some(AttributionAxis::MetadataName)`]. Pinned by
    /// `figment_name_tag_kind_some_iff_metadata_axis_metadata_name`.
    /// Composes with [`Self::figment_source_kind`] as a strict
    /// partition over the attributed-envelope surface: every attributed
    /// failure has exactly one of the two figment-metadata kind cells
    /// surfaced as [`Some`]; unattributed failures have both as [`None`].
    /// Pinned by
    /// `figment_name_tag_kind_xor_figment_source_kind_on_attributed_envelopes`.
    ///
    /// Cross-thread mirror of
    /// [`FailingSourceAttribution::figment_name_tag_kind`] (and of
    /// [`AttributionRule::figment_name_tag_kind`] at the rule layer): the
    /// captured envelope's projection agrees pointwise with the live
    /// error's, pinning the lossless-capture contract for the
    /// figment-name-tag-kind axis on the cross-thread observable form.
    /// Pinned by
    /// `figment_name_tag_kind_agrees_with_underlying_error_pointwise`.
    ///
    /// [`FigmentNameTag`]: crate::FigmentNameTag
    /// [`ShikumiError`]: crate::ShikumiError
    #[must_use]
    pub fn figment_name_tag_kind(&self) -> Option<FigmentNameTagKind> {
        self.attribution_rule
            .and_then(AttributionRule::figment_name_tag_kind)
    }

    /// [`crate::FormatProvenance`] of the file layer blamed for the
    /// failure, or `None` when no attribution was recorded *or* when
    /// the recorded attribution is not on the file axis — strict
    /// superset of
    /// [`Self::attribution_rule`]`.and_then(AttributionRule::file_provenance)`,
    /// surfaced as a typed accessor so observers (dashboards, alerting
    /// policies, attestation manifests, structured-log routers) don't
    /// re-derive the (rule → file-provenance) partial projection at
    /// every observation site.
    ///
    /// Two-stage `None` discipline mirroring [`Self::figment_source_kind`]:
    /// (1) `None` when no attribution was recorded
    /// ([`Self::attribution_rule`] is [`None`]),
    /// (2) `None` when the recorded attribution is not on the file
    /// axis ([`Self::layer_kind`] is anything other than
    /// [`Some(crate::ConfigSourceKind::File)`]) — neither path pins a
    /// file-provider class. File-axis attributions
    /// ([`AttributionRule::FileBySource`] →
    /// [`Some(crate::FormatProvenance::FigmentBuiltin)`],
    /// [`AttributionRule::FileByMetadataName`] →
    /// [`Some(crate::FormatProvenance::ShikumiBuilt)`]) surface a
    /// [`Some`] cell directly. Operationally distinguishes "no
    /// attribution at all" from "env-axis or defaults-axis attribution
    /// that names no provider class" — observers cannot recover the
    /// originating provider class off the cross-thread envelope unless
    /// the captured rule already pinned it.
    ///
    /// Composes with [`Self::layer_kind`] as a refinement on the
    /// file-axis cells: when [`Some`], the projection is [`Some`]
    /// exactly when [`Self::layer_kind`] returns
    /// [`Some(crate::ConfigSourceKind::File)`]. Pinned by
    /// `file_provenance_some_iff_layer_kind_file`.
    ///
    /// Cross-thread mirror of
    /// [`FailingSourceAttribution::file_provenance`] (and of
    /// [`AttributionRule::file_provenance`] at the rule layer): the
    /// captured envelope's projection agrees pointwise with the live
    /// error's, pinning the lossless-capture contract for the
    /// file-provenance axis on the cross-thread observable form.
    /// Pinned by
    /// `file_provenance_agrees_with_underlying_error_pointwise`.
    ///
    /// Composes with [`Self::failing_source`] as the
    /// "which-layer × which-provider-class" coordinate over the file
    /// attribution sub-surface: a structured-log replay, attestation
    /// manifest, or per-format alerting policy that routes on both
    /// halves no longer reaches for the rule slot and projects through
    /// it inline.
    #[must_use]
    pub fn file_provenance(&self) -> Option<crate::FormatProvenance> {
        self.attribution_rule
            .and_then(AttributionRule::file_provenance)
    }

    /// Joint (figment-Source-axis kind × shikumi-layer-kind) cell
    /// pinned by [`Self::attribution_rule`], or `None` when no
    /// attribution was recorded *or* when the recorded attribution
    /// is name-axis (where the rule's identity does not constrain
    /// `figment::Metadata::source` and so does not pin a joint cell)
    /// — strict superset of
    /// [`Self::attribution_rule`]`.and_then(AttributionRule::attribution_source_kind_coordinates)`,
    /// surfaced as a typed accessor so observers (dashboards,
    /// alerting policies, attestation manifests) don't re-derive the
    /// (rule → joint cell) projection at every observation site.
    ///
    /// Two-stage `None` discipline mirroring
    /// [`Self::figment_source_kind`]: (1) `None` when no attribution
    /// was recorded ([`Self::attribution_rule`] is [`None`]),
    /// (2) `None` when the recorded attribution is name-axis
    /// ([`Self::metadata_axis`] is
    /// [`Some(AttributionAxis::MetadataName)`]) — neither path pins
    /// the joint cell. Source-axis attributions
    /// ([`AttributionRule::FileBySource`] → `(File, File)`,
    /// [`AttributionRule::DefaultsByCodeUniqueness`] →
    /// `(Code, Defaults)`) surface a [`Some`] cell directly.
    ///
    /// Composes [`Self::figment_source_kind`] and [`Self::layer_kind`]
    /// into one [`Copy`] joint cell; observers reading
    /// [`crate::ConfigStore::last_reload_error`] no longer pair the
    /// two partial reads inline. Every [`Some`] return satisfies
    /// [`AttributionSourceKindCoordinates::is_realizable`] —
    /// the structural diagonal of source-axis rules — pinned by
    /// `attribution_source_kind_coordinates_returns_realizable_cell_when_some`.
    ///
    /// Cross-thread mirror of
    /// [`FailingSourceAttribution::attribution_source_kind_coordinates`]
    /// (and of [`AttributionRule::attribution_source_kind_coordinates`]
    /// at the rule layer): the captured envelope's joint cell agrees
    /// pointwise with the live error's, pinning the lossless-capture
    /// contract for the source-axis joint cell on the cross-thread
    /// observable form. Pinned by
    /// `attribution_source_kind_coordinates_agrees_with_paired_projections_pointwise`.
    #[must_use]
    pub fn attribution_source_kind_coordinates(&self) -> Option<AttributionSourceKindCoordinates> {
        self.attribution_rule
            .and_then(AttributionRule::attribution_source_kind_coordinates)
    }

    /// Joint (figment-`Metadata::name`-axis kind × shikumi-layer-kind)
    /// cell pinned by [`Self::attribution_rule`], or `None` when no
    /// attribution was recorded *or* when the recorded attribution is
    /// source-axis (where the rule's identity does not constrain
    /// `figment::Metadata::name` and so does not pin a joint cell) —
    /// strict superset of
    /// [`Self::attribution_rule`]`.and_then(AttributionRule::attribution_name_kind_coordinates)`,
    /// surfaced as a typed accessor so observers (dashboards, alerting
    /// policies, attestation manifests) don't re-derive the (rule →
    /// joint cell) projection at every observation site.
    ///
    /// Symmetric peer of [`Self::attribution_source_kind_coordinates`]
    /// on the figment-`Metadata::name` axis — the two accessors close
    /// the cross-thread observable form's figment-metadata × shikumi-
    /// layer joint-cell universe. Every attributed envelope surfaces
    /// exactly one of the two joint cells as [`Some`]; unattributed
    /// envelopes surface both as [`None`]. Pinned by
    /// `attribution_name_kind_coordinates_xor_attribution_source_kind_coordinates_on_attributed_envelopes`.
    ///
    /// Two-stage `None` discipline mirroring
    /// [`Self::attribution_source_kind_coordinates`]: (1) `None` when
    /// no attribution was recorded ([`Self::attribution_rule`] is
    /// [`None`]), (2) `None` when the recorded attribution is
    /// source-axis ([`Self::metadata_axis`] is
    /// [`Some(AttributionAxis::MetadataSource)`]) — neither path pins
    /// the joint cell. Name-axis attributions
    /// ([`AttributionRule::FileByMetadataName`] → `(Format, File)`,
    /// [`AttributionRule::EnvByPrefix`] /
    /// [`AttributionRule::EnvByUniqueness`] → `(Env, Env)`) surface a
    /// [`Some`] cell directly.
    ///
    /// Composes [`Self::figment_name_tag_kind`] and [`Self::layer_kind`]
    /// into one [`Copy`] joint cell; observers reading
    /// [`crate::ConfigStore::last_reload_error`] no longer pair the two
    /// partial reads inline. Every [`Some`] return satisfies
    /// [`AttributionNameKindCoordinates::is_realizable`] — the
    /// structural diagonal of name-axis rules — pinned by
    /// `attribution_name_kind_coordinates_returns_realizable_cell_when_some`.
    ///
    /// Cross-thread mirror of
    /// [`FailingSourceAttribution::attribution_name_kind_coordinates`]
    /// (and of [`AttributionRule::attribution_name_kind_coordinates`]
    /// at the rule layer): the captured envelope's joint cell agrees
    /// pointwise with the live error's, pinning the lossless-capture
    /// contract for the name-axis joint cell on the cross-thread
    /// observable form. Pinned by
    /// `attribution_name_kind_coordinates_agrees_with_paired_projections_pointwise`.
    #[must_use]
    pub fn attribution_name_kind_coordinates(&self) -> Option<AttributionNameKindCoordinates> {
        self.attribution_rule
            .and_then(AttributionRule::attribution_name_kind_coordinates)
    }

    /// Coordinate triple of [`Self::attribution_rule`], or `None` when
    /// no attribution was recorded — strict superset of the three
    /// sibling Option-returning accessors
    /// ([`Self::attribution_confidence`], [`Self::layer_kind`],
    /// [`Self::metadata_axis`]) collapsed into one
    /// [`Option<AttributionCoordinates>`] read.
    ///
    /// Returns `Some(_)` exactly when [`Self::attribution_rule`] is
    /// `Some(_)` (equivalently: when [`Self::failing_source`] is
    /// `Some(_)`); `None` otherwise. The same `Some-iff-attribution`
    /// discipline as the sibling projections — pinned by
    /// `coordinates_some_iff_attribution_rule_some`.
    ///
    /// One source of truth for the (axis × layer-kind × confidence)
    /// triple on the cross-thread observable envelope. Before this
    /// accessor, observers reading
    /// [`crate::ConfigStore::last_reload_error`] inlined three
    /// `self.attribution_rule.map(AttributionRule::*)` calls at every
    /// site — a recurring three-line pattern. The named struct
    /// [`AttributionCoordinates`] collapses them to one read,
    /// surfacing the triple as a typescape value (`Copy + Eq + Hash`)
    /// usable as a `HashMap` key, log label, or attestation-manifest
    /// payload without consumers re-deriving the triple at every
    /// observation site.
    ///
    /// Pairs with [`AttributionRule::from_coordinates`]: an observer
    /// that captured the [`AttributionCoordinates`] of a previous
    /// failure (e.g. into a structured-log line) can re-hydrate the
    /// originating rule by one method call, recovering the closed-enum
    /// rule identity from its coordinates without retaining the
    /// originating [`crate::ShikumiError`]. The bijection is pinned by
    /// `coordinates_round_trip_through_from_coordinates`.
    #[must_use]
    pub fn coordinates(&self) -> Option<AttributionCoordinates> {
        self.attribution_rule.map(AttributionRule::coordinates)
    }

    /// Borrowed [`FailingSourceAttribution`] envelope fused from the
    /// two parallel [`Self::failing_source`] / [`Self::attribution_rule`]
    /// slots — peer to [`crate::ShikumiError::failing_attribution`] on
    /// the live error surface, lifted onto the cross-thread observable
    /// form.
    ///
    /// Returns [`Some`] exactly when both slots are populated
    /// (the [`Some`]-iff-attribution invariant pinned by
    /// `from_error_attribution_rule_some_iff_failing_source_some`),
    /// [`None`] otherwise. Reuses the existing borrowed envelope shape
    /// rather than introducing a new owned counterpart: the source
    /// borrows into [`Self::failing_source`], the rule is [`Copy`], and
    /// the envelope shares the captured failure's lifetime.
    ///
    /// One source of truth for the (`failing_source` × `attribution_rule`)
    /// pair on the captured envelope. Before this accessor, observers
    /// reading [`crate::ConfigStore::last_reload_error`] either read the
    /// two parallel [`Option`] fields and re-paired them inline (a
    /// recurring two-line pattern at every site that wanted both
    /// halves), or read each through one of the four sibling
    /// projection accessors ([`Self::attribution_confidence`],
    /// [`Self::layer_kind`], [`Self::metadata_axis`],
    /// [`Self::coordinates`]) and lost the [`ConfigSource`] half. This
    /// accessor returns the structurally-coherent pair as one read,
    /// surfaced through the same envelope shape that
    /// [`crate::ShikumiError::failing_attribution`] returns on the
    /// live-error side.
    ///
    /// Structurally pins the [`Some`]-iff-attribution invariant: even
    /// if the two public field slots somehow drifted out of agreement
    /// (e.g. a future construction site or a deserialized payload
    /// landed inconsistent halves), this accessor returns [`None`]
    /// unless both slots are populated — the legal subset of the
    /// 2 × 2 = 4 product cells of the (`failing_source.is_some()` ×
    /// `attribution_rule.is_some()`) cube is exactly the diagonal
    /// (both [`Some`], both [`None`]), and the envelope projection
    /// collapses any off-diagonal cell back to [`None`]. The contract
    /// is pinned by `failing_attribution_some_iff_both_halves_populated`.
    ///
    /// Mirrors [`crate::ShikumiError::failing_attribution`] pointwise
    /// on every captured failure: the lossless-capture contract for
    /// the attribution envelope is pinned by
    /// `failing_attribution_agrees_with_underlying_error_pointwise`.
    /// A future field added to [`FailingSourceAttribution`] (e.g. a
    /// per-attribution span, a confidence weight, a captured
    /// `figment::Metadata` slice) propagates through this accessor
    /// once, not through every observation site.
    ///
    /// Composes with [`Self::coordinates`]: both are partial
    /// projections of the same attribution slot, populated under the
    /// same [`Some`]-iff-attribution discipline. The envelope carries
    /// the [`ConfigSource`] alongside the [`AttributionRule`];
    /// [`Self::coordinates`] drops the source and returns the
    /// (axis × layer-kind × confidence) triple for consumers that
    /// only need the rule's coordinates.
    #[must_use]
    pub fn failing_attribution(&self) -> Option<FailingSourceAttribution<'_>> {
        match (&self.failing_source, self.attribution_rule) {
            (Some(source), Some(rule)) => Some(FailingSourceAttribution::new(source, rule)),
            _ => None,
        }
    }

    /// Closed-enum classification of this captured failure's
    /// field-path localization state — the typed tri-state projection
    /// over the [`Self::field_path`] / [`Self::kind`] pair.
    ///
    /// The cross-thread observable form of [`ReloadFailure`] stores
    /// the offending field path as a flat [`Vec<String>`], collapsing
    /// the original [`Option<&[String]>`] tri-state of
    /// [`crate::ShikumiError::field_path`] into bi-state
    /// (empty / non-empty). Observers reading
    /// [`crate::ConfigStore::last_reload_error`] previously had to
    /// consult both [`Self::kind`] (to ask "is this kind even
    /// figment-bearing?" via
    /// [`ShikumiErrorKind::is_figment_bearing`]) and
    /// `Self::field_path.is_empty()` together to recover the original
    /// tri-state; this accessor lifts the recovery into the type
    /// system as a closed [`FieldPathLocalization`] enum.
    ///
    /// Total over the [`ReloadFailure`] surface — every captured
    /// failure has exactly one localization classification, peer to
    /// [`Self::kind`] (which is also total). Pairs with
    /// [`Self::attribution_confidence`] (confidence axis, partial),
    /// [`Self::layer_kind`] (layer-kind axis, partial), and
    /// [`Self::attribution_rule`] (rule axis, partial) to give
    /// observers the full
    /// (kind × localization × layer-kind × rule × confidence)
    /// projection of every captured failure as five typed reads.
    ///
    /// Agrees pointwise with
    /// [`crate::ShikumiError::field_path_localization`] on every
    /// captured failure: the lossless-capture contract for the
    /// localization axis is pinned by
    /// `field_path_localization_agrees_with_underlying_error_pointwise`.
    /// A future variant landing on [`FieldPathLocalization`] forces a
    /// classification at every consumer's exhaustive match, in
    /// lockstep with the partition surfaced on
    /// [`crate::ShikumiError`].
    #[must_use]
    pub fn field_path_localization(&self) -> FieldPathLocalization {
        if self.kind.is_figment_bearing() {
            if self.field_path.is_empty() {
                FieldPathLocalization::FigmentUnlocalized
            } else {
                FieldPathLocalization::Localized
            }
        } else {
            FieldPathLocalization::NotApplicable
        }
    }

    /// The captured offending field path rendered as a single
    /// `.`-joined dotted key — the operator-facing form of
    /// [`Self::field_path`].
    ///
    /// Cross-thread mirror of [`crate::ShikumiError::field_path_dotted`],
    /// routed through the same `dotted_field_path` join so the live
    /// error and the captured envelope name the offending field with
    /// byte-identical strings. Total over the [`ReloadFailure`] surface
    /// (returns `String`, not `Option`): the flat [`Vec<String>`]
    /// representation of [`Self::field_path`] already collapsed the
    /// underlying `None` (non-figment) and `Some("")` (figment-but-
    /// unlocalized) tri-state into one empty observable, so both render
    /// as `""` here — the same collapse the field itself documents. The
    /// distinction is recoverable through [`Self::field_path_localization`].
    ///
    /// Agrees pointwise with the underlying error: for any
    /// [`crate::ShikumiError`] `e`,
    /// `ReloadFailure::from_error(&e).field_path_dotted()` equals
    /// `e.field_path_dotted().unwrap_or_default()` — pinned by
    /// `field_path_dotted_agrees_with_underlying_error_pointwise`.
    /// Lets an observer reading [`crate::ConfigStore::last_reload_error`]
    /// render the offending field without re-joining
    /// `Self::field_path` at the consumer site.
    #[must_use]
    pub fn field_path_dotted(&self) -> String {
        dotted_field_path(&self.field_path)
    }

    /// Coordinate pair over the two orthogonal closed-enum
    /// projections every captured failure carries on the error-path-
    /// fidelity surface — [`Self::kind`] (which variant) and
    /// [`Self::field_path_localization`] (figment-attached or not).
    ///
    /// Total over the [`ReloadFailure`] surface — every captured
    /// failure has exactly one coordinate cell in the 18-cell
    /// product cube [`ErrorLocalizationCoordinates::ALL`], and the
    /// produced cell always satisfies
    /// [`ErrorLocalizationCoordinates::is_realizable`] (pinned by
    /// `error_localization_coordinates_returns_realizable_cell` over
    /// the captured-failure surface).
    ///
    /// Cross-thread mirror of
    /// [`ShikumiError::error_localization_coordinates`]: the
    /// captured envelope's coordinates agree pointwise with the
    /// underlying error's, pinning the lossless-capture contract for
    /// the (kind × localization) coordinate plane on the
    /// cross-thread observable form. Pinned by
    /// `error_localization_coordinates_agrees_with_underlying_error_pointwise`.
    ///
    /// Strict superset of the two sibling accessors
    /// ([`Self::kind`], [`Self::field_path_localization`]): the
    /// coordinate carries both as one `Copy` value, usable in
    /// `match`, `HashMap` keys, structured-log payloads, and
    /// attestation manifests without re-reading the two projections
    /// separately.
    #[must_use]
    pub fn error_localization_coordinates(&self) -> ErrorLocalizationCoordinates {
        ErrorLocalizationCoordinates {
            kind: self.kind(),
            localization: self.field_path_localization(),
        }
    }
}

impl fmt::Display for ReloadFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn fake_figment_error() -> Box<figment::Error> {
        let figment = figment::Figment::new();
        let result: Result<String, figment::Error> = figment.extract();
        Box::new(result.unwrap_err())
    }

    #[test]
    fn from_error_captures_display_message() {
        let err = ShikumiError::Parse("oops".to_owned());
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.message, err.to_string());
        assert!(f.message.contains("oops"));
    }

    #[test]
    fn from_error_captures_sources_for_extract_variant() {
        let chain = vec![
            ConfigSource::Env("APP_".to_owned()),
            ConfigSource::File(PathBuf::from("/etc/app.yaml")),
        ];
        let err = ShikumiError::Extract {
            sources: chain.clone(),
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.sources, chain);
    }

    #[test]
    fn from_error_yields_empty_sources_for_non_extract_variant() {
        let err = ShikumiError::Parse("x".to_owned());
        let f = ReloadFailure::from_error(&err);
        assert!(f.sources.is_empty());
    }

    #[test]
    fn from_error_yields_empty_sources_for_figment_variant() {
        let err = ShikumiError::Figment(fake_figment_error());
        let f = ReloadFailure::from_error(&err);
        assert!(f.sources.is_empty());
    }

    #[test]
    fn display_renders_message() {
        let f = ReloadFailure {
            message: "broken pipe".to_owned(),
            kind: ShikumiErrorKind::Parse,
            sources: vec![],
            field_path: vec![],
            failing_source: None,
            attribution_rule: None,
        };
        assert_eq!(f.to_string(), "broken pipe");
    }

    #[test]
    fn clone_preserves_data() {
        let f = ReloadFailure {
            message: "bad".to_owned(),
            kind: ShikumiErrorKind::Extract,
            sources: vec![ConfigSource::Defaults],
            field_path: vec!["a".to_owned(), "b".to_owned()],
            failing_source: Some(ConfigSource::Defaults),
            attribution_rule: Some(AttributionRule::DefaultsByCodeUniqueness),
        };
        let g = f.clone();
        assert_eq!(g.message, f.message);
        assert_eq!(g.kind, f.kind);
        assert_eq!(g.sources, f.sources);
        assert_eq!(g.field_path, f.field_path);
        assert_eq!(g.failing_source, f.failing_source);
        assert_eq!(g.attribution_rule, f.attribution_rule);
    }

    #[test]
    fn from_error_does_not_consume_source() {
        let err = ShikumiError::Parse("keepable".to_owned());
        let _f = ReloadFailure::from_error(&err);
        // err still usable
        assert!(err.is_parse());
    }

    #[test]
    fn from_error_carries_path_provenance() {
        let path = PathBuf::from("/srv/cfg/app.yaml");
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::File(path.clone())],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.sources.len(), 1);
        assert_eq!(f.sources[0].as_path(), Some(path.as_path()));
    }

    // ---- field_path capture tests ----

    #[test]
    fn from_error_captures_field_path_for_extract_with_localized_field() {
        // Build a figment error that *has* a path attribution.
        let raw = figment::Error::from("typed".to_owned()).with_path("window.size");
        let err = ShikumiError::Extract {
            sources: vec![],
            error: Box::new(raw),
        };
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.field_path, vec!["window".to_owned(), "size".to_owned()]);
    }

    #[test]
    fn from_error_captures_empty_field_path_for_extract_without_localized_field() {
        // Bare figment::Error has no path; capture surfaces an empty Vec,
        // not panic, not None.
        let err = ShikumiError::Extract {
            sources: vec![],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.field_path.is_empty());
    }

    #[test]
    fn from_error_captures_empty_field_path_for_non_figment_variant() {
        let err = ShikumiError::Parse("bad".to_owned());
        let f = ReloadFailure::from_error(&err);
        assert!(
            f.field_path.is_empty(),
            "non-figment errors yield an empty field_path, not a missing one"
        );
    }

    #[test]
    fn from_error_captures_field_path_for_figment_variant() {
        let raw = figment::Error::from("typed".to_owned()).with_path("a.b.c");
        let err = ShikumiError::Figment(Box::new(raw));
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.field_path,
            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
        );
    }

    // ---- failing_source capture tests ----

    #[test]
    fn from_error_captures_failing_source_for_attributed_extract() {
        // Build a real attributed Extract: type mismatch on a file-only
        // value, env layer present but irrelevant to the offending field.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_attr.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_env("RF_ATTR_NOTSET_")
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        let attributed = f
            .failing_source
            .expect("Extract attribution must propagate to ReloadFailure");
        assert!(attributed.is_file());
        assert_eq!(attributed.as_path(), Some(file.as_path()));
    }

    #[test]
    fn from_error_yields_none_failing_source_for_unattributed_extract() {
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(
            f.failing_source.is_none(),
            "no metadata to map → no failing_source"
        );
    }

    #[test]
    fn from_error_yields_none_failing_source_for_non_extract_variants() {
        assert!(
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned()))
                .failing_source
                .is_none()
        );
        assert!(
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error()))
                .failing_source
                .is_none()
        );
    }

    #[test]
    fn from_error_failing_source_owns_clone_independent_of_error_lifetime() {
        // Capture from a borrowed error, then drop the error. The
        // captured failing_source must remain valid (it's an owned
        // ConfigSource clone).
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_owned.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let f = {
            let err = ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err();
            ReloadFailure::from_error(&err)
        };
        let owned = f.failing_source.expect("owned attribution survives drop");
        assert_eq!(owned.as_path(), Some(file.as_path()));
    }

    // ---- attribution_rule capture tests ----

    #[test]
    fn from_error_captures_attribution_rule_for_file_by_source() {
        // Real YAML file extract: figment attaches Source::File, the
        // resolver fires FileBySource. The rule must propagate to the
        // ReloadFailure alongside the source.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_rule.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.attribution_rule, Some(AttributionRule::FileBySource));
        assert!(f.failing_source.is_some());
    }

    #[test]
    fn from_error_attribution_rule_some_iff_failing_source_some() {
        // Invariant: the rule slot is populated exactly when the source
        // slot is. Across every variant.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        // Attributed: both Some.
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("inv.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let attributed = ReloadFailure::from_error(
            &ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err(),
        );
        assert_eq!(
            attributed.failing_source.is_some(),
            attributed.attribution_rule.is_some()
        );
        assert!(attributed.failing_source.is_some());

        // Unattributed Extract: both None.
        let unattr = ReloadFailure::from_error(&ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        });
        assert!(unattr.failing_source.is_none());
        assert!(unattr.attribution_rule.is_none());

        // Non-Extract: both None.
        let parse = ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned()));
        assert!(parse.failing_source.is_none());
        assert!(parse.attribution_rule.is_none());
    }

    #[test]
    fn from_error_attribution_rule_none_for_unattributed_extract() {
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.attribution_rule.is_none());
    }

    // ---- attribution_confidence accessor tests ----

    #[test]
    fn attribution_confidence_exact_for_real_yaml_extract() {
        // Real YAML file extract attributes via FileBySource (Exact);
        // the typed accessor surfaces Exact without callers
        // destructuring the rule.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_conf_exact.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.attribution_confidence(),
            Some(AttributionConfidence::Exact)
        );
    }

    #[test]
    fn attribution_confidence_fallback_for_defaults_only_extract() {
        // A defaults-only extract whose Serialized provider attaches
        // Source::Code dispatches to DefaultsByCodeUniqueness
        // (Fallback). The accessor surfaces Fallback.
        use crate::provider::ProviderChain;
        use serde::Serialize;
        #[derive(Serialize)]
        struct Bad {
            count: String, // typed mismatch when extracted as Cfg::count: u32
        }
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let err = ProviderChain::new()
            .with_defaults(&Bad {
                count: "not_a_number".into(),
            })
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.attribution_rule,
            Some(AttributionRule::DefaultsByCodeUniqueness)
        );
        assert_eq!(
            f.attribution_confidence(),
            Some(AttributionConfidence::Fallback)
        );
    }

    #[test]
    fn attribution_confidence_none_for_unattributed_extract() {
        // No metadata to map → no rule → no confidence. The Some-iff
        // contract holds across the rule and confidence accessors.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.attribution_confidence().is_none());
        assert!(f.attribution_rule.is_none());
    }

    #[test]
    fn attribution_confidence_some_iff_attribution_rule_some() {
        // Invariant: across every constructed ReloadFailure, the
        // confidence accessor is populated exactly when the rule slot
        // is. Pins the strict-superset contract that the accessor is a
        // pure forwarder over `rule.map(AttributionRule::confidence)`.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Extract {
                sources: vec![ConfigSource::Defaults],
                error: fake_figment_error(),
            }),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert_eq!(
                f.attribution_rule.is_some(),
                f.attribution_confidence().is_some()
            );
        }
    }

    #[test]
    fn attribution_confidence_agrees_with_rule_confidence_pointwise() {
        // For every constructible attribution scenario, the accessor
        // result equals attribution_rule.map(AttributionRule::confidence)
        // — pinning the convenience accessor as a pure projection.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            // Build a synthetic ReloadFailure carrying just the rule;
            // the accessor must derive confidence from it directly.
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(f.attribution_confidence(), Some(rule.confidence()));
        }
    }

    // ---- layer_kind accessor tests ----

    #[test]
    fn layer_kind_file_for_real_yaml_extract() {
        // Real YAML file extract attributes via FileBySource → File;
        // the typed accessor surfaces File without callers
        // destructuring the rule or the source.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_kind_file.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.layer_kind(), Some(ConfigSourceKind::File));
    }

    #[test]
    fn layer_kind_defaults_for_defaults_only_extract() {
        // A defaults-only extract whose Serialized provider attaches
        // Source::Code dispatches to DefaultsByCodeUniqueness → Defaults.
        // The accessor surfaces Defaults.
        use crate::provider::ProviderChain;
        use serde::Serialize;
        #[derive(Serialize)]
        struct Bad {
            count: String, // typed mismatch when extracted as Cfg::count: u32
        }
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let err = ProviderChain::new()
            .with_defaults(&Bad {
                count: "not_a_number".into(),
            })
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.attribution_rule,
            Some(AttributionRule::DefaultsByCodeUniqueness)
        );
        assert_eq!(f.layer_kind(), Some(ConfigSourceKind::Defaults));
    }

    #[test]
    fn layer_kind_none_for_unattributed_extract() {
        // No metadata to map → no rule → no layer_kind.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.layer_kind().is_none());
        assert!(f.attribution_rule.is_none());
    }

    #[test]
    fn layer_kind_none_for_non_extract_variants() {
        // Non-figment-bearing variants never carry attribution.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert!(f.layer_kind().is_none());
        }
    }

    #[test]
    fn layer_kind_some_iff_attribution_rule_some() {
        // Invariant: across every constructed ReloadFailure, the
        // layer_kind accessor is populated exactly when the rule slot
        // is. Pins the strict-superset contract that the accessor is
        // a pure forwarder over `rule.map(AttributionRule::layer_kind)`.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Extract {
                sources: vec![ConfigSource::Defaults],
                error: fake_figment_error(),
            }),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert_eq!(f.attribution_rule.is_some(), f.layer_kind().is_some());
        }
    }

    #[test]
    fn layer_kind_agrees_with_rule_layer_kind_pointwise() {
        // For every constructible attribution scenario, the accessor
        // result equals attribution_rule.map(AttributionRule::layer_kind)
        // — pinning the convenience accessor as a pure projection.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            // Build a synthetic ReloadFailure carrying just the rule;
            // the accessor must derive layer_kind from it directly.
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(f.layer_kind(), Some(rule.layer_kind()));
        }
    }

    #[test]
    fn layer_kind_agrees_with_failing_source_kind_when_attributed() {
        // Cross-primitive invariant propagates from FailingSourceAttribution
        // through ReloadFailure: for every attributed reload failure,
        // f.layer_kind() == f.failing_source.as_ref().map(ConfigSource::kind).
        // The two formulations must agree byte-for-byte across every
        // resolver path the rest of this crate exercises.
        use crate::provider::ProviderChain;
        use serde::Serialize;

        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        #[derive(Serialize)]
        struct Bad {
            count: String,
        }

        // FileBySource: figment's YAML provider attaches Source::File.
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_kind_inv.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let f_file = ReloadFailure::from_error(
            &ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err(),
        );
        assert_eq!(
            f_file.layer_kind(),
            f_file.failing_source.as_ref().map(ConfigSource::kind),
        );
        assert_eq!(f_file.layer_kind(), Some(ConfigSourceKind::File));

        // DefaultsByCodeUniqueness: Serialized provider attaches Source::Code.
        let f_def = ReloadFailure::from_error(
            &ProviderChain::new()
                .with_defaults(&Bad {
                    count: "not_a_number".into(),
                })
                .extract::<Cfg>()
                .unwrap_err(),
        );
        assert_eq!(
            f_def.layer_kind(),
            f_def.failing_source.as_ref().map(ConfigSource::kind),
        );
        assert_eq!(f_def.layer_kind(), Some(ConfigSourceKind::Defaults));
    }

    #[test]
    fn layer_kind_orthogonal_to_attribution_confidence() {
        // The layer_kind / attribution_confidence pair are orthogonal
        // projections over the rule space along the
        // (file × env × defaults) and (exact × fallback) axes
        // respectively. Pin the orthogonality by exhibiting at least
        // three distinct (kind, confidence) pairs across constructible
        // ReloadFailure scenarios.
        use std::collections::HashSet;
        let mut pairs: HashSet<(ConfigSourceKind, AttributionConfidence)> = HashSet::new();
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            let kind = f.layer_kind().expect("attributed → kind some");
            let conf = f.attribution_confidence().expect("attributed → conf some");
            pairs.insert((kind, conf));
        }
        assert!(
            pairs.len() >= 3,
            "kind × confidence must span ≥3 cells; got: {pairs:?}"
        );
    }

    // ---- ShikumiErrorKind (`kind` field & accessor) tests ----

    fn one_per_kind() -> [(ShikumiError, ShikumiErrorKind); 6] {
        // Mirrors the `one_per_kind()` table in `error::tests`: one
        // constructed `ShikumiError` per expected `ShikumiErrorKind`.
        // The reload-side test surface uses it to drive the
        // `ReloadFailure::kind` capture across every variant.
        [
            (
                ShikumiError::NotFound {
                    tried: vec![PathBuf::from("/nf")],
                },
                ShikumiErrorKind::NotFound,
            ),
            (ShikumiError::Parse("p".to_owned()), ShikumiErrorKind::Parse),
            (
                ShikumiError::Watch(notify::Error::generic("w")),
                ShikumiErrorKind::Watch,
            ),
            (
                ShikumiError::Io(std::io::Error::other("io")),
                ShikumiErrorKind::Io,
            ),
            (
                ShikumiError::Figment(fake_figment_error()),
                ShikumiErrorKind::Figment,
            ),
            (
                ShikumiError::Extract {
                    sources: vec![],
                    error: fake_figment_error(),
                },
                ShikumiErrorKind::Extract,
            ),
        ]
    }

    #[test]
    fn from_error_captures_kind_for_each_shikumi_error_variant() {
        // Total over the kind partition: every captured ReloadFailure
        // mirrors the underlying ShikumiError's kind, on both the field
        // and the accessor. Pins the typescape contract that
        // ReloadFailure::kind is a pure projection of
        // ShikumiError::kind through ReloadFailure::from_error.
        for (err, expected) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(
                f.kind, expected,
                "field must capture underlying kind for `{err:?}`"
            );
            assert_eq!(
                f.kind(),
                expected,
                "accessor must mirror field for `{err:?}`"
            );
        }
    }

    #[test]
    fn kind_accessor_agrees_with_field_pointwise() {
        // The accessor and the public field must agree on every captured
        // ReloadFailure — one is a pure forwarder of the other.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(f.kind(), f.kind);
        }
    }

    #[test]
    fn kind_agrees_with_underlying_error_kind_pointwise() {
        // f.kind() == err.kind() across every variant. The reload-side
        // capture is a strict projection of the error-side kind.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(f.kind(), err.kind(), "kind capture must mirror error");
        }
    }

    #[test]
    fn kind_is_total_no_option_at_capture_site() {
        // Distinct from the attribution_* accessors (which return
        // Option<_>), kind is total: every captured ReloadFailure has
        // exactly one kind, regardless of attribution. Pin the totality
        // by exercising every variant — including non-Extract ones,
        // where attribution_rule / failing_source / layer_kind /
        // attribution_confidence all return None — and asserting
        // `f.kind()` is well-defined regardless.
        for (err, expected) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            // Sanity: non-Extract variants have no attribution.
            if expected != ShikumiErrorKind::Extract {
                assert!(f.attribution_rule.is_none());
                assert!(f.failing_source.is_none());
                assert!(f.layer_kind().is_none());
                assert!(f.attribution_confidence().is_none());
            }
            // Yet kind() always answers.
            assert_eq!(f.kind(), expected);
        }
    }

    #[test]
    fn kind_partitions_every_captured_reload_failure() {
        // The kind axis partitions the captured-failure surface into
        // six disjoint cells. Pin disjointness: across the table, each
        // kind appears exactly once, and six distinct kinds populate
        // six distinct hash buckets.
        use std::collections::HashSet;
        let mut seen: HashSet<ShikumiErrorKind> = HashSet::new();
        for (err, expected) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert!(seen.insert(f.kind()), "kind `{expected:?}` not unique");
        }
        assert_eq!(seen.len(), 6, "kind partition must cover six cells");
    }

    #[test]
    fn kind_extract_propagates_through_real_provider_chain() {
        // End-to-end through a real ProviderChain extract failure: the
        // captured kind is Extract, regardless of whether attribution
        // resolves. Pins the contract that the capture path
        // (ProviderChain::extract → ShikumiError::Extract →
        // ReloadFailure::from_error → ReloadFailure::kind) preserves
        // the kind axis.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_kind_extract.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.kind(), ShikumiErrorKind::Extract);
        // And attribution still resolves alongside.
        assert!(f.attribution_rule.is_some());
    }

    #[test]
    fn kind_orthogonal_to_attribution_rule() {
        // The kind axis spans more cells than the attribution axis:
        // five of the six kinds carry no attribution_rule. Pin
        // orthogonality by exhibiting (kind, attribution_rule.is_some())
        // pairs that span ≥2 cells.
        use std::collections::HashSet;
        let mut pairs: HashSet<(ShikumiErrorKind, bool)> = HashSet::new();
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            pairs.insert((f.kind(), f.attribution_rule.is_some()));
        }
        // Across the table: at least the (Extract, false) cell (no
        // attribution captured because the fake figment error has no
        // metadata.source) and one (X, false) cell for non-Extract
        // variants must appear, demonstrating the kind axis is
        // not a redundant projection of the attribution axis.
        assert!(
            pairs.len() >= 2,
            "kind × attribution-presence must span ≥2 cells; got: {pairs:?}"
        );
    }

    #[test]
    fn kind_survives_clone_independent_of_originating_error() {
        // The captured kind is owned (Copy) — it must survive cloning
        // and outlive the originating ShikumiError, parallel to the
        // already-pinned `failing_source_owns_clone` invariant.
        let f = {
            let err = ShikumiError::Parse("ephemeral".to_owned());
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        assert_eq!(g.kind(), ShikumiErrorKind::Parse);
        assert_eq!(g.kind(), f.kind());
    }

    // ---- FieldPathLocalization tests ----

    #[test]
    fn field_path_localization_localized_for_real_yaml_extract() {
        // Real YAML file extract failure with figment-localized field:
        // Localized.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_loc.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.field_path_localization(),
            FieldPathLocalization::Localized
        );
        // And the field_path slot carries the localized segments.
        assert!(!f.field_path.is_empty());
    }

    #[test]
    fn field_path_localization_unlocalized_for_extract_without_field() {
        // Bare Figment::new() extraction failure wrapped in Extract:
        // figment attached no path. FigmentUnlocalized.
        let err = ShikumiError::Extract {
            sources: vec![],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.field_path_localization(),
            FieldPathLocalization::FigmentUnlocalized
        );
        assert!(f.field_path.is_empty());
    }

    #[test]
    fn field_path_localization_unlocalized_for_figment_without_field() {
        // Bare Figment variant: figment-bearing, no localized field.
        let err = ShikumiError::Figment(fake_figment_error());
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.field_path_localization(),
            FieldPathLocalization::FigmentUnlocalized
        );
    }

    #[test]
    fn field_path_localization_not_applicable_for_non_figment_variants() {
        // Parse / NotFound / Watch / Io: NotApplicable. The captured
        // empty Vec<String> on field_path must not be confused with
        // "figment couldn't localize"; the typed accessor restores
        // the distinction.
        for err in [
            ShikumiError::Parse("x".to_owned()),
            ShikumiError::NotFound {
                tried: vec![PathBuf::from("/a")],
            },
            ShikumiError::Watch(notify::Error::generic("w")),
            ShikumiError::Io(std::io::Error::other("io")),
        ] {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(
                f.field_path_localization(),
                FieldPathLocalization::NotApplicable,
                "non-figment variant must capture as NotApplicable: {err:?}"
            );
            // Sanity: the Vec is empty for these too.
            assert!(f.field_path.is_empty());
        }
    }

    #[test]
    fn field_path_localization_agrees_with_underlying_error_pointwise() {
        // Lossless-capture contract: the captured envelope's projection
        // mirrors the source error's projection byte-for-byte, across
        // every variant. The tri-state distinction lost in the Vec<String>
        // representation is recovered by the typed accessor on both
        // sides — they must agree.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(
                f.field_path_localization(),
                err.field_path_localization(),
                "captured localization must mirror source localization for {err:?}"
            );
        }
    }

    #[test]
    fn field_path_dotted_agrees_with_underlying_error_pointwise() {
        // Lossless-capture contract for the dotted rendering: the
        // captured envelope's dotted field path equals the source
        // error's, modulo the documented None -> "" collapse the
        // Vec<String> representation imposes. Both sides route through
        // the same `dotted_field_path` join, so they cannot drift.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(
                f.field_path_dotted(),
                err.field_path_dotted().unwrap_or_default(),
                "captured dotted path must mirror source for {err:?}"
            );
        }
    }

    #[test]
    fn field_path_dotted_renders_nested_localized_capture() {
        // A real nested-key extraction failure captures into a dotted
        // observable an operator can read directly off
        // last_reload_error, without re-joining field_path.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Inner {
            #[allow(dead_code)]
            padding: u32,
        }
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            options: Inner,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_dotted_nested.yaml");
        std::fs::write(&file, "options:\n  padding: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.field_path_dotted(), "options.padding");
        assert_eq!(f.field_path_dotted(), err.field_path_dotted().unwrap());
    }

    #[test]
    fn field_path_dotted_empty_for_non_figment_capture() {
        let err = ShikumiError::Parse("x".to_owned());
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.field_path_dotted(), "");
        assert!(err.field_path_dotted().is_none());
    }

    #[test]
    fn field_path_localization_partitions_every_captured_failure() {
        // The localization axis partitions the captured-failure surface
        // into exactly the three FieldPathLocalization cells. Across
        // the standard one_per_kind() table, every captured failure
        // must classify into exactly one cell, and the table must
        // populate at least two distinct cells (the table doesn't
        // include a Localized example, but does cover NotApplicable
        // and FigmentUnlocalized).
        use std::collections::HashSet;
        let mut seen: HashSet<FieldPathLocalization> = HashSet::new();
        for (err, _) in one_per_kind() {
            seen.insert(ReloadFailure::from_error(&err).field_path_localization());
        }
        assert!(
            seen.len() >= 2,
            "one_per_kind table must span ≥2 localization cells; got: {seen:?}"
        );
        // Specifically: NotApplicable for the four non-figment kinds,
        // FigmentUnlocalized for Extract / Figment (the table builds
        // them without a path).
        assert!(seen.contains(&FieldPathLocalization::NotApplicable));
        assert!(seen.contains(&FieldPathLocalization::FigmentUnlocalized));
    }

    #[test]
    fn field_path_localization_localized_iff_field_path_non_empty() {
        // Cross-axis invariant on the captured envelope: Localized
        // exactly when field_path is non-empty. Pins the contract that
        // the typed projection and the raw Vec<String> agree on the
        // localized boundary.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(
                f.field_path_localization() == FieldPathLocalization::Localized,
                !f.field_path.is_empty(),
                "Localized iff field_path non-empty for {err:?}"
            );
        }
        // And for a constructed Localized capture (real YAML extract):
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_loc_iff.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.field_path_localization() == FieldPathLocalization::Localized,
            !f.field_path.is_empty(),
        );
        assert!(!f.field_path.is_empty());
    }

    #[test]
    fn field_path_localization_total_across_kind_axis() {
        // Distinct from the attribution_* accessors (which return
        // Option<_>), field_path_localization is total: every captured
        // ReloadFailure has exactly one localization classification,
        // regardless of attribution. Mirror of the kind-axis totality
        // pinned by `kind_is_total_no_option_at_capture_site`.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            // Always answers; the assignment is exhaustive.
            let _ = f.field_path_localization();
        }
    }

    #[test]
    fn field_path_localization_survives_clone_independent_of_originating_error() {
        // The captured localization is derived from owned slots
        // (kind: Copy + field_path: Vec<String> Clone) — it must survive
        // cloning and outlive the originating ShikumiError, parallel to
        // the already-pinned kind-clone and failing-source-owns-clone
        // invariants.
        let f = {
            let err = ShikumiError::Parse("ephemeral".to_owned());
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        assert_eq!(
            g.field_path_localization(),
            FieldPathLocalization::NotApplicable
        );
        assert_eq!(g.field_path_localization(), f.field_path_localization());
    }

    #[test]
    fn field_path_localization_orthogonal_to_kind_axis() {
        // Across the constructible captured-failure surface, the
        // (kind × localization) projection must span more than two
        // cells: the partition is finer than either axis alone. The
        // one_per_kind() table covers six (kind, localization) pairs,
        // mostly (Non-figment kind, NotApplicable) and the two
        // figment-bearing kinds with FigmentUnlocalized; adding a
        // Localized capture forces a third cell along the localization
        // axis.
        use crate::provider::ProviderChain;
        use std::collections::HashSet;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let mut pairs: HashSet<(ShikumiErrorKind, FieldPathLocalization)> = HashSet::new();
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            pairs.insert((f.kind(), f.field_path_localization()));
        }
        // Add a Localized capture to expand the cell count.
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_orth.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        pairs.insert((f.kind(), f.field_path_localization()));
        // Now: at least the four (non-figment kind, NotApplicable)
        // cells, the (Extract, FigmentUnlocalized), (Figment,
        // FigmentUnlocalized), and (Extract, Localized) cells —
        // ≥ 7 distinct cells across two axes that span 6 × 3 = 18.
        assert!(
            pairs.len() >= 5,
            "kind × localization must span ≥5 cells; got: {pairs:?}"
        );
    }

    // ---- AttributionAxis (`metadata_axis` accessor) tests ----

    #[test]
    fn metadata_axis_metadata_source_for_real_yaml_extract() {
        // Real YAML file extract attributes via FileBySource — the
        // resolver dispatched off `metadata.source` (figment's typed
        // Source::File classification). The accessor surfaces
        // MetadataSource without callers destructuring the rule.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_axis_src.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.metadata_axis(), Some(AttributionAxis::MetadataSource));
        assert_eq!(f.attribution_rule, Some(AttributionRule::FileBySource));
    }

    #[test]
    fn metadata_axis_metadata_source_for_defaults_only_extract() {
        // Defaults-only Serialized extract dispatches via
        // DefaultsByCodeUniqueness — the resolver inspected
        // `metadata.source` (figment's typed Source::Code). The
        // accessor surfaces MetadataSource even though the
        // confidence is Fallback — pins independence of the axis and
        // confidence partitions on the captured envelope.
        use crate::provider::ProviderChain;
        use serde::Serialize;
        #[derive(Serialize)]
        struct Bad {
            count: String,
        }
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let err = ProviderChain::new()
            .with_defaults(&Bad {
                count: "not_a_number".into(),
            })
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.attribution_rule,
            Some(AttributionRule::DefaultsByCodeUniqueness)
        );
        assert_eq!(f.metadata_axis(), Some(AttributionAxis::MetadataSource));
        assert_eq!(
            f.attribution_confidence(),
            Some(AttributionConfidence::Fallback)
        );
    }

    #[test]
    fn metadata_axis_none_for_unattributed_extract() {
        // No metadata to map → no rule → no metadata_axis. Pins the
        // Some-iff-attribution-rule contract on the third axis.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.metadata_axis().is_none());
        assert!(f.attribution_rule.is_none());
    }

    #[test]
    fn metadata_axis_none_for_non_extract_variants() {
        // Non-figment-bearing variants and the bare Figment variant
        // never carry attribution; the accessor must report None
        // across them all.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
            ReloadFailure::from_error(&ShikumiError::NotFound {
                tried: vec![PathBuf::from("/a")],
            }),
            ReloadFailure::from_error(&ShikumiError::Watch(notify::Error::generic("w"))),
            ReloadFailure::from_error(&ShikumiError::Io(std::io::Error::other("io"))),
        ] {
            assert!(f.metadata_axis().is_none());
        }
    }

    #[test]
    fn metadata_axis_some_iff_attribution_rule_some() {
        // Invariant: across every constructed ReloadFailure, the
        // metadata_axis accessor is populated exactly when the rule
        // slot is. Pins the strict-superset contract that the
        // accessor is a pure forwarder over
        // `rule.map(AttributionRule::metadata_axis)`.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Extract {
                sources: vec![ConfigSource::Defaults],
                error: fake_figment_error(),
            }),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert_eq!(f.attribution_rule.is_some(), f.metadata_axis().is_some());
        }
    }

    #[test]
    fn metadata_axis_agrees_with_rule_metadata_axis_pointwise() {
        // For every constructible attribution scenario, the accessor
        // result equals attribution_rule.map(AttributionRule::metadata_axis)
        // — pinning the convenience accessor as a pure projection of
        // the captured rule.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            // Build a synthetic ReloadFailure carrying just the rule;
            // the accessor must derive metadata_axis from it directly.
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(f.metadata_axis(), Some(rule.metadata_axis()));
        }
    }

    #[test]
    fn metadata_axis_orthogonal_to_attribution_confidence() {
        // The metadata_axis × attribution_confidence pair are
        // orthogonal projections over the rule space along the
        // (source × name) and (exact × fallback) axes respectively.
        // Pin orthogonality by exhibiting all four (axis, confidence)
        // cells across constructible ReloadFailure scenarios.
        use std::collections::HashSet;
        let mut pairs: HashSet<(AttributionAxis, AttributionConfidence)> = HashSet::new();
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            let axis = f.metadata_axis().expect("attributed → axis some");
            let conf = f.attribution_confidence().expect("attributed → conf some");
            pairs.insert((axis, conf));
        }
        assert_eq!(
            pairs.len(),
            4,
            "axis × confidence must span all four cells; got: {pairs:?}"
        );
    }

    #[test]
    fn metadata_axis_orthogonal_to_layer_kind() {
        // The metadata_axis × layer_kind pair must span ≥3 cells —
        // pinning that the axis partition is finer than (or
        // orthogonal to) the layer-kind partition on the captured
        // envelope.
        use std::collections::HashSet;
        let mut pairs: HashSet<(AttributionAxis, ConfigSourceKind)> = HashSet::new();
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            let axis = f.metadata_axis().expect("attributed → axis some");
            let kind = f.layer_kind().expect("attributed → kind some");
            pairs.insert((axis, kind));
        }
        assert!(
            pairs.len() >= 3,
            "axis × layer_kind must span ≥3 cells; got: {pairs:?}"
        );
    }

    // ---- figment_source_kind accessor tests ----

    #[test]
    fn figment_source_kind_some_for_real_yaml_extract() {
        // A real YAML-file extract failure attributes via FileBySource,
        // whose identity already pins FigmentSourceKind::File.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_fsk.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.attribution_rule, Some(AttributionRule::FileBySource));
        assert_eq!(f.figment_source_kind(), Some(FigmentSourceKind::File));
    }

    #[test]
    fn figment_source_kind_some_for_defaults_only_extract() {
        // A defaults-only extract attributes via DefaultsByCodeUniqueness,
        // whose identity already pins FigmentSourceKind::Code.
        use crate::provider::ProviderChain;
        use serde::Serialize;
        #[derive(Serialize)]
        struct Bad {
            count: String,
        }
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let err = ProviderChain::new()
            .with_defaults(&Bad {
                count: "not_a_number".into(),
            })
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.attribution_rule,
            Some(AttributionRule::DefaultsByCodeUniqueness),
        );
        assert_eq!(f.figment_source_kind(), Some(FigmentSourceKind::Code));
    }

    #[test]
    fn figment_source_kind_none_for_unattributed_extract() {
        // No metadata to map → no rule → no figment_source_kind.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.attribution_rule.is_none());
        assert!(f.figment_source_kind().is_none());
    }

    #[test]
    fn figment_source_kind_none_for_non_extract_variants() {
        // Non-figment-bearing variants and bare Figment never carry
        // attribution → never carry a figment_source_kind.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert!(f.figment_source_kind().is_none());
        }
    }

    #[test]
    fn figment_source_kind_none_for_name_axis_attribution() {
        // Name-axis attributions (FileByMetadataName, EnvByPrefix,
        // EnvByUniqueness) carry an attribution_rule but their
        // identity does not pin a figment-Source-axis cell — the
        // accessor returns None even when the rule slot is Some.
        // Pins the two-stage None discipline documented on the
        // accessor.
        for rule in [
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert!(f.attribution_rule.is_some(), "rule {rule:?}");
            assert!(
                f.figment_source_kind().is_none(),
                "rule {rule:?}: name-axis attribution must yield None figment_source_kind",
            );
        }
    }

    #[test]
    fn figment_source_kind_agrees_with_rule_figment_source_kind_pointwise() {
        // For every constructible rule scenario, the accessor result
        // equals attribution_rule.and_then(AttributionRule::figment_source_kind)
        // — pinning the convenience accessor as a pure projection.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(f.figment_source_kind(), rule.figment_source_kind());
        }
    }

    #[test]
    fn figment_source_kind_some_iff_metadata_axis_metadata_source() {
        // Composition law on the cross-thread envelope: when an
        // attribution is recorded, figment_source_kind is Some
        // exactly when metadata_axis is Some(MetadataSource). When no
        // attribution is recorded, both are None and the
        // biconditional still holds vacuously. Pins the same
        // refinement as the AttributionRule-side law, surfaced
        // through the captured envelope.
        let scenarios: Vec<ReloadFailure> = AttributionRule::ALL
            .iter()
            .copied()
            .map(|rule| ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            })
            .chain(std::iter::once(ReloadFailure::from_error(
                &ShikumiError::Parse("x".to_owned()),
            )))
            .collect();
        for f in scenarios {
            assert_eq!(
                f.figment_source_kind().is_some(),
                f.metadata_axis() == Some(AttributionAxis::MetadataSource),
                "envelope {:?}: figment_source_kind.is_some() must equal \
                 (metadata_axis == Some(MetadataSource))",
                f.attribution_rule,
            );
        }
    }

    #[test]
    fn figment_source_kind_agrees_with_layer_kind_pointwise_when_some() {
        // Structural diagonal on the cross-thread envelope: when
        // figment_source_kind is Some, the (figment-source-kind,
        // layer-kind) pair lies on the structural diagonal pinned by
        // the resolver — (File, File) for FileBySource, (Code,
        // Defaults) for DefaultsByCodeUniqueness. The two source-axis
        // rules' identities already name both halves of their joint
        // (figment-source × shikumi-layer) coordinate cell; the
        // accessor surfaces both halves coherently.
        let cases = [
            (
                AttributionRule::FileBySource,
                FigmentSourceKind::File,
                ConfigSourceKind::File,
            ),
            (
                AttributionRule::DefaultsByCodeUniqueness,
                FigmentSourceKind::Code,
                ConfigSourceKind::Defaults,
            ),
        ];
        for (rule, fk, ck) in cases {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(f.figment_source_kind(), Some(fk), "rule {rule:?}");
            assert_eq!(f.layer_kind(), Some(ck), "rule {rule:?}");
        }
    }

    #[test]
    fn figment_source_kind_survives_clone_independent_of_originating_error() {
        // The captured figment_source_kind is derived from the
        // captured rule (Copy) — it must survive cloning and outlive
        // the originating ShikumiError, parallel to the
        // metadata-axis-clone and layer-kind-clone invariants
        // already pinned on the cross-thread envelope.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let f = {
            let dir = tempfile::TempDir::new().unwrap();
            let file = dir.path().join("rf_fsk_clone.yaml");
            std::fs::write(&file, "count: not_a_number\n").unwrap();
            let err = ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err();
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        assert_eq!(g.figment_source_kind(), Some(FigmentSourceKind::File));
        assert_eq!(g.figment_source_kind(), f.figment_source_kind());
    }

    // ---- figment_name_tag_kind accessor tests ----
    //
    // The symmetric peer of the figment_source_kind suite on the
    // cross-thread observable form. Together the two accessors close
    // the figment-metadata kind universe on `ReloadFailure`: every
    // attributed envelope surfaces exactly one figment-metadata-kind
    // cell (Some on either source-axis or name-axis); unattributed
    // envelopes surface None on both.

    fn synthetic_failure_with_rule(rule: AttributionRule) -> ReloadFailure {
        ReloadFailure {
            message: "synth".to_owned(),
            kind: ShikumiErrorKind::Extract,
            sources: vec![],
            field_path: vec![],
            failing_source: Some(ConfigSource::Defaults),
            attribution_rule: Some(rule),
        }
    }

    #[test]
    fn figment_name_tag_kind_some_for_file_by_metadata_name_rule() {
        // FileByMetadataName fires when the resolver matched the
        // shikumi-built provider's "<format>: <path>" name-axis shape;
        // the rule's identity already pins FigmentNameTagKind::Format.
        let f = synthetic_failure_with_rule(AttributionRule::FileByMetadataName);
        assert_eq!(f.figment_name_tag_kind(), Some(FigmentNameTagKind::Format),);
    }

    #[test]
    fn figment_name_tag_kind_some_for_env_by_prefix_rule() {
        // EnvByPrefix fires when figment's "`PREFIX` environment
        // variable(s)" name-axis shape matched a chain env layer's
        // prefix; the rule's identity already pins FigmentNameTagKind::Env.
        let f = synthetic_failure_with_rule(AttributionRule::EnvByPrefix);
        assert_eq!(f.figment_name_tag_kind(), Some(FigmentNameTagKind::Env));
    }

    #[test]
    fn figment_name_tag_kind_some_for_env_by_uniqueness_rule() {
        // EnvByUniqueness fires on an env-shaped name (prefixed without
        // chain match, or bare) when the chain holds a unique Env layer;
        // the rule's identity pins FigmentNameTagKind::Env.
        let f = synthetic_failure_with_rule(AttributionRule::EnvByUniqueness);
        assert_eq!(f.figment_name_tag_kind(), Some(FigmentNameTagKind::Env));
    }

    #[test]
    fn figment_name_tag_kind_none_for_unattributed_extract() {
        // No metadata to map → no rule → no figment_name_tag_kind.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.attribution_rule.is_none());
        assert!(f.figment_name_tag_kind().is_none());
    }

    #[test]
    fn figment_name_tag_kind_none_for_non_extract_variants() {
        // Non-figment-bearing variants and bare Figment never carry
        // attribution → never carry a figment_name_tag_kind.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert!(f.figment_name_tag_kind().is_none());
        }
    }

    #[test]
    fn figment_name_tag_kind_none_for_source_axis_attribution() {
        // Source-axis attributions (FileBySource, DefaultsByCodeUniqueness)
        // carry an attribution_rule but their identity does not pin a
        // figment-name-axis cell — the accessor returns None even when
        // the rule slot is Some. The dual of
        // `figment_source_kind_none_for_name_axis_attribution`.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = synthetic_failure_with_rule(rule);
            assert!(f.attribution_rule.is_some(), "rule {rule:?}");
            assert!(
                f.figment_name_tag_kind().is_none(),
                "rule {rule:?}: source-axis attribution must yield None figment_name_tag_kind",
            );
        }
    }

    #[test]
    fn figment_name_tag_kind_agrees_with_rule_figment_name_tag_kind_pointwise() {
        // For every constructible rule scenario, the cross-thread
        // accessor result equals
        // attribution_rule.and_then(AttributionRule::figment_name_tag_kind)
        // — pinning the convenience accessor as a pure projection. Peer
        // to `figment_source_kind_agrees_with_rule_figment_source_kind_pointwise`
        // on the name-axis.
        for rule in AttributionRule::ALL.iter().copied() {
            let f = synthetic_failure_with_rule(rule);
            assert_eq!(f.figment_name_tag_kind(), rule.figment_name_tag_kind());
        }
    }

    #[test]
    fn figment_name_tag_kind_some_iff_metadata_axis_metadata_name() {
        // Composition law on the cross-thread envelope: when an
        // attribution is recorded, figment_name_tag_kind is Some
        // exactly when metadata_axis is Some(MetadataName). When no
        // attribution is recorded, both are None and the biconditional
        // still holds vacuously. Pins the same refinement as the
        // AttributionRule-side law, surfaced through the captured
        // envelope. Dual of
        // `figment_source_kind_some_iff_metadata_axis_metadata_source`.
        let scenarios: Vec<ReloadFailure> = AttributionRule::ALL
            .iter()
            .copied()
            .map(synthetic_failure_with_rule)
            .chain(std::iter::once(ReloadFailure::from_error(
                &ShikumiError::Parse("x".to_owned()),
            )))
            .collect();
        for f in scenarios {
            assert_eq!(
                f.figment_name_tag_kind().is_some(),
                f.metadata_axis() == Some(AttributionAxis::MetadataName),
                "envelope {:?}: figment_name_tag_kind.is_some() must equal \
                 (metadata_axis == Some(MetadataName))",
                f.attribution_rule,
            );
        }
    }

    #[test]
    fn figment_name_tag_kind_xor_figment_source_kind_on_attributed_envelopes() {
        // Cross-axis partition law on the cross-thread envelope: every
        // attributed failure carries exactly one of figment_source_kind
        // / figment_name_tag_kind as Some (rule identity dispatches on
        // exactly one figment-metadata axis); unattributed failures
        // carry both as None. Closes the figment-metadata kind universe
        // on the ReloadFailure surface — the same partition the
        // AttributionRule side pins via
        // `attribution_rule_figment_name_tag_kind_xor_figment_source_kind`,
        // surfaced through the captured envelope.
        for rule in AttributionRule::ALL.iter().copied() {
            let f = synthetic_failure_with_rule(rule);
            let src_some = f.figment_source_kind().is_some();
            let name_some = f.figment_name_tag_kind().is_some();
            assert!(
                src_some ^ name_some,
                "attributed envelope for rule {rule:?}: exactly one of \
                 figment_source_kind / figment_name_tag_kind must be Some \
                 (got src_some={src_some}, name_some={name_some})",
            );
        }
        // Unattributed envelope: both halves None.
        let f = ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned()));
        assert!(f.figment_source_kind().is_none());
        assert!(f.figment_name_tag_kind().is_none());
    }

    #[test]
    fn figment_name_tag_kind_agrees_with_underlying_error_pointwise() {
        // End-to-end lossless-capture: a real Extract error attributing
        // via EnvByPrefix (synthesized through
        // `synthetic_error_with_metadata_name`) produces a captured
        // envelope whose figment_name_tag_kind projection equals the
        // underlying error's failing_attribution()'s
        // figment_name_tag_kind. Peer to
        // `file_provenance_agrees_with_underlying_error_pointwise` on the
        // file-provenance axis, but pinning the agreement law across the
        // error → envelope boundary on the figment-name-tag-kind axis.
        // Uses a synthetic env-prefixed metadata name (the same shape
        // shikumi's tests for EnvByPrefix use in error::tests) so the
        // resolver attributes via EnvByPrefix without needing a live
        // figment::providers::Env in the test process.
        let mut e = figment::Error::from("synth".to_owned());
        e.metadata = Some(figment::Metadata::named("`MAXIS_` environment variable(s)"));
        let err = ShikumiError::Extract {
            sources: vec![
                ConfigSource::Defaults,
                ConfigSource::Env("MAXIS_".to_owned()),
            ],
            error: Box::new(e),
        };
        let f = ReloadFailure::from_error(&err);
        let underlying = err
            .failing_attribution()
            .and_then(FailingSourceAttribution::figment_name_tag_kind);
        assert_eq!(f.figment_name_tag_kind(), underlying);
        assert_eq!(
            f.figment_name_tag_kind(),
            Some(FigmentNameTagKind::Env),
            "env-prefixed extract attributes via EnvByPrefix → FigmentNameTagKind::Env",
        );
    }

    #[test]
    fn figment_name_tag_kind_survives_clone_independent_of_originating_error() {
        // The captured figment_name_tag_kind is derived from the
        // captured rule (Copy) — it must survive cloning and outlive
        // the originating ShikumiError, parallel to the
        // figment_source_kind / metadata_axis / layer_kind clone-survival
        // invariants already pinned on the cross-thread envelope.
        let f = {
            let mut e = figment::Error::from("synth".to_owned());
            e.metadata = Some(figment::Metadata::named(
                "`CLONED_` environment variable(s)",
            ));
            let err = ShikumiError::Extract {
                sources: vec![
                    ConfigSource::Defaults,
                    ConfigSource::Env("CLONED_".to_owned()),
                ],
                error: Box::new(e),
            };
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        assert_eq!(g.figment_name_tag_kind(), Some(FigmentNameTagKind::Env));
        assert_eq!(g.figment_name_tag_kind(), f.figment_name_tag_kind());
    }

    #[test]
    fn file_provenance_agrees_with_rule_file_provenance_pointwise() {
        // For every constructible rule scenario, the cross-thread
        // accessor result equals
        // attribution_rule.and_then(AttributionRule::file_provenance) —
        // pinning the convenience accessor as a pure projection over
        // the captured rule slot. Peer to
        // `figment_source_kind_agrees_with_rule_figment_source_kind_pointwise`
        // on the file-provenance axis.
        for rule in AttributionRule::ALL.iter().copied() {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(f.file_provenance(), rule.file_provenance());
        }
    }

    #[test]
    fn file_provenance_some_iff_layer_kind_file() {
        // Composition law on the cross-thread envelope: when an
        // attribution is recorded, file_provenance is Some exactly
        // when layer_kind is Some(File). When no attribution is
        // recorded, both are None and the biconditional still holds
        // vacuously. Pins the same refinement as the AttributionRule-
        // side `attribution_rule_file_provenance_some_iff_file_layer_kind`
        // biconditional, surfaced through the captured envelope.
        let scenarios: Vec<ReloadFailure> = AttributionRule::ALL
            .iter()
            .copied()
            .map(|rule| ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            })
            .chain(std::iter::once(ReloadFailure::from_error(
                &ShikumiError::Parse("x".to_owned()),
            )))
            .collect();
        for f in scenarios {
            assert_eq!(
                f.file_provenance().is_some(),
                f.layer_kind() == Some(ConfigSourceKind::File),
                "envelope {:?}: file_provenance.is_some() must equal \
                 (layer_kind == Some(File))",
                f.attribution_rule,
            );
        }
    }

    #[test]
    fn file_provenance_pins_each_file_rule_on_envelope() {
        // Concrete pin: the two file-axis rules map through the
        // envelope to the two recognized FormatProvenance cells in
        // lockstep with the rule-side projection. Peer to
        // `attribution_rule_file_provenance_pins_each_file_rule`
        // surfaced through the captured envelope.
        let cases = [
            (
                AttributionRule::FileBySource,
                crate::FormatProvenance::FigmentBuiltin,
            ),
            (
                AttributionRule::FileByMetadataName,
                crate::FormatProvenance::ShikumiBuilt,
            ),
        ];
        for (rule, provenance) in cases {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::File(std::path::PathBuf::from("/etc/x"))),
                attribution_rule: Some(rule),
            };
            assert_eq!(f.file_provenance(), Some(provenance), "rule {rule:?}");
        }
    }

    #[test]
    fn file_provenance_agrees_with_underlying_error_pointwise() {
        // End-to-end lossless-capture: a real Extract error attributing
        // via FileBySource produces a captured envelope whose
        // file_provenance projection equals the underlying error's
        // failing_attribution()'s file_provenance. Peer to
        // `figment_source_kind_survives_clone_independent_of_originating_error`
        // but pinning the agreement law across the error → envelope
        // boundary.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_fp_agreement.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        let underlying = err
            .failing_attribution()
            .and_then(FailingSourceAttribution::file_provenance);
        assert_eq!(f.file_provenance(), underlying);
        assert_eq!(
            f.file_provenance(),
            Some(crate::FormatProvenance::FigmentBuiltin),
            "YAML extract failure attributes via FileBySource → FigmentBuiltin",
        );
    }

    #[test]
    fn file_provenance_survives_clone_independent_of_originating_error() {
        // The captured file_provenance is derived from the captured
        // rule (Copy) — it must survive cloning and outlive the
        // originating ShikumiError, parallel to the
        // figment_source_kind / metadata_axis / layer_kind clone
        // invariants already pinned on the cross-thread envelope.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let f = {
            let dir = tempfile::TempDir::new().unwrap();
            let file = dir.path().join("rf_fp_clone.yaml");
            std::fs::write(&file, "count: not_a_number\n").unwrap();
            let err = ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err();
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        assert_eq!(
            g.file_provenance(),
            Some(crate::FormatProvenance::FigmentBuiltin),
        );
        assert_eq!(g.file_provenance(), f.file_provenance());
    }

    #[test]
    fn metadata_axis_survives_clone_independent_of_originating_error() {
        // The captured axis is derived from the captured rule (Copy)
        // — it must survive cloning and outlive the originating
        // ShikumiError, parallel to the kind-clone and
        // failing-source-owns-clone invariants already pinned.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let f = {
            let dir = tempfile::TempDir::new().unwrap();
            let file = dir.path().join("rf_axis_clone.yaml");
            std::fs::write(&file, "count: not_a_number\n").unwrap();
            let err = ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err();
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        assert_eq!(g.metadata_axis(), Some(AttributionAxis::MetadataSource));
        assert_eq!(g.metadata_axis(), f.metadata_axis());
    }

    // ---- coordinates accessor tests ----

    #[test]
    fn coordinates_for_real_yaml_extract_carries_full_triple() {
        // End-to-end: a real YAML-file extract failure surfaces the
        // (MetadataSource, File, Exact) triple in one accessor read.
        // The captured envelope's coordinates() agrees with the three
        // sibling Option-returning projection accessors.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_coords.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        let coords = f.coordinates().expect("attributed → coordinates some");
        assert_eq!(coords.axis, AttributionAxis::MetadataSource);
        assert_eq!(coords.layer_kind, ConfigSourceKind::File);
        assert_eq!(coords.confidence, AttributionConfidence::Exact);
    }

    #[test]
    fn coordinates_some_iff_attribution_rule_some() {
        // Some-iff-attribution invariant: the coordinates accessor is
        // populated exactly when the rule slot is, peer to
        // attribution_confidence / layer_kind / metadata_axis.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Extract {
                sources: vec![ConfigSource::Defaults],
                error: fake_figment_error(),
            }),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert_eq!(f.attribution_rule.is_some(), f.coordinates().is_some());
        }
    }

    #[test]
    fn coordinates_agrees_with_three_projection_accessors_pointwise() {
        // For every recognized rule, the named-struct lift on the
        // ReloadFailure side surfaces the same per-axis values as the
        // three sibling Option-returning forwarders. Pins the
        // contract that the accessor is a pure projection of
        // attribution_rule.map(AttributionRule::coordinates), not a
        // re-derived computation.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            let coords = f.coordinates().expect("attributed → coords some");
            assert_eq!(Some(coords.axis), f.metadata_axis());
            assert_eq!(Some(coords.layer_kind), f.layer_kind());
            assert_eq!(Some(coords.confidence), f.attribution_confidence());
        }
    }

    #[test]
    fn coordinates_round_trips_through_from_coordinates() {
        // The bijection statement on the captured envelope: a captured
        // ReloadFailure's coordinates round-trip back to the originating
        // rule via AttributionRule::from_coordinates. Pins the
        // operational use case — re-hydrating a rule from a captured
        // structured-log payload of three closed-enum coordinates.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            let coords = f.coordinates().expect("coords some");
            assert_eq!(
                AttributionRule::from_coordinates(coords),
                Some(rule),
                "captured coords for {rule:?} must round-trip"
            );
        }
    }

    #[test]
    fn coordinates_survives_clone_independent_of_originating_error() {
        // The captured triple is derived from the captured rule (Copy)
        // — it must survive cloning and outlive the originating
        // ShikumiError, parallel to the metadata_axis / layer_kind /
        // attribution_confidence clone-survival invariants.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let f = {
            let dir = tempfile::TempDir::new().unwrap();
            let file = dir.path().join("rf_coords_clone.yaml");
            std::fs::write(&file, "count: not_a_number\n").unwrap();
            let err = ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err();
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        let expected = AttributionCoordinates {
            axis: AttributionAxis::MetadataSource,
            layer_kind: ConfigSourceKind::File,
            confidence: AttributionConfidence::Exact,
        };
        assert_eq!(g.coordinates(), Some(expected));
        assert_eq!(g.coordinates(), f.coordinates());
    }

    #[test]
    fn coordinates_distinguishes_every_rule_on_synthetic_failures() {
        // Joint injectivity on the captured envelope: distinct rules
        // captured into ReloadFailure produce distinct coordinate
        // triples. Pins the structural-completeness statement on the
        // cross-thread observable surface, peer to the underlying
        // AttributionRule joint-injectivity contract.
        use std::collections::HashSet;
        let mut coords_set: HashSet<AttributionCoordinates> = HashSet::new();
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            coords_set.insert(f.coordinates().expect("coords some"));
        }
        assert_eq!(
            coords_set.len(),
            5,
            "every captured rule must occupy a distinct coordinate cell; got: {coords_set:?}"
        );
    }

    // ---- failing_attribution accessor tests ----

    #[test]
    fn failing_attribution_for_real_yaml_extract_borrows_source_and_rule() {
        // End-to-end: a real YAML-file extract failure surfaces both
        // halves of the attribution as one borrowed envelope read,
        // peer to ShikumiError::failing_attribution on the live-error
        // side. The envelope's source borrows into the captured
        // failing_source slot; the rule is the captured rule.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_attr_envelope.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();

        let f = ReloadFailure::from_error(&err);
        let envelope = f.failing_attribution().expect("attributed → envelope some");
        assert_eq!(envelope.rule, AttributionRule::FileBySource);
        assert_eq!(envelope.source.as_path(), Some(file.as_path()));
    }

    #[test]
    fn failing_attribution_some_iff_both_halves_populated() {
        // The Some-iff-attribution invariant is structural on the
        // accessor: the diagonal (both Some / both None) of the
        // (failing_source × attribution_rule) 2×2 cube produces
        // Some(envelope) / None respectively, and the two off-diagonal
        // cells (only one half populated) collapse back to None.
        // Pins that the envelope projection is the legal subset of the
        // 4-cell product cube, peer to the way coordinates() and the
        // three sibling Option-returning forwarders enforce
        // Some-iff-rule.

        // Both Some: envelope Some.
        let both = ReloadFailure {
            message: "synth".to_owned(),
            kind: ShikumiErrorKind::Extract,
            sources: vec![],
            field_path: vec![],
            failing_source: Some(ConfigSource::Defaults),
            attribution_rule: Some(AttributionRule::DefaultsByCodeUniqueness),
        };
        assert!(both.failing_attribution().is_some());

        // Both None: envelope None.
        let neither = ReloadFailure {
            message: "synth".to_owned(),
            kind: ShikumiErrorKind::Parse,
            sources: vec![],
            field_path: vec![],
            failing_source: None,
            attribution_rule: None,
        };
        assert!(neither.failing_attribution().is_none());

        // Off-diagonal (only source): envelope None — the legal-subset
        // collapse pins the structural invariant even if a future
        // construction site lands inconsistent halves.
        let only_source = ReloadFailure {
            message: "synth".to_owned(),
            kind: ShikumiErrorKind::Extract,
            sources: vec![],
            field_path: vec![],
            failing_source: Some(ConfigSource::Defaults),
            attribution_rule: None,
        };
        assert!(only_source.failing_attribution().is_none());

        // Off-diagonal (only rule): envelope None.
        let only_rule = ReloadFailure {
            message: "synth".to_owned(),
            kind: ShikumiErrorKind::Extract,
            sources: vec![],
            field_path: vec![],
            failing_source: None,
            attribution_rule: Some(AttributionRule::FileBySource),
        };
        assert!(only_rule.failing_attribution().is_none());
    }

    #[test]
    fn failing_attribution_none_for_unattributed_extract() {
        // No metadata to map → no attribution captured → envelope None.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.failing_attribution().is_none());
    }

    #[test]
    fn failing_attribution_none_for_non_extract_variants() {
        // Non-figment-bearing variants and the bare Figment variant
        // never carry attribution; the envelope accessor must report
        // None across them all, peer to the four sibling
        // Option-returning projection accessors.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
            ReloadFailure::from_error(&ShikumiError::NotFound {
                tried: vec![PathBuf::from("/a")],
            }),
            ReloadFailure::from_error(&ShikumiError::Watch(notify::Error::generic("w"))),
            ReloadFailure::from_error(&ShikumiError::Io(std::io::Error::other("io"))),
        ] {
            assert!(f.failing_attribution().is_none());
        }
    }

    #[test]
    fn failing_attribution_envelope_carries_same_halves_as_fields() {
        // For every captured-from real attributed extract, the envelope's
        // (source, rule) pair must equal the parallel (failing_source,
        // attribution_rule) field pair byte-for-byte. Pins the accessor
        // as a pure projection of the two slots, not a re-derived
        // computation.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_attr_parity.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        let envelope = f.failing_attribution().expect("attributed → envelope some");
        assert_eq!(Some(envelope.rule), f.attribution_rule);
        assert_eq!(Some(envelope.source), f.failing_source.as_ref());
    }

    #[test]
    fn failing_attribution_agrees_with_underlying_error_pointwise() {
        // Lossless-capture contract for the attribution envelope: the
        // captured ReloadFailure's failing_attribution() agrees with
        // the originating ShikumiError's failing_attribution() across
        // every variant, modulo the lifetime difference (the live
        // form borrows into the chain, the captured form borrows into
        // the cloned slots). The (source, rule) pair must match
        // byte-for-byte on every recognized rule.
        use crate::provider::ProviderChain;
        use serde::Serialize;

        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        #[derive(Serialize)]
        struct Bad {
            count: String,
        }

        // FileBySource path.
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_attr_pointwise.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err_file = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f_file = ReloadFailure::from_error(&err_file);
        let live = err_file.failing_attribution().expect("live envelope some");
        let captured = f_file
            .failing_attribution()
            .expect("captured envelope some");
        assert_eq!(live.rule, captured.rule);
        assert_eq!(live.source, captured.source);

        // DefaultsByCodeUniqueness path.
        let err_def = ProviderChain::new()
            .with_defaults(&Bad {
                count: "not_a_number".into(),
            })
            .extract::<Cfg>()
            .unwrap_err();
        let f_def = ReloadFailure::from_error(&err_def);
        let live = err_def.failing_attribution().expect("live envelope some");
        let captured = f_def.failing_attribution().expect("captured envelope some");
        assert_eq!(live.rule, captured.rule);
        assert_eq!(live.source, captured.source);

        // Unattributed Extract: both surfaces must agree on None.
        let err_unattr = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f_unattr = ReloadFailure::from_error(&err_unattr);
        assert!(err_unattr.failing_attribution().is_none());
        assert!(f_unattr.failing_attribution().is_none());

        // Non-Extract variants: both surfaces must agree on None.
        for err in [
            ShikumiError::Parse("x".to_owned()),
            ShikumiError::Figment(fake_figment_error()),
        ] {
            let f = ReloadFailure::from_error(&err);
            assert!(err.failing_attribution().is_none());
            assert!(f.failing_attribution().is_none());
        }
    }

    #[test]
    fn failing_attribution_envelope_coordinates_match_separate_accessor() {
        // The envelope's coordinates() must equal the captured
        // failure's coordinates() on every attributed scenario —
        // pinning that routing through the envelope vs. the bare
        // accessor gives the same triple. Composition contract for
        // the (envelope, coordinates) pair on the captured surface,
        // peer to the (envelope, coordinates) pair on the live-error
        // surface.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            let envelope = f.failing_attribution().expect("attributed → envelope some");
            assert_eq!(Some(envelope.coordinates()), f.coordinates());
            assert_eq!(envelope.confidence(), rule.confidence());
            assert_eq!(envelope.layer_kind(), rule.layer_kind());
            assert_eq!(envelope.metadata_axis(), rule.metadata_axis());
        }
    }

    #[test]
    fn failing_attribution_envelope_outlives_originating_error() {
        // Capture from a borrowed error, drop the error, then borrow
        // the envelope from the surviving ReloadFailure. The envelope
        // borrows into the captured failure's owned ConfigSource clone,
        // so it must remain valid after the originating ShikumiError
        // is dropped — parallel to the failing_source-owns-clone
        // invariant already pinned.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_attr_outlives.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let f = {
            let err = ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err();
            ReloadFailure::from_error(&err)
        };
        let envelope = f.failing_attribution().expect("envelope some after drop");
        assert_eq!(envelope.rule, AttributionRule::FileBySource);
        assert_eq!(envelope.source.as_path(), Some(file.as_path()));
    }

    #[test]
    fn failing_attribution_some_iff_other_attribution_accessors_some() {
        // Cross-accessor invariant on the captured envelope: the new
        // failing_attribution() accessor and the four pre-existing
        // Some-iff-attribution accessors (attribution_confidence /
        // layer_kind / metadata_axis / coordinates) populate exactly
        // together. Pins that the envelope accessor lives on the same
        // diagonal of the attribution-presence cube as its peers, not
        // a refinement or a relaxation.
        use crate::provider::ProviderChain;
        use serde::Serialize;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        #[derive(Serialize)]
        struct Bad {
            count: String,
        }

        // Attributed (FileBySource).
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_attr_diag_file.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let f_file = ReloadFailure::from_error(
            &ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err(),
        );

        // Attributed (DefaultsByCodeUniqueness).
        let f_def = ReloadFailure::from_error(
            &ProviderChain::new()
                .with_defaults(&Bad {
                    count: "not_a_number".into(),
                })
                .extract::<Cfg>()
                .unwrap_err(),
        );

        // Unattributed Extract.
        let f_unattr = ReloadFailure::from_error(&ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        });

        // Non-Extract.
        let f_parse = ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned()));

        for f in [&f_file, &f_def, &f_unattr, &f_parse] {
            let env_some = f.failing_attribution().is_some();
            assert_eq!(env_some, f.attribution_confidence().is_some());
            assert_eq!(env_some, f.layer_kind().is_some());
            assert_eq!(env_some, f.metadata_axis().is_some());
            assert_eq!(env_some, f.coordinates().is_some());
            assert_eq!(env_some, f.attribution_rule.is_some());
            assert_eq!(env_some, f.failing_source.is_some());
        }
    }

    // ---- error_localization_coordinates tests ----

    #[test]
    fn error_localization_coordinates_agrees_with_underlying_error_pointwise() {
        // Lossless-capture contract for the (kind × localization)
        // coordinate plane on the cross-thread observable form: the
        // captured envelope's coordinate cell mirrors the source
        // error's cell byte-for-byte across every variant. Together
        // with `kind_agrees_with_underlying_error_pointwise` and
        // `field_path_localization_agrees_with_underlying_error_pointwise`,
        // this pins agreement on each named slot AND on the
        // collapsed pair, so a future variant landing must keep all
        // three projections in lockstep.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            assert_eq!(
                f.error_localization_coordinates(),
                err.error_localization_coordinates(),
                "captured coordinates must mirror source coordinates for {err:?}"
            );
        }
    }

    #[test]
    fn error_localization_coordinates_returns_realizable_cell() {
        // Every captured failure maps to a realizable cell in the
        // 18-cell product cube. Pins the forward-total /
        // image-realizable contract on the cross-thread observable
        // form: the accessor never produces an unrealizable cell, no
        // matter which underlying variant was captured.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            let cell = f.error_localization_coordinates();
            assert!(
                cell.is_realizable(),
                "captured cell must be realizable (got {cell:?} from {err:?})",
            );
        }
    }

    #[test]
    fn error_localization_coordinates_mirrors_sibling_accessors_on_capture() {
        // The captured coordinate accessor is a thin lift over the
        // two sibling accessors (kind, field_path_localization) on
        // the envelope: the produced cell's named fields must agree
        // byte-for-byte with the two separate reads on the same
        // envelope. Pins the lossless-decomposition contract on the
        // cross-thread observable form.
        for (err, _) in one_per_kind() {
            let f = ReloadFailure::from_error(&err);
            let cell = f.error_localization_coordinates();
            assert_eq!(
                cell.kind,
                f.kind(),
                "captured coordinate.kind must agree with f.kind() for {err:?}",
            );
            assert_eq!(
                cell.localization,
                f.field_path_localization(),
                "captured coordinate.localization must agree with f.field_path_localization() for {err:?}",
            );
        }
    }

    // ---- attribution_source_kind_coordinates accessor tests ----

    #[test]
    fn attribution_source_kind_coordinates_some_for_real_yaml_extract() {
        // A real YAML-file extract failure attributes via FileBySource,
        // whose joint cell is (File, File) — the source-axis rule's
        // identity already pins both halves on the cross-thread
        // observable form.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let dir = tempfile::TempDir::new().unwrap();
        let file = dir.path().join("rf_askc.yaml");
        std::fs::write(&file, "count: not_a_number\n").unwrap();
        let err = ProviderChain::new()
            .with_file(&file)
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(f.attribution_rule, Some(AttributionRule::FileBySource));
        assert_eq!(
            f.attribution_source_kind_coordinates(),
            Some(AttributionSourceKindCoordinates {
                figment_source_kind: FigmentSourceKind::File,
                layer_kind: ConfigSourceKind::File,
            }),
        );
    }

    #[test]
    fn attribution_source_kind_coordinates_some_for_defaults_only_extract() {
        // A defaults-only extract attributes via DefaultsByCodeUniqueness,
        // whose joint cell is (Code, Defaults). Pins the second
        // realizable cell on the cross-thread observable form.
        use crate::provider::ProviderChain;
        use serde::Serialize;
        #[derive(Serialize)]
        struct Bad {
            count: String,
        }
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let err = ProviderChain::new()
            .with_defaults(&Bad {
                count: "not_a_number".into(),
            })
            .extract::<Cfg>()
            .unwrap_err();
        let f = ReloadFailure::from_error(&err);
        assert_eq!(
            f.attribution_rule,
            Some(AttributionRule::DefaultsByCodeUniqueness),
        );
        assert_eq!(
            f.attribution_source_kind_coordinates(),
            Some(AttributionSourceKindCoordinates {
                figment_source_kind: FigmentSourceKind::Code,
                layer_kind: ConfigSourceKind::Defaults,
            }),
        );
    }

    #[test]
    fn attribution_source_kind_coordinates_none_for_unattributed_extract() {
        // No metadata to map → no rule → no joint cell. Pins the
        // first stage of the two-stage None discipline on the
        // cross-thread envelope.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.attribution_rule.is_none());
        assert!(f.attribution_source_kind_coordinates().is_none());
    }

    #[test]
    fn attribution_source_kind_coordinates_none_for_non_extract_variants() {
        // Non-figment-bearing variants and bare Figment never carry
        // attribution → never carry a joint cell.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert!(f.attribution_source_kind_coordinates().is_none());
        }
    }

    #[test]
    fn attribution_source_kind_coordinates_none_for_name_axis_attribution() {
        // Name-axis attributions carry an attribution_rule but their
        // identity does not pin the joint cell — the accessor returns
        // None even when the rule slot is Some. Pins the second-stage
        // None arm of the two-stage discipline on the cross-thread
        // envelope, parallel to
        // `figment_source_kind_none_for_name_axis_attribution`.
        for rule in [
            AttributionRule::FileByMetadataName,
            AttributionRule::EnvByPrefix,
            AttributionRule::EnvByUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert!(f.attribution_rule.is_some(), "rule {rule:?}");
            assert!(
                f.attribution_source_kind_coordinates().is_none(),
                "rule {rule:?}: name-axis attribution must yield None joint cell",
            );
        }
    }

    #[test]
    fn attribution_source_kind_coordinates_agrees_with_rule_pointwise() {
        // For every constructible rule scenario, the accessor result
        // equals
        // attribution_rule.and_then(AttributionRule::attribution_source_kind_coordinates)
        // — pinning the convenience accessor as a pure projection.
        for rule in AttributionRule::ALL.iter().copied() {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(
                f.attribution_source_kind_coordinates(),
                rule.attribution_source_kind_coordinates(),
            );
        }
    }

    #[test]
    fn attribution_source_kind_coordinates_returns_realizable_cell_when_some() {
        // Every Some return from the cross-thread accessor satisfies
        // AttributionSourceKindCoordinates::is_realizable — the
        // captured envelope's projection never produces an
        // unrealizable cell, no matter which rule was captured.
        let scenarios: Vec<ReloadFailure> = AttributionRule::ALL
            .iter()
            .copied()
            .map(|rule| ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            })
            .chain(std::iter::once(ReloadFailure::from_error(
                &ShikumiError::Parse("x".to_owned()),
            )))
            .collect();
        for f in scenarios {
            if let Some(cell) = f.attribution_source_kind_coordinates() {
                assert!(
                    cell.is_realizable(),
                    "envelope {:?}: joint cell {cell:?} must be realizable",
                    f.attribution_rule,
                );
            }
        }
    }

    #[test]
    fn attribution_source_kind_coordinates_agrees_with_paired_projections_pointwise() {
        // Lossless-decomposition contract on the cross-thread
        // envelope: the joint cell's named fields agree byte-for-byte
        // with the paired
        // (figment_source_kind, layer_kind)
        // reads on the same envelope. Holds vacuously when the joint
        // cell is None (the paired projection is also None on its
        // figment_source_kind half).
        let scenarios: Vec<ReloadFailure> = AttributionRule::ALL
            .iter()
            .copied()
            .map(|rule| ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            })
            .chain(std::iter::once(ReloadFailure::from_error(
                &ShikumiError::Parse("x".to_owned()),
            )))
            .collect();
        for f in scenarios {
            let joint = f.attribution_source_kind_coordinates();
            let paired = f.figment_source_kind().map(|figment_source_kind| {
                AttributionSourceKindCoordinates {
                    figment_source_kind,
                    layer_kind: f.layer_kind().expect(
                        "figment_source_kind Some implies layer_kind Some on the cross-thread envelope",
                    ),
                }
            });
            assert_eq!(
                joint, paired,
                "envelope {:?}: joint cell must equal paired projections",
                f.attribution_rule,
            );
        }
    }

    #[test]
    fn attribution_source_kind_coordinates_survives_clone_independent_of_originating_error() {
        // The captured joint cell is derived from the captured rule
        // (Copy) — it must survive cloning and outlive the originating
        // ShikumiError, parallel to the figment_source_kind-clone,
        // metadata-axis-clone, and layer-kind-clone invariants
        // already pinned on the cross-thread envelope.
        use crate::provider::ProviderChain;
        #[derive(serde::Deserialize, Debug)]
        struct Cfg {
            #[allow(dead_code)]
            count: u32,
        }
        let f = {
            let dir = tempfile::TempDir::new().unwrap();
            let file = dir.path().join("rf_askc_clone.yaml");
            std::fs::write(&file, "count: not_a_number\n").unwrap();
            let err = ProviderChain::new()
                .with_file(&file)
                .extract::<Cfg>()
                .unwrap_err();
            ReloadFailure::from_error(&err)
        };
        let g = f.clone();
        assert_eq!(
            g.attribution_source_kind_coordinates(),
            Some(AttributionSourceKindCoordinates {
                figment_source_kind: FigmentSourceKind::File,
                layer_kind: ConfigSourceKind::File,
            }),
        );
        assert_eq!(
            g.attribution_source_kind_coordinates(),
            f.attribution_source_kind_coordinates(),
        );
    }

    // ---- attribution_name_kind_coordinates accessor tests ----

    #[test]
    fn attribution_name_kind_coordinates_none_for_unattributed_extract() {
        // No metadata to map → no rule → no name-axis joint cell. Pins
        // the first stage of the two-stage None discipline on the
        // cross-thread envelope, symmetric peer of
        // `attribution_source_kind_coordinates_none_for_unattributed_extract`.
        let err = ShikumiError::Extract {
            sources: vec![ConfigSource::Defaults],
            error: fake_figment_error(),
        };
        let f = ReloadFailure::from_error(&err);
        assert!(f.attribution_rule.is_none());
        assert!(f.attribution_name_kind_coordinates().is_none());
    }

    #[test]
    fn attribution_name_kind_coordinates_none_for_non_extract_variants() {
        // Non-figment-bearing variants and bare Figment never carry
        // attribution → never carry a name-axis joint cell.
        for f in [
            ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned())),
            ReloadFailure::from_error(&ShikumiError::Figment(fake_figment_error())),
        ] {
            assert!(f.attribution_name_kind_coordinates().is_none());
        }
    }

    #[test]
    fn attribution_name_kind_coordinates_none_for_source_axis_attribution() {
        // Source-axis attributions carry an attribution_rule but their
        // identity does not pin the name-axis joint cell — the
        // accessor returns None even when the rule slot is Some. Pins
        // the second-stage None arm of the two-stage discipline on the
        // cross-thread envelope, symmetric peer of
        // `attribution_source_kind_coordinates_none_for_name_axis_attribution`.
        for rule in [
            AttributionRule::FileBySource,
            AttributionRule::DefaultsByCodeUniqueness,
        ] {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert!(f.attribution_rule.is_some(), "rule {rule:?}");
            assert!(
                f.attribution_name_kind_coordinates().is_none(),
                "rule {rule:?}: source-axis attribution must yield None name-axis joint cell",
            );
        }
    }

    #[test]
    fn attribution_name_kind_coordinates_some_for_name_axis_attribution_pins_known_cells() {
        // Name-axis attributions surface their joint cell directly on
        // the cross-thread envelope: FileByMetadataName → (Format, File),
        // EnvByPrefix / EnvByUniqueness → (Env, Env). Pins both
        // realizable cells of the new cube through synthetic
        // ReloadFailure values carrying each name-axis rule.
        let cases: [(AttributionRule, AttributionNameKindCoordinates); 3] = [
            (
                AttributionRule::FileByMetadataName,
                AttributionNameKindCoordinates {
                    figment_name_tag_kind: FigmentNameTagKind::Format,
                    layer_kind: ConfigSourceKind::File,
                },
            ),
            (
                AttributionRule::EnvByPrefix,
                AttributionNameKindCoordinates {
                    figment_name_tag_kind: FigmentNameTagKind::Env,
                    layer_kind: ConfigSourceKind::Env,
                },
            ),
            (
                AttributionRule::EnvByUniqueness,
                AttributionNameKindCoordinates {
                    figment_name_tag_kind: FigmentNameTagKind::Env,
                    layer_kind: ConfigSourceKind::Env,
                },
            ),
        ];
        for (rule, expected) in cases {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(
                f.attribution_name_kind_coordinates(),
                Some(expected),
                "rule {rule:?}: name-axis joint cell pin on cross-thread envelope",
            );
        }
    }

    #[test]
    fn attribution_name_kind_coordinates_agrees_with_rule_pointwise() {
        // For every constructible rule scenario, the accessor result
        // equals
        // attribution_rule.and_then(AttributionRule::attribution_name_kind_coordinates)
        // — pinning the convenience accessor as a pure projection.
        for rule in AttributionRule::ALL.iter().copied() {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            assert_eq!(
                f.attribution_name_kind_coordinates(),
                rule.attribution_name_kind_coordinates(),
            );
        }
    }

    #[test]
    fn attribution_name_kind_coordinates_returns_realizable_cell_when_some() {
        // Every Some return from the cross-thread accessor satisfies
        // AttributionNameKindCoordinates::is_realizable — the captured
        // envelope's projection never produces an unrealizable cell,
        // no matter which rule was captured.
        let scenarios: Vec<ReloadFailure> = AttributionRule::ALL
            .iter()
            .copied()
            .map(|rule| ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            })
            .chain(std::iter::once(ReloadFailure::from_error(
                &ShikumiError::Parse("x".to_owned()),
            )))
            .collect();
        for f in scenarios {
            if let Some(cell) = f.attribution_name_kind_coordinates() {
                assert!(
                    cell.is_realizable(),
                    "envelope {:?}: joint cell {cell:?} must be realizable",
                    f.attribution_rule,
                );
            }
        }
    }

    #[test]
    fn attribution_name_kind_coordinates_agrees_with_paired_projections_pointwise() {
        // Lossless-decomposition contract on the cross-thread
        // envelope: the joint cell's named fields agree byte-for-byte
        // with the paired
        // (figment_name_tag_kind, layer_kind)
        // reads on the same envelope. Holds vacuously when the joint
        // cell is None (the paired projection is also None on its
        // figment_name_tag_kind half).
        let scenarios: Vec<ReloadFailure> = AttributionRule::ALL
            .iter()
            .copied()
            .map(|rule| ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            })
            .chain(std::iter::once(ReloadFailure::from_error(
                &ShikumiError::Parse("x".to_owned()),
            )))
            .collect();
        for f in scenarios {
            let joint = f.attribution_name_kind_coordinates();
            let paired = f.figment_name_tag_kind().map(|figment_name_tag_kind| {
                AttributionNameKindCoordinates {
                    figment_name_tag_kind,
                    layer_kind: f.layer_kind().expect(
                        "figment_name_tag_kind Some implies layer_kind Some on the cross-thread envelope",
                    ),
                }
            });
            assert_eq!(
                joint, paired,
                "envelope {:?}: joint cell must equal paired projections",
                f.attribution_rule,
            );
        }
    }

    #[test]
    fn attribution_name_kind_coordinates_xor_attribution_source_kind_coordinates_on_attributed_envelopes()
     {
        // Cross-cube partition law on the cross-thread observable
        // form: every attributed envelope surfaces exactly one of the
        // two figment-metadata × shikumi-layer joint cells as Some;
        // unattributed envelopes surface both as None. Closes the
        // joint-cell universe across the two cubes on the captured
        // envelope, mirror of the rule-side
        // `attribution_rule_attribution_name_kind_coordinates_xor_attribution_source_kind_coordinates`.
        for rule in AttributionRule::ALL.iter().copied() {
            let f = ReloadFailure {
                message: "synth".to_owned(),
                kind: ShikumiErrorKind::Extract,
                sources: vec![],
                field_path: vec![],
                failing_source: Some(ConfigSource::Defaults),
                attribution_rule: Some(rule),
            };
            let source = f.attribution_source_kind_coordinates().is_some();
            let name = f.attribution_name_kind_coordinates().is_some();
            assert_ne!(
                source, name,
                "envelope {rule:?}: exactly one of the two joint cells must be Some",
            );
        }
        // Unattributed envelope: both None.
        let unattributed = ReloadFailure::from_error(&ShikumiError::Parse("x".to_owned()));
        assert!(unattributed.attribution_source_kind_coordinates().is_none());
        assert!(unattributed.attribution_name_kind_coordinates().is_none());
    }

    #[test]
    fn attribution_name_kind_coordinates_survives_clone_independent_of_originating_error() {
        // The captured joint cell is derived from the captured rule
        // (Copy) — it must survive cloning and outlive the originating
        // ShikumiError, parallel to the figment_name_tag_kind-clone
        // and attribution_source_kind_coordinates-clone invariants
        // already pinned on the cross-thread envelope.
        let f = ReloadFailure {
            message: "synth".to_owned(),
            kind: ShikumiErrorKind::Extract,
            sources: vec![],
            field_path: vec![],
            failing_source: Some(ConfigSource::Env("APP_".to_owned())),
            attribution_rule: Some(AttributionRule::EnvByPrefix),
        };
        let g = f.clone();
        assert_eq!(
            g.attribution_name_kind_coordinates(),
            Some(AttributionNameKindCoordinates {
                figment_name_tag_kind: FigmentNameTagKind::Env,
                layer_kind: ConfigSourceKind::Env,
            }),
        );
        assert_eq!(
            g.attribution_name_kind_coordinates(),
            f.attribution_name_kind_coordinates(),
        );
    }
}