tatara-process 0.2.389

Process CRD — K8s clusters, workloads, migrations, tests as Unix processes in the tatara convergence lattice
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
//! `tagged_union::resolve` — the typescape's "exactly-one-Option" pattern,
//! lifted to one source of truth.
//!
//! Several CRD-facing types in this crate ([`crate::intent::Intent`],
//! [`crate::lifetime::Lifetime`], [`crate::export::ArtifactSource`],
//! [`crate::export::VectorChannel`], [`crate::encapsulates::EncapsulationKind`])
//! carry `N` `Option<T>` fields where exactly one is expected to be
//! populated on the wire. Each previously hand-rolled the same
//! `count() + if-let-chain + unreachable!()` body — four parallel tables
//! (the struct fields, an `is_some()` count array, an `if-let-else`
//! resolution chain, and any sibling projection like `IntentVariant::kind`)
//! kept coherent only by code review. The `unreachable!()` arm at the
//! bottom of every chain was a sentinel that fires at runtime if the
//! parallel tables ever drift.
//!
//! This module collapses the resolver to ONE typed sweep over an
//! `IntoIterator<Item = Option<V>>` of candidate variant projections.
//! Adding a new tagged-union variant is now ONE additional line at the
//! callsite — no `unreachable!()` arm to update, no parallel `is_some()`
//! count array to extend.

/// Outcome of [`resolve`] when the candidate list isn't exactly-one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResolveError {
    /// No candidate was populated.
    None,
    /// More than one candidate was populated.
    Many,
}

/// Resolve at most one populated variant from a candidate list.
///
/// Each item in `candidates` is the projected borrowed-variant view for
/// the corresponding `Option<T>` field — `None` when the field is unset,
/// `Some(V::Variant(...))` when set.
///
/// Returns the single populated variant, [`ResolveError::None`] when
/// none are populated, or [`ResolveError::Many`] when more than one are.
///
/// The body is one short-circuiting sweep — `Many` is returned as soon
/// as the second populated entry is seen, without scanning the rest.
pub fn resolve<V>(candidates: impl IntoIterator<Item = Option<V>>) -> Result<V, ResolveError> {
    let mut found: Option<V> = None;
    for candidate in candidates {
        if candidate.is_some() {
            if found.is_some() {
                return Err(ResolveError::Many);
            }
            found = candidate;
        }
    }
    found.ok_or(ResolveError::None)
}

/// Sibling error carriers on tagged-union `.variant()` sites all
/// project the two [`ResolveError`] arms onto the SAME closed-set
/// diagnostic shape — `Empty(&'static str)` for "no variant set"
/// (carrying the closed-set kind list so the operator diagnostic
/// names every candidate) and a payload-free `Ambiguous` for
/// "multiple variants set". This trait names that shared shape as
/// ONE typed contract; [`resolve_or_err`] then composes [`resolve`]
/// with the trait so each per-carrier `.map_err(|e| match e { ... })`
/// site collapses to a one-line typed dispatch.
///
/// Impls live at each error carrier's own module so the (diagnostic
/// message, closed-set list) pair stays owned by the carrier that
/// publishes it — the trait is the projection, not the message.
pub trait TaggedUnionError: Sized {
    /// Construct the "no variant set" arm with the closed-set kind
    /// list slash-joined into the diagnostic payload.
    fn empty(kinds: &'static str) -> Self;
    /// Construct the "multiple variants set" arm.
    fn ambiguous() -> Self;
}

/// Resolve at most one populated variant, mapping the two
/// [`ResolveError`] arms onto the caller's typed carrier via
/// [`TaggedUnionError`]. The compound-lift primitive: sweep +
/// short-circuit + typed-error dispatch as ONE call.
///
/// Substrate primitive for the four sibling `Xxx::variant()` sites
/// on `ProcessSpec` (`Intent::variant`,
/// `EncapsulationKind::variant`, `ArtifactSource::variant`,
/// `VectorChannel::variant`) that previously restated the SAME
/// `.map_err(|e| match e { None => Empty(LIST), Many => Ambiguous })`
/// two-arm dispatch at each call site — every one of them a
/// byte-identical restatement of the (empty→list, many→ambiguous)
/// projection whose payload identity is strictly the carrier's own
/// diagnostic. A fifth sibling error carrier picks up the projection
/// through ONE `impl TaggedUnionError` block + ONE `resolve_or_err`
/// call site.
///
/// The [`Lifetime::variant`](crate::lifetime::Lifetime::variant)
/// site is DELIBERATELY not routed through this primitive — its
/// `ResolveError::None` arm resolves to a `Permanent` default
/// variant, not to an `Empty` typed error, so the projection shape
/// diverges at the None arm.
pub fn resolve_or_err<V, E: TaggedUnionError>(
    candidates: impl IntoIterator<Item = Option<V>>,
    kinds: &'static str,
) -> Result<V, E> {
    resolve(candidates).map_err(|e| match e {
        ResolveError::None => E::empty(kinds),
        ResolveError::Many => E::ambiguous(),
    })
}

/// Declare a sibling error carrier for a tagged-union `.variant()`
/// site — the enum + [`TaggedUnionError`] impl in ONE authoring
/// surface.
///
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) pre-lift restated the same
/// four-piece authoring shape by hand:
///
/// 1. `#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq,
///    Eq)]` on the carrier — byte-identical across all four.
/// 2. A two-variant enum body (`Empty(&'static str)`, `Ambiguous`)
///    — structurally identical.
/// 3. Two `#[error(...)]` messages whose only per-carrier knob is a
///    noun-prefix (`"intent"`, `"encapsulation kind"`, ...) — every
///    other byte of the (`"has no variant set (one of {0}
///    required)"`, `"has multiple variants set; exactly one
///    required"`) tails was verbatim.
/// 4. A six-line `impl TaggedUnionError` whose two constructor
///    bodies re-projected `Self::Empty(kinds)` / `Self::Ambiguous`
///    onto each carrier's own typed variants.
///
/// The macro collapses (1) + (2) + (4) onto ONE call and takes the
/// two per-carrier operator-facing diagnostic literals as named
/// arguments so (3) stays visible at the callsite without re-authoring
/// the shared derive set or trait impl. A fifth sibling carrier
/// lands as ONE `declare_tagged_union_error!` invocation — no
/// re-authored `#[derive(...)]`, no re-authored two-variant enum
/// body, no re-authored `impl TaggedUnionError` block.
///
/// Emitted derives include `Copy` — the `Empty` arm carries only
/// a `&'static str` and the `Ambiguous` arm is payload-free, so
/// the carrier is always `Copy` regardless of caller.
///
/// # Example
///
/// ```ignore
/// declare_tagged_union_error! {
///     pub IntentError,
///     empty = "intent has no variant set (one of {0} required)",
///     ambiguous = "intent has multiple variants set; exactly one required",
/// }
/// ```
///
/// Expands to the enum + [`TaggedUnionError`] impl for
/// `IntentError`; the `Empty` arm carries the caller's closed-set
/// kind-list literal.
#[macro_export]
macro_rules! declare_tagged_union_error {
    (
        $(#[$attr:meta])*
        $vis:vis $name:ident,
        empty = $empty:literal,
        ambiguous = $ambiguous:literal $(,)?
    ) => {
        $(#[$attr])*
        #[derive(
            ::std::clone::Clone,
            ::std::marker::Copy,
            ::std::fmt::Debug,
            ::thiserror::Error,
            ::std::cmp::PartialEq,
            ::std::cmp::Eq,
        )]
        $vis enum $name {
            #[error($empty)]
            Empty(&'static str),
            #[error($ambiguous)]
            Ambiguous,
        }

        impl $crate::tagged_union::TaggedUnionError for $name {
            fn empty(kinds: &'static str) -> Self {
                Self::Empty(kinds)
            }
            fn ambiguous() -> Self {
                Self::Ambiguous
            }
        }
    };
}

/// Declare the three-block impl stanza a tagged-union parent type
/// publishes to the substrate — inherent `.variant()` forwarder +
/// [`VariantSelector<Parent>`] impl on the sibling `Kind` +
/// [`TaggedUnion`] impl on the parent — in ONE authoring surface.
///
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) pre-lift restated the same three
/// impl blocks by hand:
///
/// 1. `impl $parent { pub fn variant(&self) -> Result<$variant<'_>, $err> { ... } }`
///    — a one-line delegation to the [`TaggedUnion::variant`] default
///    body, plus 5 lines of rustdoc cross-referencing the other three
///    sibling `.variant()` sites verbatim.
/// 2. `impl VariantSelector<$parent> for $kind { type Variant<'a> = $variant<'a>; fn select(...) { <$kind>::select(self, parent) } }`
///    — 6 lines whose only per-site knobs are (`$parent`, `$kind`,
///    `$variant`); the trait method body a straight delegation to the
///    inherent `<$kind>::select`.
/// 3. `impl TaggedUnion for $parent { type Kind = $kind; type Error = $err; const KIND_LIST = $kind_list; }`
///    — 3 associated-item assignments whose only per-site knobs are
///    the (`$kind`, `$err`, `$kind_list`) tuple.
///
/// The macro takes the (`$parent`, `$kind`, `$variant`, `$err`,
/// `$kind_list`) five-tuple as named arguments and emits all three
/// blocks. A fifth sibling tagged-union parent picks up all three
/// impls through ONE macro call — no re-authored inherent
/// `.variant()` forwarder, no re-authored `impl VariantSelector`
/// block, no re-authored `impl TaggedUnion` block.
///
/// The emitted inherent `.variant()`'s rustdoc is canonical (names
/// the substrate primitive, not the exact set of sibling sites) so
/// a fifth sibling doesn't drift the cross-ref count against reality
/// merely by existing.
///
/// # Example
///
/// ```ignore
/// declare_tagged_union_impls! {
///     parent = Intent,
///     kind = IntentKind,
///     variant = IntentVariant,
///     error = IntentError,
///     kind_list = INTENT_KIND_LIST,
/// }
/// ```
///
/// Expands to the inherent `Intent::variant`, the
/// `VariantSelector<Intent>` impl on `IntentKind`, and the
/// `TaggedUnion` impl on `Intent`.
#[macro_export]
macro_rules! declare_tagged_union_impls {
    (
        parent = $parent:ty,
        kind = $kind:ty,
        variant = $variant:ident,
        error = $err:ty,
        kind_list = $kind_list:expr $(,)?
    ) => {
        impl $parent {
            /// Resolve to exactly one variant. Errors on zero or many.
            ///
            /// One-line inherent forwarder that delegates the sweep
            /// body to the substrate primitive
            /// [`crate::tagged_union::TaggedUnion::variant`] — every
            /// production `.variant()` site on `ProcessSpec` dispatches
            /// through this ONE default body so the resolve-sweep
            /// pattern lives at ONE substrate site. The inherent surface
            /// stays load-bearing so consumer callsites don't need
            /// `use TaggedUnion`.
            pub fn variant(&self) -> ::std::result::Result<$variant<'_>, $err> {
                <Self as $crate::tagged_union::TaggedUnion>::variant(self)
            }
        }

        impl $crate::tagged_union::VariantSelector<$parent> for $kind {
            type Variant<'a> = $variant<'a>;
            fn select<'a>(self, parent: &'a $parent) -> ::std::option::Option<$variant<'a>>
            where
                Self: 'a,
            {
                <$kind>::select(self, parent)
            }
        }

        impl $crate::tagged_union::TaggedUnion for $parent {
            type Kind = $kind;
            type Error = $err;
            const KIND_LIST: &'static str = $kind_list;
        }
    };
}

/// Project the borrowed-view of a tagged-union variant addressed by
/// this closed-set discriminator.
///
/// Companion trait to [`TaggedUnion`] — binds a `Kind` closed-set to
/// the parent `P` it discriminates AND to the borrowed-view
/// [`Self::Variant<'a>`] the resolver hands out. Every one of the
/// four production `.variant()` sites on `ProcessSpec`
/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// pre-lift restated the same
/// `Self::Kind::ALL.into_iter().map(|k| k.select(self))` sweep body
/// verbatim at its inherent `.variant()`. Post-lift the trait binds
/// `(k.select(self), Variant<'a>)` onto ONE typed contract per Kind
/// so [`TaggedUnion::variant`]'s default body can dispatch the sweep
/// generically — the four sibling inherent bodies collapse to
/// one-line delegations and a fifth sibling picks up the sweep for
/// free through ONE `impl VariantSelector` block.
///
/// The GAT `Variant<'a>` carries the parent's lifetime so a borrowed
/// view projected from `&'a P` composes typed with the resolver's
/// short-circuit — every projection stays a compile-time refinement,
/// no `Box<dyn ...>` erasure. The GAT is additionally bound to
/// [`VariantKind<Self>`] so every implementor's borrowed view knows
/// its addressing Kind — the reverse projection of [`Self::select`]
/// closed at compile-time so a fifth sibling that adds `impl
/// VariantSelector` without opening the peer `impl VariantKind` fails
/// at the trait bound, not later at a per-consumer round-trip test.
pub trait VariantSelector<P: ?Sized>: Copy + 'static {
    /// The borrowed-view enum returned by the parent's inherent
    /// `.variant()` method — one arm per closed-set variant, each
    /// arm carrying a `&'a` reference into the parent's populated
    /// slot. Bound generically here so [`TaggedUnion::variant`]'s
    /// default body can name the return type without restating it
    /// per parent. Additionally bound to [`VariantKind<Self>`] so
    /// the reverse projection `Variant<'a> → Self` is closed at the
    /// trait boundary — every implementor's borrowed view knows its
    /// addressing Kind through ONE typed contract, and the substrate
    /// testkit [`assert_variant_round_trip`] composes `select`
    /// (forward) with `variant_kind` (reverse) generically.
    type Variant<'a>: VariantKind<Self>
    where
        P: 'a,
        Self: 'a;

    /// Project a `&'a P` borrow into the optional typed variant view
    /// for `self` (the addressed discriminator). Returns `None` iff
    /// the matching slot on `P` is `None`. Composes the closed-set
    /// sweep [`TaggedUnion::variant`] loops over.
    fn select<'a>(self, parent: &'a P) -> Option<Self::Variant<'a>>
    where
        Self: 'a;
}

/// Reverse projection — every borrowed-variant view enum knows its
/// closed-set `K` discriminator.
///
/// Dual of [`VariantSelector<P>::select`] on the addressed Kind:
/// where the selector projects a parent borrow forward into an
/// optional Variant, this trait projects a populated Variant back
/// into the Kind that addresses it. Together they compose the
/// round-trip contract every tagged-union `.variant()` site pins
/// via the substrate testkit [`assert_variant_round_trip`]:
/// `k.select(&parent).map(|v| v.variant_kind()) == Some(k)` on the
/// populated side, and `parent.variant().unwrap().variant_kind() == k`
/// through the [`TaggedUnion::variant`] resolver's default body.
///
/// Every borrowed-view enum on `ProcessSpec`'s tagged-union axis
/// ([`crate::intent::IntentVariant<'_>`],
/// [`crate::lifetime::LifetimeVariant<'_>`],
/// [`crate::encapsulates::EncapsulationKindVariant<'_>`],
/// [`crate::export::ArtifactVariant<'_>`],
/// [`crate::export::ChannelVariant<'_>`]) pre-lift restated the same
/// `match self { Self::A(_) => K::A, Self::B(_) => K::B, ... }`
/// per-arm mapping at its own inherent method (named `.kind()` on
/// four of five sites; `.target()` on
/// [`crate::encapsulates::EncapsulationKindVariant`] where the
/// discriminator's semantic role is a target of encapsulation, not
/// a kind of parent). The reverse-projection body must stay
/// per-implementor — it names the ground-truth arm-to-Kind mapping
/// only the site knows — but the CONTRACT lives at ONE typed
/// surface so:
///
/// * Every downstream generic consumer binds through
///   `<T::Variant<'_> as VariantKind<T::Kind>>::variant_kind(&v)`
///   instead of a per-parent inherent-method restatement.
/// * [`VariantSelector<P>::Variant<'a>`] bounds this trait — a
///   fifth sibling that adds `impl VariantSelector<P> for XKind`
///   without the peer `impl VariantKind<XKind> for XVariant<'_>`
///   fails at the associated-type bound, so the reverse projection
///   is closed at compile-time across every implementor.
/// * The generic testkit [`assert_variant_round_trip`] composes
///   `select` (forward) with `variant_kind` (reverse) at ONE
///   substrate site — the four sibling
///   `_kind_round_trips_through_variant_kind` /
///   `_target_round_trips_through_variant_target` test bodies
///   collapse to one-line invocations.
///
/// The trait method is named [`Self::variant_kind`] rather than
/// `kind` to avoid shadowing the inherent `.kind()` (or
/// `.target()`) methods each borrowed-view enum already publishes.
/// Every impl body is a one-line delegation to the site's inherent
/// method — the substrate stays the projection, not the mapping.
pub trait VariantKind<K: Copy + 'static> {
    /// Project a borrowed-variant view back into its addressing
    /// closed-set `K` discriminator. Round-trips the closed set on
    /// the populated side against [`VariantSelector::select`] — a
    /// value returned by `k.select(&parent).unwrap()` must satisfy
    /// `variant_kind() == k`, and a value returned by
    /// `parent.variant().unwrap()` must satisfy `variant_kind() ==
    /// k` for the populated slot's `k`.
    fn variant_kind(&self) -> K;
}

/// Generic round-trip testkit — pins that
/// [`VariantSelector::select`] (forward projection) and
/// [`VariantKind::variant_kind`] (reverse projection) compose the
/// closed set in both directions on the populated side.
///
/// Substrate primitive for the four sibling
/// `_kind_round_trips_through_variant_kind` /
/// `_target_round_trips_through_variant_target` tests on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) that pre-lift each restated the
/// same two-arm round-trip probe at their own test bodies:
///
/// 1. For each `k in K::ALL`, construct a parent with only slot `k`
///    populated (via a site-local `single_slot_X(k) -> Parent`
///    helper).
/// 2. Assert that `k.select(&parent).unwrap().variant_kind() == k`
///    (the forward-then-reverse round-trip).
/// 3. Assert that `parent.variant().unwrap().variant_kind() == k`
///    (the resolver-then-reverse round-trip).
///
/// Post-lift each site's round-trip test collapses to ONE
/// `assert_variant_round_trip::<T, _>(single_slot_X)` invocation
/// whose body is the substrate primitive's own dispatch. A fifth
/// sibling picks up the round-trip check through ONE call site.
///
/// The `make_parent` closure stays per-site — every one of the four
/// production sites already owns a
/// `single_slot_intent(k) / single_slot_source(k) /
/// single_slot_channel(k) / single_slot_kind(t)` helper that
/// constructs a minimally-valid parent with the addressed slot's
/// inner spec populated; the closure IS the round-trip's ground
/// truth for "populate slot k", and lifting it into the primitive
/// would collapse the per-site construction knowledge that stays
/// deliberately local.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// — `Lifetime` doesn't impl [`TaggedUnion`] (its `variant()` returns
/// `Ok(Permanent)` on empty, not an `Empty` typed error), so the
/// `<T: TaggedUnion>` bound doesn't reach it. Its per-site
/// round-trip test binds through [`VariantKind`] directly on
/// [`crate::lifetime::LifetimeVariant`] instead.
#[track_caller]
pub fn assert_variant_round_trip<T, F>(make_parent: F)
where
    T: TaggedUnion,
    T::Kind: PartialEq + std::fmt::Debug,
    F: Fn(T::Kind) -> T,
{
    for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
        .iter()
        .copied()
    {
        let parent = make_parent(k);
        let selected = k.select(&parent).unwrap_or_else(|| {
            panic!("VariantSelector::select must return Some for populated slot {k:?}")
        });
        assert_eq!(
            <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
                &selected,
            ),
            k,
            "select→variant_kind round-trip failed for {k:?}",
        );
        let resolved = parent.variant().ok().unwrap_or_else(|| {
            panic!("TaggedUnion::variant must resolve exactly-one populated for {k:?}")
        });
        assert_eq!(
            <<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
                &resolved,
            ),
            k,
            "variant()→variant_kind resolver disagreed on {k:?}",
        );
    }
}

/// Declarative surface that names the (Kind, Error, KIND_LIST) triple
/// a tagged-union `.variant()` site publishes to the substrate — and
/// provides the sweep body as ONE default method every implementor
/// picks up for free.
///
/// Every one of the four production `.variant()` sites on `ProcessSpec`
/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// exposes the SAME three-piece surface: a closed-set discriminator
/// [`Self::Kind`], a typed [`Self::Error`] carrier that projects onto
/// the shared [`TaggedUnionError`] contract, and a slash-joined
/// operator diagnostic literal [`Self::KIND_LIST`]. Pre-lift the
/// triple lived on each parent type as independent inherent items —
/// the (Kind, Error) types cross-referenced only by module-doc prose,
/// the `KIND_LIST` `&'static str` maintained separately at each site
/// alongside the inherent `.variant()` body. Post-lift the trait
/// binds the three onto ONE typed contract per parent so downstream
/// generic code binds to `<T: TaggedUnion>` instead of restating the
/// per-parent quadruple of associated names.
///
/// The [`Self::variant`] default method is the substrate primitive
/// every inherent `.variant()` on the four production sites delegates
/// to — one-line inherent forwarders preserve the load-bearing
/// calling convention (so no downstream callsite needs
/// `use crate::tagged_union::TaggedUnion` to reach `.variant()`) while
/// the resolve-sweep body lives at ONE substrate site. Adding a fifth
/// sibling means ONE `impl TaggedUnion` block + ONE
/// `impl VariantSelector<Self>` block on the sibling `Kind` + ONE
/// one-line inherent forwarder — no re-authored 5-line
/// `resolve_or_err(K::ALL.into_iter().map(|k| k.select(self)),
/// KIND_LIST)` sweep body.
///
/// The `Kind` type is bound to [`tatara_closed_set::ClosedSet`] so
/// generic testkit primitives (starting with
/// [`assert_kind_list_matches_closed_set`]) can compose
/// `<Self::Kind as ClosedSet>::labels_joined("/")` against
/// [`Self::KIND_LIST`] byte-identically across every implementor —
/// the diagnostic-stability invariant every sibling pre-lift pinned
/// through a hand-rolled per-site test body. It is additionally
/// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s default
/// body reaches `k.select(self)` generically.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY not routed
/// through this trait — its `variant()` returns `Ok(Permanent)` on
/// empty rather than an `Empty` typed error, so its projection shape
/// diverges from the four Empty-projecting siblings. Same reasoning
/// as [`resolve_or_err`]'s explicit exclusion of `Lifetime`.
pub trait TaggedUnion: Sized {
    /// The closed-set discriminator over this tagged-union's variants.
    /// Bound to [`tatara_closed_set::ClosedSet`] so the generic
    /// diagnostic-stability testkit ([`assert_kind_list_matches_closed_set`])
    /// can project `<Self::Kind as ClosedSet>::labels_joined("/")`
    /// against [`Self::KIND_LIST`] byte-identically. Additionally
    /// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s
    /// default body can dispatch `k.select(self)` at each
    /// [`ClosedSet::ALL`] entry generically.
    type Kind: tatara_closed_set::ClosedSet + VariantSelector<Self>;

    /// The typed error carrier returned by the parent's inherent
    /// `.variant()` method — projects onto the shared
    /// [`TaggedUnionError`] contract so [`resolve_or_err`]'s two-arm
    /// dispatch reaches every implementor uniformly.
    type Error: TaggedUnionError;

    /// Slash-joined operator diagnostic literal — the payload of
    /// [`TaggedUnionError::empty`] when no slot is populated on this
    /// tagged union. Pinned against
    /// `<Self::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
    /// by [`assert_kind_list_matches_closed_set`] so a variant added
    /// to `Self::Kind` without updating this constant (or a renamed
    /// variant) fails-loudly at the testkit boundary.
    const KIND_LIST: &'static str;

    /// Sweep over every [`Self::Kind`] discriminator in
    /// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order,
    /// projecting each into the parent's borrowed variant view via
    /// [`VariantSelector::select`], and resolve to exactly one populated
    /// variant through [`resolve_or_err`]. Errors on zero (with
    /// [`Self::KIND_LIST`] carried on the [`TaggedUnionError::empty`]
    /// arm) or many.
    ///
    /// The substrate primitive every one of the four production
    /// `.variant()` sites on `ProcessSpec` dispatches through — the
    /// per-parent inherent `.variant()` is a one-line delegation to
    /// this default so the calling convention (`intent.variant()`,
    /// `channel.variant()`, ...) stays load-bearing at the callsite
    /// without every consumer picking up `use TaggedUnion`.
    ///
    /// Adding a fifth sibling picks up this body for free — no
    /// re-authored `resolve_or_err(...)` sweep at the impl block.
    fn variant(&self) -> Result<<Self::Kind as VariantSelector<Self>>::Variant<'_>, Self::Error> {
        resolve_or_err(
            <Self::Kind as tatara_closed_set::ClosedSet>::ALL
                .iter()
                .copied()
                .map(|k| k.select(self)),
            Self::KIND_LIST,
        )
    }
}

/// Generic diagnostic-stability testkit — pins that [`TaggedUnion::KIND_LIST`]
/// matches `<T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
/// byte-identically for every implementor.
///
/// Substrate primitive for the four sibling
/// `_error_empty_lists_every_kind_in_canonical_order` tests on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// that pre-lift each restated the same
/// `assert_eq!(<XxxKind as ClosedSet>::labels_joined("/"),
/// XXX_KIND_LIST)` two-argument comparison at their own test bodies —
/// byte-identical projections whose only per-carrier knobs (the Kind
/// type + the KIND_LIST constant) are the two associated items the
/// [`TaggedUnion`] trait names. Post-lift each site collapses to ONE
/// `assert_kind_list_matches_closed_set::<Xxx>()` invocation whose
/// body is the substrate primitive's own dispatch.
///
/// A fifth sibling tagged-union parent picks up the diagnostic-
/// stability check through ONE `impl TaggedUnion for X` block + ONE
/// `assert_kind_list_matches_closed_set::<X>()` call site — no
/// re-authored `<XKind as ClosedSet>::labels_joined("/")` composition
/// at the test site, no re-authored per-site `assert_eq!` pair.
#[track_caller]
pub fn assert_kind_list_matches_closed_set<T: TaggedUnion>() {
    let derived = <T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/");
    assert_eq!(
        derived,
        T::KIND_LIST,
        "TaggedUnion KIND_LIST drift — must equal <T::Kind as ClosedSet>::labels_joined(\"/\")",
    );
}

/// Generic ambiguity testkit — pins that [`TaggedUnion::variant`]
/// resolves to [`TaggedUnionError::ambiguous`] on EVERY off-diagonal
/// `(a, b)` pair in [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// `× ALL`.
///
/// Substrate primitive for the sibling
/// `_two_slots_is_ambiguous_across_every_pair` tests on `ProcessSpec`
/// ([`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// that pre-lift each restated the same nested-`for a in K::ALL { for
/// b in K::ALL { if a == b { continue; } … } }` sweep at their own
/// test bodies — byte-identical projections whose only per-carrier
/// knobs are the (Kind type + the `two_slot_X(a, b) -> Parent`
/// two-slot factory) pair. Post-lift each site collapses to ONE
/// `assert_two_slots_ambiguous::<Xxx, _>(two_slot_X)` invocation.
///
/// The `two_slot` closure stays per-site — every one of the three
/// production sites already owns a `two_slot_kind /
/// two_slot_source / two_slot_channel` helper that composes two
/// `single_slot_X`s per-field. The closure IS the "populate both
/// slots a and b" ground truth for the carrier's field structure;
/// lifting it into the primitive would collapse per-site field-
/// composition knowledge that stays deliberately local.
///
/// The pair sweep excludes the diagonal (`a == b`) — a single slot
/// populated is exactly-one, not many, and the round-trip primitive
/// [`assert_variant_round_trip`] already pins that populated slot's
/// resolution. This primitive is the peer contract for the Many arm.
///
/// A fifth sibling tagged-union parent picks up the ambiguity check
/// through ONE `impl TaggedUnion for X` block + ONE per-site
/// `two_slot_X` helper + ONE `assert_two_slots_ambiguous::<X, _>`
/// call site — no re-authored nested-for sweep at the test surface,
/// no re-authored `assert_eq!(..., X::Error::Ambiguous, ...)` arm.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// — `Lifetime` doesn't impl [`TaggedUnion`] (its error carrier has
/// no `Empty` arm; its `variant()` returns `Ok(Permanent)` on empty
/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
/// bound doesn't reach it. Its per-site ambiguity assertion binds
/// through the inherent `.variant()` + hand-authored two-slot
/// probe. Same reasoning as [`resolve_or_err`]'s and
/// [`assert_variant_round_trip`]'s exclusions.
#[track_caller]
pub fn assert_two_slots_ambiguous<T, F>(two_slot: F)
where
    T: TaggedUnion,
    T::Kind: PartialEq + std::fmt::Debug,
    T::Error: PartialEq + std::fmt::Debug,
    F: Fn(T::Kind, T::Kind) -> T,
{
    let expected = T::Error::ambiguous();
    for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
        .iter()
        .copied()
    {
        for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
            .iter()
            .copied()
        {
            if a == b {
                continue;
            }
            let parent = two_slot(a, b);
            let err = parent.variant().err().unwrap_or_else(|| {
                panic!("({a:?}, {b:?}) two-slot parent must not resolve to a variant")
            });
            assert_eq!(err, expected, "({a:?}, {b:?}) should resolve Ambiguous");
        }
    }
}

/// Generic wire-key / kind-label alignment testkit — pins that every
/// single-slot parent serializes to a JSON object with EXACTLY ONE key
/// whose name equals `<T::Kind as tatara_closed_set::ClosedSet>::label`
/// on the populated slot's kind.
///
/// Substrate primitive for the four sibling
/// `X_kind_as_str_matches_field_name` / `intent_kind_as_str_matches_intent_field_name`
/// tests on `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// that pre-lift each restated the same wire-format sweep at their own
/// test bodies:
///
/// 1. For each `k in K::ALL`, construct a single-slot parent via
///    the site-local `single_slot_X(k) -> Parent` factory.
/// 2. Serialize it to the wire format and assert that the emitted
///    key matches `k.as_str()`.
///
/// Post-lift each site's alignment test collapses to ONE
/// `assert_single_slot_key_matches_label::<T, _>(single_slot_X)`
/// invocation whose body IS the substrate primitive's own dispatch.
/// A fifth sibling picks up the alignment check through ONE call site.
///
/// The primitive projects through `serde_json::to_value` rather than
/// `serde_yaml::to_string` for two reasons: (1) the check is
/// structural (exactly-one-key + name equality), not textual (substring
/// against a `"{key}:"` YAML fragment), so a future site that gains
/// non-tagged-union metadata fields is caught HERE at the exactly-one
/// arm — the YAML-substring check the three encapsulates / export sites
/// carried pre-lift would silently pass on such drift. (2) serde's
/// field-rename projection (`rename_all = "camelCase"`) is format-
/// agnostic, so a JSON check pins the SAME invariant a YAML check
/// would pin, byte-identically. Every one of the four production
/// parents already emits exactly one key on a single-slot populate —
/// their `#[serde(default, skip_serializing_if = "Option::is_none")]`
/// annotations on every tagged-union slot guarantee it — so upgrading
/// the three YAML sites to the JSON exactly-one check is a strict
/// strengthening.
///
/// The `single_slot` closure stays per-site — every one of the four
/// production sites already owns a `single_slot_intent /
/// single_slot_kind / single_slot_source / single_slot_channel` helper
/// that constructs a minimally-valid parent with the addressed slot's
/// inner spec populated; the closure IS the "populate slot k" ground
/// truth for the carrier's field structure. Reused verbatim from the
/// [`assert_variant_round_trip`] primitive.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// from THIS trait-projected surface — `Lifetime` doesn't impl
/// [`TaggedUnion`] (its `variant()` returns `Ok(Permanent)` on empty
/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
/// bound doesn't reach it. The bound-relaxed peer
/// [`assert_wire_key_matches_label`] carries the SAME sweep body
/// under `<T: Serialize>` + `<K: ClosedSet>` alone — Lifetime binds
/// through it directly and this trait-projected surface becomes a
/// one-line delegation whose only load-bearing purpose is to name
/// the TaggedUnion parent's `T::Kind` associated type at the call
/// site (existing `assert_single_slot_key_matches_label::<T, _>(f)`
/// callers stay unchanged; the peer inflects the same body onto
/// non-TaggedUnion parents).
#[track_caller]
pub fn assert_single_slot_key_matches_label<T, F>(single_slot: F)
where
    T: TaggedUnion + serde::Serialize,
    T::Kind: PartialEq + std::fmt::Debug,
    F: Fn(T::Kind) -> T,
{
    assert_wire_key_matches_label::<T, T::Kind, F>(single_slot);
}

/// Bound-relaxed peer of [`assert_single_slot_key_matches_label`] —
/// the SAME wire-key alignment sweep, but on any `(K, T)` pair where
/// `K: ClosedSet` addresses `T: Serialize` through a caller-supplied
/// `single_slot: Fn(K) -> T` factory. Drops the `T: TaggedUnion`
/// bound the sibling primitive carries so parents whose empty
/// resolution shape diverges from the tagged-union convention (the
/// canonical example: [`crate::lifetime::Lifetime`], whose empty
/// resolves to `Permanent(&DEFAULT_PERMANENT)` rather than to an
/// [`TaggedUnionError::empty`] carrier) still bind through ONE
/// substrate wire-key alignment site.
///
/// The two primitives share ONE sweep body; the trait-projected
/// [`assert_single_slot_key_matches_label`] is now a one-line
/// delegation to this bound-relaxed peer, so every drift-arm the
/// sibling `#[should_panic]` probe pins on the delegating surface
/// mechanically pins here too. The compounding gain: a fifth parent
/// whose closed-set kind K doesn't ride the TaggedUnion trait (a
/// future variant surface with a default-arm on empty; a wire-only
/// enum whose parent is a wrapper struct that never publishes a
/// resolver; a K-addressed `HashMap<K, Payload>` where the payload
/// isn't a tagged-union variant carrier at all) picks up wire-key
/// alignment through ONE call site — no re-authored serialize +
/// exactly-one-key + name-equality body at the test surface, no
/// per-parent drift risk where the trait-projected surface catches
/// it and the bespoke surface forgets.
///
/// The primitive binds `<K: ClosedSet + PartialEq + Debug>` (the
/// strict union of the sweep body's projection + the panic-message
/// substrate-wide shape) — every production `ClosedSet` implementor
/// across the crate carries `Debug + PartialEq` through the
/// substrate-wide `#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
/// DeriveClosedSet)]` shape, so no site pays a bound-widening cost
/// to bind through this peer.
#[track_caller]
pub fn assert_wire_key_matches_label<T, K, F>(single_slot: F)
where
    T: serde::Serialize,
    K: tatara_closed_set::ClosedSet + PartialEq + std::fmt::Debug,
    F: Fn(K) -> T,
{
    for k in <K as tatara_closed_set::ClosedSet>::ALL.iter().copied() {
        let parent = single_slot(k);
        let value = serde_json::to_value(&parent)
            .unwrap_or_else(|e| panic!("single_slot({k:?}) must serialize as JSON: {e}"));
        let obj = value.as_object().unwrap_or_else(|| {
            panic!("single_slot({k:?}) must serialize to a JSON object, got {value}")
        });
        let keys: Vec<&String> = obj.keys().collect();
        assert_eq!(
            keys.len(),
            1,
            "single_slot({k:?}) must serialize to exactly one populated field, got keys: {keys:?}",
        );
        let expected = <K as tatara_closed_set::ClosedSet>::label(k);
        assert_eq!(
            keys[0].as_str(),
            expected,
            "wire-key drift for {k:?}: single_slot's populated field '{}' must equal <K as ClosedSet>::label ({expected:?})",
            keys[0],
        );
    }
}

/// Generic Display / [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
/// alignment testkit — pins that [`core::fmt::Display`] renders each variant
/// BYTE-IDENTICALLY to the trait-visible `ClosedSet::label` projection for
/// every implementor.
///
/// Substrate primitive for the 29 sibling
/// `X_display_matches_as_str` tests across `tatara-process`
/// (`AllocationPhase`, `IntentKind`, `WorkloadKind`, `EncapsulationMode`,
/// `EncapsulationTarget`, `ConditionKind`, `TerminateReasonKind`,
/// `AutoTerminateKind`, `SighupStrategy`, `ReplacementPolicy`,
/// `ReturnPolicy`, `MemberState`, `PoolPhase`, `VerificationPhase`,
/// `SelectStrategyKind`, `MustReachPhase`, `ExportTrigger`,
/// `ReportFormat`, `ReportPayloadShape`, `ArtifactKind`, `ChannelKind`,
/// `DataClassification`, `ConvergencePointType`, `Arity`,
/// `SubstrateType`, `CalmClassification`, `OptimizationDirection`,
/// `HorizonKind`, `TeardownPolicy`) that pre-lift each restated the
/// same
/// ```text
/// for v in K::ALL {
///     assert_eq!(v.to_string(), v.as_str());
/// }
/// ```
/// two-line probe verbatim at their own test bodies — byte-identical
/// projections whose only per-carrier knob is the closed-set type name.
/// Post-lift each site collapses to ONE
/// `assert_display_matches_label::<X>()` invocation whose body IS the
/// substrate primitive's own dispatch.
///
/// The primitive projects through the STABLE trait-visible name
/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
/// than the inherent `.as_str()` each site publishes locally. Every
/// production implementor here derives its `label` body from `as_str`
/// via `#[closed_set(via = "as_str", display)]` (the substrate-wide
/// derive shape), so the two are byte-identical by construction; the
/// primitive's projection through `label` therefore pins the SAME
/// invariant the pre-lift bodies pinned while binding to the
/// stable trait-visible surface. A future implementor whose inherent
/// canonical projection is named something other than `as_str` (e.g.
/// `.keyword()`, `.spelling()`) but still routes through
/// `#[closed_set(via = "...", display)]` picks up the alignment check
/// through ONE `assert_display_matches_label::<X>()` invocation with
/// no inherent-name coupling at the test site.
///
/// A fifth (or thirtieth, or hundredth) implementor picks up the
/// Display-alignment check through ONE
/// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `display`
/// attribute + ONE `assert_display_matches_label::<X>()` call site —
/// no re-authored two-line
/// `for v in K::ALL { assert_eq!(v.to_string(), v.as_str()) }` body
/// at the test surface, no per-site drift risk where 28 sibling
/// tests carry the assertion and the 29th forgets.
///
/// Sibling shape to [`assert_kind_list_matches_closed_set`] on the
/// (`T::KIND_LIST` slash-join, `Display` byte-identity) axis: both
/// project the closed-set's label surface onto ONE typed contract
/// and pin it against a per-implementor rendering; the former for
/// the tagged-union parent's [`TaggedUnion::KIND_LIST`] `&'static str`,
/// this one for the enum's `Display` byte stream. Together they close
/// the "label surface must round-trip verbatim" invariant every
/// closed-set-carrying implementor across the crate publishes.
#[track_caller]
pub fn assert_display_matches_label<T>()
where
    T: tatara_closed_set::ClosedSet + core::fmt::Display + PartialEq + core::fmt::Debug,
{
    let type_name = core::any::type_name::<T>();
    for &v in <T as tatara_closed_set::ClosedSet>::ALL {
        let rendered = v.to_string();
        let expected = <T as tatara_closed_set::ClosedSet>::label(v);
        assert_eq!(
            rendered.as_str(),
            expected,
            "{type_name}: Display drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {rendered:?}",
        );
    }
}

/// CANONICAL-KEY CONTRACT testkit — pins that each variant's serde
/// serialization (as a JSON string value, unquoted) matches its
/// canonical [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
/// projection BYTE-IDENTICALLY for every implementor.
///
/// Substrate primitive for the 20 sibling
/// `X_as_str_matches_serde` tests across `tatara-process`
/// (`TeardownPolicy`, `EncapsulationMode`, `ConditionKind`,
/// `SighupStrategy`, `ReplacementPolicy`, `ReturnPolicy`, `MemberState`,
/// `PoolPhase`, `VerificationPhase`, `MustReachPhase`, `WorkloadKind`,
/// `ExportTrigger`, `ReportFormat`, `DataClassification`,
/// `ConvergencePointType`, `SubstrateType`, `CalmClassification`,
/// `OptimizationDirection`, `HorizonKind`, `AllocationPhase`) that
/// pre-lift each restated the same
/// ```text
/// for v in K::ALL {
///     let serialized = serde_json::to_string(&v).expect("serialize");
///     let unquoted = serialized
///         .trim_start_matches('"')
///         .trim_end_matches('"')
///         .to_string();
///     assert_eq!(unquoted, v.as_str(), "as_str drift for {v:?}: ...");
/// }
/// ```
/// four-line probe verbatim at their own test bodies — byte-identical
/// projections whose only per-carrier knob is the closed-set type name.
/// Post-lift each site collapses to ONE
/// `assert_label_matches_serde_serialization::<X>()` invocation whose
/// body IS the substrate primitive's own dispatch.
///
/// The primitive projects through the STABLE trait-visible name
/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
/// than the inherent `.as_str()` each site publishes locally. Every
/// production implementor here derives its `label` body from `as_str`
/// via `#[closed_set(via = "as_str", display)]` + `#[serde(rename_all
/// = "PascalCase")]` (the substrate-wide derive shape), so the two are
/// byte-identical by construction; the primitive's projection through
/// `label` therefore pins the SAME invariant the pre-lift bodies
/// pinned while binding to the stable trait-visible surface. A future
/// implementor whose canonical inherent projection is named something
/// other than `as_str` (e.g. `.keyword()`, `.spelling()`) but still
/// routes through `#[closed_set(via = "...")]` picks up the wire-format
/// alignment check through ONE call with no inherent-name coupling at
/// the test site.
///
/// A twenty-first (or hundredth) implementor picks up the alignment
/// check through ONE `#[derive(tatara_closed_set::DeriveClosedSet)]` +
/// `#[derive(serde::Serialize)]` + `#[serde(rename_all = "...")]`
/// attribute + ONE `assert_label_matches_serde_serialization::<X>()`
/// call site — no re-authored four-line probe body at the test surface,
/// no per-site drift risk where 19 sibling tests carry the assertion
/// and the 20th forgets, no `serde_json::to_string`+`trim_matches`+
/// `assert_eq!` composition re-derived per implementor.
///
/// Sibling shape to [`assert_display_matches_label`] on the
/// (Display byte-identity, serde-wire-format byte-identity) axis: both
/// project the closed-set's label surface onto ONE typed contract and
/// pin it against a per-implementor rendering; the former for the
/// enum's [`Display`](core::fmt::Display) byte stream, this one for
/// the serde JSON-string wire format. Together they close the "label
/// surface renders verbatim across every projection consumers reach
/// for" invariant every closed-set-carrying implementor across the
/// crate publishes.
#[track_caller]
pub fn assert_label_matches_serde_serialization<T>()
where
    T: tatara_closed_set::ClosedSet + serde::Serialize + core::fmt::Debug,
{
    let type_name = core::any::type_name::<T>();
    for &v in <T as tatara_closed_set::ClosedSet>::ALL {
        let serialized = serde_json::to_string(&v).unwrap_or_else(|e| {
            panic!("{type_name}: closed-set variant {v:?} must serialize: {e}")
        });
        let unquoted = serialized.trim_start_matches('"').trim_end_matches('"');
        let expected = <T as tatara_closed_set::ClosedSet>::label(v);
        assert_eq!(
            unquoted,
            expected,
            "{type_name}: serde output drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {unquoted:?} (full serialization {serialized:?})",
        );
    }
}

/// CLOSED-SET CONVENTION PANEL testkit — pins the FULL three-axis
/// label-surface convention (parse round-trip, Display byte-identity,
/// serde-JSON-string byte-identity) at ONE substrate call site per
/// implementor.
///
/// Compound-lift of [`tatara_closed_set::assert_closed_set_well_formed`]
/// + [`assert_display_matches_label`] + [`assert_label_matches_serde_
/// serialization`] — every closed-set enum on `ProcessSpec` that
/// carries the substrate-wide `#[derive(DeriveClosedSet)] +
/// #[derive(Serialize)] + #[closed_set(via = "as_str", display)] +
/// #[serde(rename_all = "PascalCase")]` shape publishes ALL THREE
/// axes of the label surface, and pre-lift each production test
/// module hand-authored three sibling one-line tests
/// (`X_is_well_formed_closed_set`, `X_display_matches_as_str`,
/// `X_as_str_matches_serde`) that each restated the SAME
/// `crate::tagged_union::assert_<axis>::<X>()` invocation with only
/// the axis name varying between siblings. Post-lift each site
/// collapses to ONE `assert_closed_set_convention_panel::<X>()`
/// invocation whose body IS the three-axis composition dispatched
/// through the substrate primitive here.
///
/// The three sub-assertions stay independently callable — a future
/// implementor that publishes only two of the three axes (a
/// `Display`-less internal enum, e.g., or a `Serialize`-less
/// runtime-only enum) still binds through the two sibling primitives
/// individually. The compound is a strict superset: any implementor
/// that satisfies the compound's bounds already satisfies each
/// sub-assertion's bounds by construction, and the failure mode of
/// each sub-assertion still surfaces with the exact-message
/// granularity `#[track_caller]` gives the individual primitives
/// (the compound is `#[track_caller]` too, so a sub-assertion panic
/// surfaces at the compound's call site — a future promotion could
/// wrap each sub-assertion in a `std::panic::catch_unwind` to
/// aggregate all three axis failures into ONE panic message, but the
/// pre-lift discipline is that each axis's failure surfaces with its
/// own diagnostic).
///
/// The compound's bounds are the strict union of the three sub-
/// assertions' bounds:
///   - [`assert_closed_set_well_formed`] requires
///     `T: ClosedSet + PartialEq + Debug` + `T::Unknown: Display`;
///   - [`assert_display_matches_label`] requires
///     `T: ClosedSet + Display + PartialEq + Debug`;
///   - [`assert_label_matches_serde_serialization`] requires
///     `T: ClosedSet + Serialize + Debug`.
/// The union `T: ClosedSet + Serialize + Display + PartialEq + Debug`
/// + `T::Unknown: Display` is what every 3-axis production consumer
/// already satisfies through the substrate-wide derive shape — any
/// implementor that fails the compound's bounds would ALSO fail the
/// individual sub-assertions' bounds, so the compound doesn't shrink
/// the reachable set of implementors relative to hand-authoring the
/// three sibling calls.
///
/// A future FOURTH label-surface projection (e.g. a `serde_yaml`
/// byte-identity axis if the crate gains a YAML wire form on closed-
/// set enums, or a `kubectl_annotation` axis if the reconciler grows
/// an annotation-carried label surface) lands as ONE new
/// `assert_<axis>_matches_label::<T>()` substrate primitive + ONE
/// new line inside this compound's body. Every one of the ~20
/// production implementors of the panel picks up the fourth-axis
/// alignment check mechanically at their sole `assert_closed_set_
/// convention_panel::<X>()` call site — no per-implementor test-site
/// authoring, no per-crate test-site drop pathway where 19 sibling
/// call sites carry the check and the 20th forgets. The exact
/// promise `e4a4eba`'s future gain #2 named after
/// `assert_label_matches_serde_serialization` opened the wire-format
/// axis: a workspace-wide panel with byte-identical calling shapes
/// (`assert_X::<T>()`) that composes as freely as its sub-primitives.
///
/// Sibling shape to [`assert_variant_round_trip`] +
/// [`assert_kind_list_matches_closed_set`] +
/// [`assert_two_slots_ambiguous`] +
/// [`assert_single_slot_key_matches_label`] on the tagged-union
/// PARENT axis: the parent-side compound would compose the four
/// parent-side per-axis primitives, this one composes the three
/// child-side per-axis primitives on the child's [`ClosedSet`]
/// surface. Together the two compounds close the "closed-set
/// convention holds across every projection consumers reach for" at
/// two adjacent panels — one per closed-set-carrying enum, one per
/// tagged-union parent.
///
/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
/// three-axis label-surface convention becomes ONE typed theorem
/// provable generically over any
/// `T: ClosedSet + Serialize + Display + PartialEq + Debug` bound
/// rather than THREE hand-authored per-implementor one-line probes
/// held coherent by test-module convention. THEORY.md §II.1
/// invariant 5 (composition preserves proofs) — the three sub-
/// assertions compose structurally through ONE primitive here, so a
/// regression at ONE axis surfaces at the sub-assertion's own
/// panic message rather than as silent drift at every consumer that
/// might otherwise forget to include the axis in its per-site
/// author-time enumeration.
#[track_caller]
pub fn assert_closed_set_convention_panel<T>()
where
    T: tatara_closed_set::ClosedSet
        + serde::Serialize
        + core::fmt::Display
        + PartialEq
        + core::fmt::Debug,
    T::Unknown: core::fmt::Display,
{
    tatara_closed_set::assert_closed_set_well_formed::<T>();
    assert_display_matches_label::<T>();
    assert_label_matches_serde_serialization::<T>();
}

/// TAGGED-UNION CONVENTION PANEL testkit — pins the FULL four-axis
/// tagged-union parent convention (KIND_LIST diagnostic-stability,
/// variant round-trip on the single-slot side, ALL×ALL two-slot
/// ambiguity, wire-key alignment on the single-slot side) at ONE
/// substrate call site per parent.
///
/// Parent-side compound-lift, sibling to
/// [`assert_closed_set_convention_panel`] on the child's
/// [`tatara_closed_set::ClosedSet`] axis. Composes
/// [`assert_kind_list_matches_closed_set`] (no fixture) +
/// [`assert_variant_round_trip`] (`single_slot`) +
/// [`assert_two_slots_ambiguous`] (`two_slot`) +
/// [`assert_single_slot_key_matches_label`] (`single_slot`).
///
/// Every one of the four production `.variant()` parents on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) publishes the four-axis
/// convention through the shared substrate-wide attribute-set:
/// `#[derive(DeriveClosedSet)]` on the addressing `Kind`,
/// `declare_tagged_union_impls!` for the resolver+selector+trait
/// triple, `#[serde(rename_all = "camelCase")]` +
/// `#[serde(default, skip_serializing_if = "Option::is_none")]` on
/// every tagged-union slot. Pre-lift each production site
/// hand-authored FOUR sibling per-axis tests (`X_kind_round_trips_through_variant_kind`
/// / `X_kind_list_matches_ClosedSet_labels` /
/// `X_two_slots_are_ambiguous` /
/// `X_kind_as_str_matches_field_name`) that each restated the
/// SAME `crate::tagged_union::assert_<axis>::<T, _>(fixture)`
/// invocation with only the axis name + fixture arity varying
/// between siblings. Post-lift each site's four per-axis sibling
/// tests can collapse to ONE
/// `assert_tagged_union_convention_panel::<T, _, _>(
/// single_slot_X, two_slot_X)` invocation whose body IS the
/// four-axis composition dispatched through the substrate
/// primitive here.
///
/// The two closures stay per-site — every one of the four
/// production parents already owns a `single_slot_X(k) -> Parent`
/// / `two_slot_X(a, b) -> Parent` pair, and the substrate-local
/// `{single,two}_slot_*_probe` peers (siblings to the wire-key
/// sweep's substrate-local probes) let the substrate-wide sweep
/// below bind through the compound without reaching across the
/// per-crate test-module boundaries. Lifting the two closures
/// into the primitive would collapse the per-site construction
/// knowledge that stays deliberately local — the closure IS the
/// "populate slot k" / "populate the (a, b) pair" ground truth
/// for the parent's field structure.
///
/// Bounds are the strict union of the four sub-assertions' bounds:
/// [`assert_kind_list_matches_closed_set`] requires
/// `T: TaggedUnion`; [`assert_variant_round_trip`] requires
/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
/// + `F: Fn(T::Kind) -> T`; [`assert_two_slots_ambiguous`] requires
/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
/// + `T::Error: PartialEq + Debug` + `F: Fn(T::Kind, T::Kind) -> T`;
/// [`assert_single_slot_key_matches_label`] requires
/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
/// + `F: Fn(T::Kind) -> T`. The union
/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
/// + `T::Error: PartialEq + Debug` + `F1: Fn(T::Kind) -> T`
/// + `F2: Fn(T::Kind, T::Kind) -> T` is what every one of the four
/// production parents already satisfies through the shared
/// substrate-wide impls — any implementor that fails the compound's
/// bounds would ALSO fail the individual sub-assertions' bounds,
/// so the compound doesn't shrink the reachable set of
/// implementors relative to hand-authoring the four sibling calls.
/// The `single_slot` closure is dispatched to
/// [`assert_variant_round_trip`] by reference so the compound can
/// re-dispatch it to [`assert_single_slot_key_matches_label`] by
/// value on the final call — a caller passes ONE `Fn(T::Kind) -> T`
/// factory (not `FnOnce`) at the two axes that need it.
///
/// `#[track_caller]` on both the compound and each sub-primitive,
/// so a sub-assertion panic surfaces at the compound's caller site
/// with the failing axis's exact panic-message substring
/// (e.g. "TaggedUnion KIND_LIST drift", "select→variant_kind
/// round-trip failed", "should resolve Ambiguous", "wire-key
/// drift"). The four sub-assertions stay independently callable —
/// a future parent that publishes only three of the four axes (a
/// wire-format-less runtime parent, e.g., or an
/// ambiguity-less parent whose `.variant()` short-circuits on
/// the first populated slot) still binds through the sibling
/// primitives individually.
///
/// A future FIFTH parent-side projection (e.g. a
/// `two_slots_have_stable_diagnostic` axis if the ambiguity error
/// gains a per-parent operator-facing message, or a
/// `variant_kind_stays_stable_across_generation` axis if the
/// resolver's iteration order becomes load-bearing) lands as ONE
/// new `assert_<axis>::<T, _>(...)` substrate primitive + ONE new
/// line inside this compound's body. Every one of the four
/// production parents picks up the fifth-axis alignment check
/// mechanically at their sole
/// `assert_tagged_union_convention_panel::<T, _, _>(single_slot,
/// two_slot)` call site — no per-parent test-site authoring, no
/// per-crate test-site drop pathway where 3 sibling call sites
/// carry the check and the 4th forgets. The exact promise the
/// child-side [`assert_closed_set_convention_panel`] compound's
/// docstring named on the child axis, extended here to the parent
/// axis: a workspace-wide panel with byte-identical calling shapes
/// (`assert_<compound>::<T, _, _>(single_slot, two_slot)`) that
/// composes as freely as its sub-primitives.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
/// error, so its projection shape diverges from the four
/// Empty-projecting parents. Same reasoning as [`resolve_or_err`]'s
/// / [`assert_variant_round_trip`]'s / [`assert_two_slots_ambiguous`]'s
/// / [`assert_single_slot_key_matches_label`]'s exclusions.
///
/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
/// four-axis parent-side tagged-union convention becomes ONE typed
/// theorem provable generically over any
/// `T: TaggedUnion + Serialize` bound rather than FOUR
/// hand-authored per-parent tests held coherent by test-module
/// convention. THEORY.md §II.1 invariant 5 (composition preserves
/// proofs) — the four sub-assertions compose structurally through
/// ONE primitive here, so a regression at ONE axis surfaces at the
/// sub-assertion's own panic message rather than as silent drift
/// at every parent that might otherwise forget to include the
/// axis in its per-site author-time enumeration.
#[track_caller]
pub fn assert_tagged_union_convention_panel<T, F1, F2>(single_slot: F1, two_slot: F2)
where
    T: TaggedUnion + serde::Serialize,
    T::Kind: PartialEq + std::fmt::Debug,
    T::Error: PartialEq + std::fmt::Debug,
    F1: Fn(T::Kind) -> T,
    F2: Fn(T::Kind, T::Kind) -> T,
{
    assert_kind_list_matches_closed_set::<T>();
    assert_variant_round_trip::<T, _>(&single_slot);
    assert_two_slots_ambiguous::<T, _>(two_slot);
    assert_single_slot_key_matches_label::<T, _>(single_slot);
}

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

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum V {
        A,
        B,
        C,
    }

    #[test]
    fn empty_candidate_list_is_none() {
        let r: Result<V, _> = resolve(std::iter::empty());
        assert_eq!(r.unwrap_err(), ResolveError::None);
    }

    #[test]
    fn all_none_is_none() {
        let r: Result<V, _> = resolve([None, None, None]);
        assert_eq!(r.unwrap_err(), ResolveError::None);
    }

    #[test]
    fn single_some_is_resolved_regardless_of_position() {
        assert_eq!(resolve([Some(V::A), None, None]).unwrap(), V::A);
        assert_eq!(resolve([None, Some(V::B), None]).unwrap(), V::B);
        assert_eq!(resolve([None, None, Some(V::C)]).unwrap(), V::C);
    }

    #[test]
    fn two_or_more_some_is_many() {
        assert_eq!(
            resolve([Some(V::A), Some(V::B), None]).unwrap_err(),
            ResolveError::Many
        );
        assert_eq!(
            resolve([Some(V::A), None, Some(V::C)]).unwrap_err(),
            ResolveError::Many
        );
        assert_eq!(
            resolve([None, Some(V::B), Some(V::C)]).unwrap_err(),
            ResolveError::Many
        );
        assert_eq!(
            resolve([Some(V::A), Some(V::B), Some(V::C)]).unwrap_err(),
            ResolveError::Many
        );
    }

    /// Short-circuit invariant: once `Many` is decided, the sweep does
    /// NOT inspect further candidates. Encode it as a side-effect probe.
    #[test]
    fn many_short_circuits_after_second_some() {
        let mut visited = 0usize;
        let candidates = (0..4).map(|i| {
            visited += 1;
            // first two are Some, the rest would be Some too if we got there.
            Some(i)
        });
        // We can't actually consume `visited` here because it's borrowed in
        // the closure — fold the count via the resolver's short-circuit.
        let _ = resolve(candidates);
        // The resolver evaluates the iterator lazily up to the second
        // Some — index 0 (found = Some(0)), index 1 (Many → return).
        assert_eq!(visited, 2);
    }

    /// The helper is value-agnostic — works with borrowed enum-view
    /// types matching the actual on-the-typescape callsites.
    #[test]
    fn works_with_borrowed_enum_view() {
        #[derive(Debug, PartialEq)]
        enum View<'a> {
            X(&'a u32),
            Y(&'a String),
        }
        let x = 7u32;
        let r = resolve([Some(View::X(&x)), None]).unwrap();
        assert_eq!(r, View::X(&7));
    }

    /// Local sibling-shaped carrier used to pin the trait +
    /// [`resolve_or_err`] dispatch without depending on the
    /// crate's real error types.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum E {
        Empty(&'static str),
        Ambiguous,
    }

    impl TaggedUnionError for E {
        fn empty(kinds: &'static str) -> Self {
            E::Empty(kinds)
        }
        fn ambiguous() -> Self {
            E::Ambiguous
        }
    }

    /// Four-outcome truth table at the compound-lift boundary.
    /// Pins that the two failure arms of [`resolve`] project onto
    /// the trait's two typed constructors byte-identically, and
    /// that the Ok arm falls through untouched.
    #[test]
    fn resolve_or_err_dispatches_each_arm_through_the_trait() {
        const KINDS: &str = "a/b/c";

        assert_eq!(
            resolve_or_err::<V, E>([Some(V::A), None, None], KINDS).unwrap(),
            V::A
        );
        assert_eq!(
            resolve_or_err::<V, E>([None, Some(V::B), None], KINDS).unwrap(),
            V::B
        );

        assert_eq!(
            resolve_or_err::<V, E>([None, None, None], KINDS).unwrap_err(),
            E::Empty(KINDS)
        );

        assert_eq!(
            resolve_or_err::<V, E>([Some(V::A), Some(V::B), None], KINDS).unwrap_err(),
            E::Ambiguous
        );
    }

    /// The trait's Empty arm carries the &'static str the caller
    /// hands `resolve_or_err`, verbatim — a rename at the caller's
    /// `KINDS` constant reaches the diagnostic surface intact.
    #[test]
    fn resolve_or_err_empty_carries_the_caller_kinds_verbatim() {
        const KINDS_ALPHA: &str = "alpha/beta";
        const KINDS_GAMMA: &str = "gamma/delta/epsilon";

        assert_eq!(
            resolve_or_err::<V, E>([None, None], KINDS_ALPHA).unwrap_err(),
            E::Empty(KINDS_ALPHA)
        );
        assert_eq!(
            resolve_or_err::<V, E>([None, None, None], KINDS_GAMMA).unwrap_err(),
            E::Empty(KINDS_GAMMA)
        );
    }

    /// The compound-lift preserves [`resolve`]'s short-circuit at
    /// the Many arm — a third-and-later candidate is not
    /// inspected once the second populated entry is seen.
    #[test]
    fn resolve_or_err_short_circuits_on_many() {
        let mut visited = 0usize;
        let candidates = (0..4).map(|i| {
            visited += 1;
            Some(i)
        });
        let _ = resolve_or_err::<i32, E>(candidates, "irrelevant");
        assert_eq!(visited, 2);
    }

    // -------------------------------------------------------------------
    // `declare_tagged_union_error!` macro-emitted carrier — pins the
    // shape a fifth sibling would land through the macro instead of
    // hand-rolling the enum + `impl TaggedUnionError` block.
    // -------------------------------------------------------------------

    crate::declare_tagged_union_error! {
        pub(super) MacroEmittedError,
        empty = "test carrier has no variant set (one of {0} required)",
        ambiguous = "test carrier has multiple variants set; exactly one required",
    }

    /// The macro-emitted carrier's [`TaggedUnionError`] impl dispatches
    /// the same four-outcome truth table [`resolve_or_err`] pins for a
    /// hand-rolled carrier — pins that swapping a hand-rolled carrier
    /// for a macro-emitted one preserves the compound-lift's projection
    /// byte-identically.
    #[test]
    fn macro_emitted_carrier_projects_through_resolve_or_err() {
        const KINDS: &str = "one/two/three";

        assert_eq!(
            resolve_or_err::<V, MacroEmittedError>([Some(V::A), None, None], KINDS).unwrap(),
            V::A
        );
        assert_eq!(
            resolve_or_err::<V, MacroEmittedError>([None, None, None], KINDS).unwrap_err(),
            MacroEmittedError::Empty(KINDS)
        );
        assert_eq!(
            resolve_or_err::<V, MacroEmittedError>([Some(V::A), Some(V::B), None], KINDS)
                .unwrap_err(),
            MacroEmittedError::Ambiguous
        );
    }

    /// The macro-emitted carrier's `#[error(...)]` messages render the
    /// two operator-facing diagnostic strings the caller handed the
    /// macro, verbatim — a rename at the caller's literal reaches the
    /// operator diagnostic surface intact.
    #[test]
    fn macro_emitted_carrier_display_renders_caller_literals_verbatim() {
        assert_eq!(
            MacroEmittedError::Empty("alpha/beta").to_string(),
            "test carrier has no variant set (one of alpha/beta required)",
        );
        assert_eq!(
            MacroEmittedError::Ambiguous.to_string(),
            "test carrier has multiple variants set; exactly one required",
        );
    }

    /// The macro-emitted carrier is `Copy` — a substrate-wide promise
    /// pinned by the macro's `#[derive(..., Copy, ...)]` header so a
    /// consumer treating the carrier as a value type (memcpy-cheap
    /// return, `.copied()` on an `Option<&E>`) stays valid across every
    /// carrier the macro emits.
    #[test]
    fn macro_emitted_carrier_is_copy() {
        fn assert_copy<T: Copy>() {}
        assert_copy::<MacroEmittedError>();
    }

    // -------------------------------------------------------------------
    // `TaggedUnion` trait — declarative surface pinning the
    // (Kind, Error, KIND_LIST) triple. `assert_kind_list_matches_closed_set`
    // is the generic diagnostic-stability testkit primitive shared by
    // every implementor's `_error_empty_lists_every_kind_in_canonical_order`
    // site.
    // -------------------------------------------------------------------

    /// Local sibling-shaped Kind enum used to pin the trait's
    /// diagnostic-stability primitive without depending on the crate's
    /// four production tagged unions. Uses [`tatara_closed_set::DeriveClosedSet`]
    /// so `<Self as ClosedSet>::labels_joined("/")` reaches the same
    /// substrate composition the four production sites bind through.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
    #[closed_set(via = "as_str", generate_unknown, display)]
    enum LocalKind {
        Alpha,
        Beta,
        Gamma,
    }

    impl LocalKind {
        const ALL: [Self; 3] = [Self::Alpha, Self::Beta, Self::Gamma];
        const fn as_str(self) -> &'static str {
            match self {
                Self::Alpha => "alpha",
                Self::Beta => "beta",
                Self::Gamma => "gamma",
            }
        }
    }

    /// Local parent type — impls [`TaggedUnion`] with a `KIND_LIST`
    /// literal that matches the canonical `<LocalKind as
    /// ClosedSet>::labels_joined("/")` projection. Carries three
    /// `Option<u32>` slots so the substrate-primitive
    /// [`TaggedUnion::variant`] default method can be exercised
    /// directly on a sibling-shaped-but-crate-local parent, isolated
    /// from the four production tagged unions.
    ///
    /// Derives [`serde::Serialize`] with `skip_serializing_if =
    /// "Option::is_none"` on every slot so the wire-format primitive
    /// [`assert_single_slot_key_matches_label`] can be exercised
    /// directly against the sibling-shaped scaffold — mirrors the
    /// `#[serde(default, skip_serializing_if = "Option::is_none")]`
    /// annotation every one of the four production tagged unions
    /// carries on its own slots.
    #[derive(Default, serde::Serialize)]
    struct LocalParent {
        #[serde(skip_serializing_if = "Option::is_none")]
        alpha: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        beta: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        gamma: Option<u32>,
    }

    /// Borrowed-view of a populated slot on [`LocalParent`] — the
    /// return type of [`LocalKind::select`] and the substrate-primitive
    /// [`TaggedUnion::variant`] default on `LocalParent`.
    #[derive(Debug, PartialEq)]
    enum LocalVariant<'a> {
        Alpha(&'a u32),
        Beta(&'a u32),
        Gamma(&'a u32),
    }

    impl VariantSelector<LocalParent> for LocalKind {
        type Variant<'a> = LocalVariant<'a>;
        fn select<'a>(self, parent: &'a LocalParent) -> Option<LocalVariant<'a>>
        where
            Self: 'a,
        {
            match self {
                Self::Alpha => parent.alpha.as_ref().map(LocalVariant::Alpha),
                Self::Beta => parent.beta.as_ref().map(LocalVariant::Beta),
                Self::Gamma => parent.gamma.as_ref().map(LocalVariant::Gamma),
            }
        }
    }

    impl VariantKind<LocalKind> for LocalVariant<'_> {
        fn variant_kind(&self) -> LocalKind {
            match self {
                Self::Alpha(_) => LocalKind::Alpha,
                Self::Beta(_) => LocalKind::Beta,
                Self::Gamma(_) => LocalKind::Gamma,
            }
        }
    }

    crate::declare_tagged_union_error! {
        pub(super) LocalParentError,
        empty = "local carrier has no variant set (one of {0} required)",
        ambiguous = "local carrier has multiple variants set; exactly one required",
    }

    impl TaggedUnion for LocalParent {
        type Kind = LocalKind;
        type Error = LocalParentError;
        const KIND_LIST: &'static str = "alpha/beta/gamma";
    }

    /// The testkit primitive resolves the canonical join of every
    /// `LocalKind` variant's label against the trait's `KIND_LIST`
    /// constant byte-identically — the four production sites bind
    /// through this exact dispatch. The Ok arm is the "no drift"
    /// outcome; a divergence surfaces as a labeled assertion failure.
    #[test]
    fn assert_kind_list_matches_closed_set_accepts_coherent_impl() {
        assert_kind_list_matches_closed_set::<LocalParent>();
    }

    /// The testkit primitive is a `#[track_caller]` compound-lift:
    /// a drift between `<T::Kind as ClosedSet>::labels_joined("/")`
    /// and `T::KIND_LIST` fails the assertion at the caller's site,
    /// not inside the primitive body. Pin the failing case with a
    /// local parent whose `KIND_LIST` is deliberately mis-authored
    /// (a variant reorder), so a regression that drops the drift
    /// detection fails-loudly here.
    #[test]
    #[should_panic(expected = "TaggedUnion KIND_LIST drift")]
    fn assert_kind_list_matches_closed_set_rejects_drifted_impl() {
        struct Drifted;
        // The `TaggedUnion` trait bounds `Kind: VariantSelector<Self>`
        // with `Variant<'a>: VariantKind<Self>`; the drift test only
        // exercises `assert_kind_list_matches_closed_set` (which reaches
        // the (Kind, KIND_LIST) pair, not the sweep body), so reusing
        // the sibling `LocalVariant<'a>` (with its already-load-bearing
        // `impl VariantKind<LocalKind>`) + always-`None` `select`
        // satisfies both bounds without wiring a real projection.
        impl VariantSelector<Drifted> for LocalKind {
            type Variant<'a> = LocalVariant<'a>;
            fn select<'a>(self, _: &'a Drifted) -> Option<LocalVariant<'a>>
            where
                Self: 'a,
            {
                None
            }
        }
        impl TaggedUnion for Drifted {
            type Kind = LocalKind;
            type Error = LocalParentError;
            // Deliberate drift — canonical join is "alpha/beta/gamma".
            const KIND_LIST: &'static str = "beta/alpha/gamma";
        }
        assert_kind_list_matches_closed_set::<Drifted>();
    }

    /// Every one of the four production `.variant()` sites on
    /// `ProcessSpec` impls [`TaggedUnion`] with `KIND_LIST` reaching
    /// the substrate primitive `assert_kind_list_matches_closed_set`
    /// coherently. Sweep every production implementor at ONE
    /// substrate boundary so a regression that drifts a production
    /// site's `KIND_LIST` (or renames a `Kind` variant without
    /// updating the constant) fails BOTH at the per-crate test site
    /// AND at this substrate-wide sweep — no per-implementor test
    /// site can drop the check silently.
    #[test]
    fn every_production_tagged_union_binds_through_the_testkit_primitive() {
        assert_kind_list_matches_closed_set::<crate::intent::Intent>();
        assert_kind_list_matches_closed_set::<crate::encapsulates::EncapsulationKind>();
        assert_kind_list_matches_closed_set::<crate::export::ArtifactSource>();
        assert_kind_list_matches_closed_set::<crate::export::VectorChannel>();
    }

    /// Every one of the four production `.variant()` sites on
    /// `ProcessSpec` binds through the wire-key primitive
    /// [`assert_single_slot_key_matches_label`] coherently — every
    /// per-site `single_slot_X(k)` factory serializes to a JSON object
    /// with EXACTLY ONE key whose name equals `k.label()` (delegating
    /// to each Kind's inherent `as_str`, matching the parent's serde
    /// `rename_all = "camelCase"` projection). Sweep every production
    /// implementor at ONE substrate boundary so a regression that
    /// drifts a production site's `single_slot_X` factory (populates
    /// the wrong slot; leaks residual slots between calls) OR the
    /// parent's field-to-kind alignment (`as_str` returns "receipts"
    /// but the field is named `receipt`) fails BOTH at the per-crate
    /// test site AND at this substrate-wide sweep — no per-implementor
    /// test site can drop the check silently.
    #[test]
    fn every_production_tagged_union_binds_through_the_wire_key_testkit_primitive() {
        assert_single_slot_key_matches_label::<crate::intent::Intent, _>(single_slot_intent_probe);
        assert_single_slot_key_matches_label::<crate::encapsulates::EncapsulationKind, _>(
            single_slot_encapsulation_kind_probe,
        );
        assert_single_slot_key_matches_label::<crate::export::ArtifactSource, _>(
            single_slot_artifact_source_probe,
        );
        assert_single_slot_key_matches_label::<crate::export::VectorChannel, _>(
            single_slot_vector_channel_probe,
        );
    }

    /// The parent-side four-axis compound-lift dispatches Ok on a
    /// coherent implementor — the [`LocalParent`] scaffold publishes
    /// every axis (`TaggedUnion` via
    /// [`crate::declare_tagged_union_error`]-emitted `LocalParentError`
    /// + Serialize via `#[derive(serde::Serialize)]` +
    /// `LocalKind: PartialEq + Debug` +
    /// `LocalParentError: PartialEq + Debug`), matching the
    /// substrate-wide four-axis convention every one of the four
    /// production parents carries. The Ok arm is the "no drift"
    /// outcome; a divergence at ANY sub-assertion's composition
    /// inside the compound (accidentally dropped, silently reordered,
    /// or short-circuited) surfaces at the sub-primitive's own
    /// panic message (each sub-primitive is `#[track_caller]`), and
    /// the per-axis failing arms are pinned by the sibling
    /// `#[should_panic]` probes already at the per-axis primitive
    /// layer (`assert_kind_list_matches_closed_set_rejects_drifted_impl`,
    /// `assert_variant_round_trip_rejects_factory_that_leaves_slot_empty`,
    /// `assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot`,
    /// `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`).
    /// Re-authoring per-axis drift probes at the compound layer
    /// would restate the SAME four axis-typed contracts through a
    /// compound wrapper without adding a new gate.
    #[test]
    fn assert_tagged_union_convention_panel_accepts_coherent_local_impl() {
        fn single_slot(k: LocalKind) -> LocalParent {
            match k {
                LocalKind::Alpha => LocalParent {
                    alpha: Some(11),
                    ..Default::default()
                },
                LocalKind::Beta => LocalParent {
                    beta: Some(22),
                    ..Default::default()
                },
                LocalKind::Gamma => LocalParent {
                    gamma: Some(33),
                    ..Default::default()
                },
            }
        }
        fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
            let mut p = LocalParent::default();
            for k in [a, b] {
                match k {
                    LocalKind::Alpha => p.alpha = Some(11),
                    LocalKind::Beta => p.beta = Some(22),
                    LocalKind::Gamma => p.gamma = Some(33),
                }
            }
            p
        }
        assert_tagged_union_convention_panel::<LocalParent, _, _>(single_slot, two_slot);
    }

    /// Every one of the four production `.variant()` parents on
    /// `ProcessSpec` binds through the four-axis convention-panel
    /// primitive [`assert_tagged_union_convention_panel`] coherently.
    /// Sweep every production parent at ONE substrate boundary so a
    /// regression that (a) drops ANY of the four sub-assertions from
    /// the compound's body, (b) reorders them in a way that skips
    /// one on Ok, (c) silently binds the compound against a
    /// hollowed-out sub-assertion body, or (d) drifts a substrate-
    /// local `{single,two}_slot_*_probe` fixture (populates the
    /// wrong slot; leaks residual slots between calls; the `.or()`
    /// composition drops a slot on the two-slot side) fails BOTH at
    /// the per-crate test site AND at this substrate-wide sweep.
    ///
    /// Pinned in lock-step with the sibling
    /// `every_production_tagged_union_binds_through_the_testkit_primitive`
    /// (KIND_LIST axis) and
    /// `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
    /// (wire-key axis) sweeps — every parent enumerated below is a
    /// member of BOTH sibling sweeps (their bounds are strict
    /// subsets of the compound's `T: TaggedUnion + Serialize` +
    /// `T::Kind: PartialEq + Debug` + `T::Error: PartialEq + Debug`
    /// bound), and every parent additionally publishes both a
    /// substrate-local `single_slot_*_probe` and a
    /// substrate-local `two_slot_*_probe` peer above. Post-sweep the
    /// substrate-wide four-axis parent-side convention-panel
    /// discipline is a property of the workspace, not a per-file
    /// convention — even before any per-site test-body sweep
    /// collapses the four per-parent sibling tests into ONE compound
    /// call each.
    #[test]
    fn every_production_tagged_union_binds_through_the_convention_panel_testkit_primitive() {
        assert_tagged_union_convention_panel::<crate::intent::Intent, _, _>(
            single_slot_intent_probe,
            two_slot_intent_probe,
        );
        assert_tagged_union_convention_panel::<crate::encapsulates::EncapsulationKind, _, _>(
            single_slot_encapsulation_kind_probe,
            two_slot_encapsulation_kind_probe,
        );
        assert_tagged_union_convention_panel::<crate::export::ArtifactSource, _, _>(
            single_slot_artifact_source_probe,
            two_slot_artifact_source_probe,
        );
        assert_tagged_union_convention_panel::<crate::export::VectorChannel, _, _>(
            single_slot_vector_channel_probe,
            two_slot_vector_channel_probe,
        );
    }

    /// The Display / label alignment primitive dispatches Ok on a
    /// coherent implementor — the [`LocalKind`] scaffold derives
    /// `Display` from `label` via `#[closed_set(via = "as_str",
    /// display)]`, matching the substrate-wide derive shape every
    /// production implementor across the crate carries. The Ok arm
    /// is the "no drift" outcome; a divergence surfaces as a labeled
    /// assertion failure at the caller site (this test's own line).
    #[test]
    fn assert_display_matches_label_accepts_coherent_impl() {
        assert_display_matches_label::<LocalKind>();
    }

    /// A local closed-set scaffold whose `Display` deliberately
    /// diverges from `label` — pins the failing arm of the primitive.
    /// The `#[closed_set(via = "as_str")]` attribute WITHOUT `display`
    /// leaves the `Display` impl uncovered by the derive, and the
    /// hand-authored `impl Display` below emits a suffixed rendering
    /// that no `label` projection returns. A regression that drops
    /// the alignment assertion inside
    /// [`assert_display_matches_label`] fails-loudly at this
    /// `#[should_panic]` probe before it can silently thread through
    /// the 29 production `X_display_matches_as_str` sites.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
    #[closed_set(via = "as_str", generate_unknown)]
    enum DisplayDriftKind {
        Alpha,
        Beta,
    }

    impl DisplayDriftKind {
        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
        const fn as_str(self) -> &'static str {
            match self {
                Self::Alpha => "alpha",
                Self::Beta => "beta",
            }
        }
    }

    impl std::fmt::Display for DisplayDriftKind {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            // Deliberate drift — Display suffixes the label with a
            // marker no `label` projection returns.
            write!(f, "{}!", self.as_str())
        }
    }

    #[test]
    #[should_panic(expected = "Display drifted from ClosedSet::label")]
    fn assert_display_matches_label_rejects_drifted_impl() {
        assert_display_matches_label::<DisplayDriftKind>();
    }

    /// Every closed-set enum across `tatara-process` that carried a
    /// hand-rolled `X_display_matches_as_str` test pre-lift now binds
    /// through the substrate primitive at ONE call site each.  This
    /// substrate-wide sweep pins every production Display-alignment
    /// consumer at ONE boundary so a per-crate test-site drop cannot
    /// silently disable the check — the sweep here catches the drift
    /// even when the per-site test body is removed. Mirrors the
    /// `every_production_tagged_union_binds_through_the_testkit_primitive`
    /// and `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
    /// sibling sweeps on the (`KIND_LIST` slash-join, wire-key)
    /// axes; this one closes the (`Display` byte-identity) axis.
    #[test]
    fn every_production_display_impl_binds_through_the_testkit_primitive() {
        assert_display_matches_label::<crate::allocation::AllocationPhase>();
        assert_display_matches_label::<crate::boundary::ConditionKind>();
        assert_display_matches_label::<crate::classification::Arity>();
        assert_display_matches_label::<crate::classification::CalmClassification>();
        assert_display_matches_label::<crate::classification::ConvergencePointType>();
        assert_display_matches_label::<crate::classification::DataClassification>();
        assert_display_matches_label::<crate::classification::HorizonKind>();
        assert_display_matches_label::<crate::classification::OptimizationDirection>();
        assert_display_matches_label::<crate::classification::SubstrateType>();
        assert_display_matches_label::<crate::compliance::VerificationPhase>();
        assert_display_matches_label::<crate::encapsulates::EncapsulationMode>();
        assert_display_matches_label::<crate::encapsulates::EncapsulationTarget>();
        assert_display_matches_label::<crate::export::ArtifactKind>();
        assert_display_matches_label::<crate::export::ChannelKind>();
        assert_display_matches_label::<crate::export::ExportTrigger>();
        assert_display_matches_label::<crate::export::ReportFormat>();
        assert_display_matches_label::<crate::export::ReportPayloadShape>();
        assert_display_matches_label::<crate::intent::IntentKind>();
        assert_display_matches_label::<crate::intent::WorkloadKind>();
        assert_display_matches_label::<crate::lifetime::LifetimeKind>();
        assert_display_matches_label::<crate::lifetime::TeardownPolicy>();
        assert_display_matches_label::<crate::lifetime_clock::AutoTerminateKind>();
        assert_display_matches_label::<crate::lifetime_clock::TerminateReasonKind>();
        assert_display_matches_label::<crate::matrix::SelectStrategyKind>();
        assert_display_matches_label::<crate::pool::MemberState>();
        assert_display_matches_label::<crate::pool::PoolPhase>();
        assert_display_matches_label::<crate::pool::ReplacementPolicy>();
        assert_display_matches_label::<crate::pool::ReturnPolicy>();
        assert_display_matches_label::<crate::signal::SighupStrategy>();
        assert_display_matches_label::<crate::spec::MustReachPhase>();
    }

    /// Local closed-set scaffold whose serde `rename_all = "lowercase"`
    /// projection matches its `via = "as_str"` label byte-identically —
    /// pins the Ok arm of the wire-format primitive. Every production
    /// implementor across the crate carries the substrate-wide
    /// `#[closed_set(via = "as_str")]` + `#[serde(rename_all = ...)]`
    /// pair whose alignment this scaffold pins on the sibling-shaped
    /// local surface.
    #[derive(
        Clone,
        Copy,
        Debug,
        PartialEq,
        Eq,
        Hash,
        serde::Serialize,
        tatara_closed_set::DeriveClosedSet,
    )]
    #[serde(rename_all = "lowercase")]
    #[closed_set(via = "as_str", generate_unknown)]
    enum SerdeAlignedKind {
        Alpha,
        Beta,
    }

    impl SerdeAlignedKind {
        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
        const fn as_str(self) -> &'static str {
            match self {
                Self::Alpha => "alpha",
                Self::Beta => "beta",
            }
        }
    }

    #[test]
    fn assert_label_matches_serde_serialization_accepts_coherent_impl() {
        assert_label_matches_serde_serialization::<SerdeAlignedKind>();
    }

    /// A local closed-set scaffold whose serde output deliberately
    /// diverges from `label` — pins the failing arm of the wire-format
    /// primitive. The `#[serde(rename_all = "UPPERCASE")]` projection
    /// emits uppercase JSON strings while the `via = "as_str"` label
    /// stays lowercase. A regression that drops the alignment assertion
    /// inside [`assert_label_matches_serde_serialization`] fails-loudly
    /// at this `#[should_panic]` probe before it can silently thread
    /// through the 20 production `X_as_str_matches_serde` sites.
    #[derive(
        Clone,
        Copy,
        Debug,
        PartialEq,
        Eq,
        Hash,
        serde::Serialize,
        tatara_closed_set::DeriveClosedSet,
    )]
    #[serde(rename_all = "UPPERCASE")]
    #[closed_set(via = "as_str", generate_unknown)]
    enum SerdeDriftKind {
        Alpha,
        Beta,
    }

    impl SerdeDriftKind {
        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
        const fn as_str(self) -> &'static str {
            match self {
                Self::Alpha => "alpha",
                Self::Beta => "beta",
            }
        }
    }

    #[test]
    #[should_panic(expected = "serde output drifted from ClosedSet::label")]
    fn assert_label_matches_serde_serialization_rejects_drifted_impl() {
        assert_label_matches_serde_serialization::<SerdeDriftKind>();
    }

    /// Local closed-set scaffold whose ALL THREE axes of the label-
    /// surface convention align by construction — pins the Ok arm of
    /// the compound-panel primitive.
    ///
    /// `#[serde(rename_all = "lowercase")]` matches the `via = "as_str"`
    /// labels byte-identically (the serde-alignment axis). The
    /// `display` sub-attribute on `#[closed_set(via = "as_str",
    /// display)]` derives `impl Display` from the same `as_str`
    /// projection (the Display-alignment axis). The `generate_unknown`
    /// sub-attribute emits the `T::Unknown` carrier the round-trip
    /// axis's `parse_label` returns on unknown input. Together these
    /// three attributes stamp the substrate-wide derive shape every
    /// production 3-axis-panel consumer carries; a caller that lands
    /// through this scaffold satisfies EVERY bound the compound's
    /// where-clause names.
    ///
    /// Peer to the sibling per-axis fixtures [`LocalKind`] (Display
    /// axis, no serde) and [`SerdeAlignedKind`] (serde axis, no
    /// Display) on the label-surface primitive family; this fixture
    /// closes the diagonal by carrying both attribute-sets at once,
    /// so a regression at ANY sub-assertion's composition inside the
    /// compound (the compound accidentally dropping the well-formed
    /// call, silently reordering the three calls, wrapping them in a
    /// short-circuit that skips the middle one on Ok, …) fails the
    /// compound's happy-path pin below rather than as silent drift at
    /// every 3-axis consumer.
    #[derive(
        Clone,
        Copy,
        Debug,
        PartialEq,
        Eq,
        Hash,
        serde::Serialize,
        tatara_closed_set::DeriveClosedSet,
    )]
    #[serde(rename_all = "lowercase")]
    #[closed_set(via = "as_str", generate_unknown, display)]
    enum PanelAlignedKind {
        Alpha,
        Beta,
    }

    impl PanelAlignedKind {
        const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
        const fn as_str(self) -> &'static str {
            match self {
                Self::Alpha => "alpha",
                Self::Beta => "beta",
            }
        }
    }

    /// The compound-panel primitive dispatches Ok on a coherent
    /// implementor — [`PanelAlignedKind`] carries every attribute the
    /// substrate-wide 3-axis derive shape publishes, so all three
    /// sub-assertions the compound composes (well-formed, Display /
    /// label, serde / label) pass by construction. The Ok arm is the
    /// "no drift on any axis" outcome; a divergence at any single
    /// sub-assertion surfaces as that sub-assertion's own labeled
    /// panic message (with the caller-attributed line via
    /// `#[track_caller]` on both the compound and its sub-
    /// primitives), NOT as a silent pass.
    ///
    /// The per-axis failing arms are pinned by the sibling per-axis
    /// #[should_panic] probes above:
    ///   - the round-trip axis's failing arm is pinned by
    ///     [`tatara_closed_set::assert_closed_set_well_formed`]'s own
    ///     `#[should_panic]` probe in the `tatara-closed-set` crate;
    ///   - the Display axis's failing arm is pinned by
    ///     [`assert_display_matches_label_rejects_drifted_impl`] on
    ///     [`DisplayDriftKind`];
    ///   - the serde axis's failing arm is pinned by
    ///     [`assert_label_matches_serde_serialization_rejects_drifted_impl`]
    ///     on [`SerdeDriftKind`].
    /// Each per-axis drift fixture already surfaces its axis's exact
    /// panic-message substring, so re-authoring per-axis
    /// `#[should_panic]` probes at the compound layer would restate
    /// the SAME three axis-typed contracts through a compound
    /// wrapper — one more copy of the same three pins, not a new
    /// gate. The compound's happy-path pin here suffices to verify
    /// the composition doesn't lose ANY sub-assertion (a regression
    /// that swallows one axis silently would still fail the sibling
    /// sub-assertion's own drift probe on the drift fixture).
    #[test]
    fn assert_closed_set_convention_panel_accepts_coherent_impl() {
        assert_closed_set_convention_panel::<PanelAlignedKind>();
    }

    /// Every closed-set enum across `tatara-process` that publishes
    /// ALL THREE axes of the label-surface convention (well-formed +
    /// Display-alignment + serde-alignment) now binds through the
    /// substrate compound-panel primitive at ONE call site each in
    /// this sweep. Pinned in lock-step with the sibling
    /// `every_production_serde_serialization_binds_through_the_testkit_primitive`
    /// sweep — every enum enumerated below is a member of BOTH sweeps
    /// (the compound's `T: Serialize + Display + ClosedSet + ...`
    /// bound is a strict superset of `assert_label_matches_serde_
    /// serialization`'s `T: ClosedSet + Serialize + Debug` bound, and
    /// the 20 wire-format consumers all additionally impl Display via
    /// `#[closed_set(via = "as_str", display)]`).
    ///
    /// A regression that (a) drops the compound's `assert_closed_set_
    /// well_formed` dispatch, (b) reorders the three sub-assertions
    /// in a way that skips one on Ok, or (c) silently binds the
    /// compound against a hollowed-out sub-assertion body catches
    /// here at the substrate-wide boundary — the sweep pins every
    /// production 3-axis consumer's compound-panel discipline through
    /// ONE test even before any per-site test-body sweep collapses
    /// the three per-enum sibling tests into ONE compound call each.
    /// Post-sweep the substrate-wide compound-panel discipline is a
    /// property of the workspace, not a per-file convention.
    #[test]
    fn every_production_convention_panel_binds_through_the_testkit_primitive() {
        assert_closed_set_convention_panel::<crate::allocation::AllocationPhase>();
        assert_closed_set_convention_panel::<crate::boundary::ConditionKind>();
        assert_closed_set_convention_panel::<crate::classification::CalmClassification>();
        assert_closed_set_convention_panel::<crate::classification::ConvergencePointType>();
        assert_closed_set_convention_panel::<crate::classification::DataClassification>();
        assert_closed_set_convention_panel::<crate::classification::HorizonKind>();
        assert_closed_set_convention_panel::<crate::classification::OptimizationDirection>();
        assert_closed_set_convention_panel::<crate::classification::SubstrateType>();
        assert_closed_set_convention_panel::<crate::compliance::VerificationPhase>();
        assert_closed_set_convention_panel::<crate::encapsulates::EncapsulationMode>();
        assert_closed_set_convention_panel::<crate::export::ExportTrigger>();
        assert_closed_set_convention_panel::<crate::export::ReportFormat>();
        assert_closed_set_convention_panel::<crate::intent::WorkloadKind>();
        assert_closed_set_convention_panel::<crate::lifetime::TeardownPolicy>();
        assert_closed_set_convention_panel::<crate::pool::MemberState>();
        assert_closed_set_convention_panel::<crate::pool::PoolPhase>();
        assert_closed_set_convention_panel::<crate::pool::ReplacementPolicy>();
        assert_closed_set_convention_panel::<crate::pool::ReturnPolicy>();
        assert_closed_set_convention_panel::<crate::signal::SighupStrategy>();
        assert_closed_set_convention_panel::<crate::spec::MustReachPhase>();
    }

    /// Every closed-set enum across `tatara-process` that carried a
    /// hand-rolled `X_as_str_matches_serde` test pre-lift now binds
    /// through the substrate primitive at ONE call site each. This
    /// substrate-wide sweep pins every production wire-format alignment
    /// consumer at ONE boundary so a per-crate test-site drop cannot
    /// silently disable the check — the sweep here catches the drift
    /// even when the per-site test body is removed. Mirrors the sibling
    /// `every_production_display_impl_binds_through_the_testkit_primitive`
    /// sweep on the (Display byte-identity) axis; this one closes the
    /// (serde JSON-string byte-identity) axis.
    #[test]
    fn every_production_serde_serialization_binds_through_the_testkit_primitive() {
        assert_label_matches_serde_serialization::<crate::allocation::AllocationPhase>();
        assert_label_matches_serde_serialization::<crate::boundary::ConditionKind>();
        assert_label_matches_serde_serialization::<crate::classification::CalmClassification>();
        assert_label_matches_serde_serialization::<crate::classification::ConvergencePointType>();
        assert_label_matches_serde_serialization::<crate::classification::DataClassification>();
        assert_label_matches_serde_serialization::<crate::classification::HorizonKind>();
        assert_label_matches_serde_serialization::<crate::classification::OptimizationDirection>();
        assert_label_matches_serde_serialization::<crate::classification::SubstrateType>();
        assert_label_matches_serde_serialization::<crate::compliance::VerificationPhase>();
        assert_label_matches_serde_serialization::<crate::encapsulates::EncapsulationMode>();
        assert_label_matches_serde_serialization::<crate::export::ExportTrigger>();
        assert_label_matches_serde_serialization::<crate::export::ReportFormat>();
        assert_label_matches_serde_serialization::<crate::intent::WorkloadKind>();
        assert_label_matches_serde_serialization::<crate::lifetime::TeardownPolicy>();
        assert_label_matches_serde_serialization::<crate::pool::MemberState>();
        assert_label_matches_serde_serialization::<crate::pool::PoolPhase>();
        assert_label_matches_serde_serialization::<crate::pool::ReplacementPolicy>();
        assert_label_matches_serde_serialization::<crate::pool::ReturnPolicy>();
        assert_label_matches_serde_serialization::<crate::signal::SighupStrategy>();
        assert_label_matches_serde_serialization::<crate::spec::MustReachPhase>();
    }

    // Substrate-local single-slot factories — mirror the per-site
    // `single_slot_X` test helpers each production site owns, so the
    // substrate-wide sweep above binds through the wire-key primitive
    // without reaching across the per-crate test-module boundaries the
    // per-site helpers are scoped to. The primitive only requires that
    // the addressed slot on the parent is populated; the inner spec's
    // exact field values are irrelevant to the wire-key check.

    fn single_slot_intent_probe(kind: crate::intent::IntentKind) -> crate::intent::Intent {
        use crate::intent::{
            AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, Intent, IntentKind,
            LispIntent, NixIntent, WorkloadKind,
        };
        match kind {
            IntentKind::Nix => Intent {
                nix: Some(NixIntent {
                    flake_ref: "f".into(),
                    attribute: "a".into(),
                    system: None,
                    attic_cache: None,
                    extra_args: vec![],
                    delegate_to_nix_build: false,
                }),
                ..Intent::default()
            },
            IntentKind::Flux => Intent {
                flux: Some(FluxIntent {
                    git_repository: "g".into(),
                    path: "p".into(),
                    git_repository_namespace: None,
                    target_namespace: None,
                    decrypt_sops: true,
                    helm_chart: None,
                    helm_values: None,
                }),
                ..Intent::default()
            },
            IntentKind::Lisp => Intent {
                lisp: Some(LispIntent {
                    source: "()".into(),
                    reader: "tatara-lisp".into(),
                    version: "v1".into(),
                    bindings: std::collections::BTreeMap::new(),
                }),
                ..Intent::default()
            },
            IntentKind::Container => Intent {
                container: Some(ContainerIntent {
                    image: "x".into(),
                    replicas: None,
                    command: vec![],
                    args: vec![],
                    env: std::collections::BTreeMap::new(),
                    workload_kind: WorkloadKind::default(),
                }),
                ..Intent::default()
            },
            IntentKind::Aplicacao => Intent {
                aplicacao: Some(AplicacaoIntent {
                    chart_ref: "x".into(),
                    version: "1".into(),
                    profile: String::new(),
                    values_overlay: serde_json::Value::Null,
                    release_name: None,
                    target_namespace: None,
                    install_timeout: None,
                }),
                ..Intent::default()
            },
            IntentKind::Guest => Intent {
                guest: Some(GuestIntent {
                    spec: serde_json::json!({"name": "x"}),
                    state_dir: None,
                    allow_remote_build: None,
                }),
                ..Intent::default()
            },
        }
    }

    fn single_slot_encapsulation_kind_probe(
        target: crate::encapsulates::EncapsulationTarget,
    ) -> crate::encapsulates::EncapsulationKind {
        use crate::encapsulates::{
            BareWorkload, EncapsulationKind, EncapsulationTarget, ExistingHelmRelease,
            ExistingKustomization,
        };
        match target {
            EncapsulationTarget::ExistingHelmRelease => EncapsulationKind {
                existing_helm_release: Some(ExistingHelmRelease {
                    namespace: "ns".into(),
                    name: "hr".into(),
                    release_name: "rel".into(),
                }),
                ..EncapsulationKind::default()
            },
            EncapsulationTarget::ExistingKustomization => EncapsulationKind {
                existing_kustomization: Some(ExistingKustomization {
                    namespace: "ns".into(),
                    name: "ks".into(),
                }),
                ..EncapsulationKind::default()
            },
            EncapsulationTarget::BareWorkload => {
                let mut sel = std::collections::BTreeMap::new();
                sel.insert("app".into(), "x".into());
                EncapsulationKind {
                    bare_workload: Some(BareWorkload {
                        namespace: "ns".into(),
                        selector: sel,
                    }),
                    ..EncapsulationKind::default()
                }
            }
        }
    }

    fn single_slot_artifact_source_probe(
        kind: crate::export::ArtifactKind,
    ) -> crate::export::ArtifactSource {
        use crate::export::{
            ArtifactKind, ArtifactSource, ProcessSnapshotSource, ReceiptsSource, ReportFormat,
            RunMarkerSource, TestReportSource,
        };
        match kind {
            ArtifactKind::Receipts => ArtifactSource {
                receipts: Some(ReceiptsSource::default()),
                ..ArtifactSource::default()
            },
            ArtifactKind::TestReport => ArtifactSource {
                test_report: Some(TestReportSource {
                    configmap: "cm".into(),
                    key: "k".into(),
                    format: ReportFormat::Junit,
                    namespace: None,
                }),
                ..ArtifactSource::default()
            },
            ArtifactKind::ProcessSnapshot => ArtifactSource {
                process_snapshot: Some(ProcessSnapshotSource::default()),
                ..ArtifactSource::default()
            },
            ArtifactKind::RunMarker => ArtifactSource {
                run_marker: Some(RunMarkerSource::default()),
                ..ArtifactSource::default()
            },
        }
    }

    fn single_slot_vector_channel_probe(
        kind: crate::export::ChannelKind,
    ) -> crate::export::VectorChannel {
        use crate::export::{
            ChannelKind, HttpEventChannel, NatsSubjectChannel, StdoutChannel, VectorChannel,
        };
        match kind {
            ChannelKind::HttpEvent => VectorChannel {
                http_event: Some(HttpEventChannel {
                    endpoint: None,
                    signal_type: "x".into(),
                }),
                ..VectorChannel::default()
            },
            ChannelKind::NatsSubject => VectorChannel {
                nats_subject: Some(NatsSubjectChannel {
                    subject: "s".into(),
                    stream: "S".into(),
                    url: None,
                }),
                ..VectorChannel::default()
            },
            ChannelKind::Stdout => VectorChannel {
                stdout: Some(StdoutChannel::default()),
                ..VectorChannel::default()
            },
        }
    }

    // Substrate-local two-slot factories — peers to the sibling
    // `single_slot_*_probe` block above. Each composes
    // `single_slot_*_probe(a)` with `single_slot_*_probe(b)`
    // through per-field `Option::or` on the parent's tagged-union
    // slots, matching the shape every per-site `two_slot_X(a, b)`
    // helper across the four production parents already carries.
    // The ambiguity-primitive only requires that BOTH addressed
    // slots on the parent are populated; the inner spec's exact
    // field values are irrelevant to the two-slot ambiguity check.

    fn two_slot_intent_probe(
        a: crate::intent::IntentKind,
        b: crate::intent::IntentKind,
    ) -> crate::intent::Intent {
        let ia = single_slot_intent_probe(a);
        let ib = single_slot_intent_probe(b);
        crate::intent::Intent {
            nix: ia.nix.or(ib.nix),
            flux: ia.flux.or(ib.flux),
            lisp: ia.lisp.or(ib.lisp),
            container: ia.container.or(ib.container),
            aplicacao: ia.aplicacao.or(ib.aplicacao),
            guest: ia.guest.or(ib.guest),
        }
    }

    fn two_slot_encapsulation_kind_probe(
        a: crate::encapsulates::EncapsulationTarget,
        b: crate::encapsulates::EncapsulationTarget,
    ) -> crate::encapsulates::EncapsulationKind {
        let ka = single_slot_encapsulation_kind_probe(a);
        let kb = single_slot_encapsulation_kind_probe(b);
        crate::encapsulates::EncapsulationKind {
            existing_helm_release: ka.existing_helm_release.or(kb.existing_helm_release),
            existing_kustomization: ka.existing_kustomization.or(kb.existing_kustomization),
            bare_workload: ka.bare_workload.or(kb.bare_workload),
        }
    }

    fn two_slot_artifact_source_probe(
        a: crate::export::ArtifactKind,
        b: crate::export::ArtifactKind,
    ) -> crate::export::ArtifactSource {
        let sa = single_slot_artifact_source_probe(a);
        let sb = single_slot_artifact_source_probe(b);
        crate::export::ArtifactSource {
            receipts: sa.receipts.or(sb.receipts),
            test_report: sa.test_report.or(sb.test_report),
            process_snapshot: sa.process_snapshot.or(sb.process_snapshot),
            run_marker: sa.run_marker.or(sb.run_marker),
        }
    }

    fn two_slot_vector_channel_probe(
        a: crate::export::ChannelKind,
        b: crate::export::ChannelKind,
    ) -> crate::export::VectorChannel {
        let ca = single_slot_vector_channel_probe(a);
        let cb = single_slot_vector_channel_probe(b);
        crate::export::VectorChannel {
            http_event: ca.http_event.or(cb.http_event),
            nats_subject: ca.nats_subject.or(cb.nats_subject),
            stdout: ca.stdout.or(cb.stdout),
        }
    }

    /// The trait's `KIND_LIST` associated const IS the same
    /// `&'static str` the inherent `_LIST` constant publishes at
    /// each production site — pin identity via `std::ptr::eq` so a
    /// future silent copy (e.g. `const KIND_LIST: &'static str =
    /// "...literal...";` at the impl block) is caught here.
    #[test]
    fn production_tagged_union_kind_list_borrows_the_inherent_constant() {
        assert!(std::ptr::eq(
            <crate::intent::Intent as TaggedUnion>::KIND_LIST,
            crate::intent::INTENT_KIND_LIST,
        ));
        assert!(std::ptr::eq(
            <crate::encapsulates::EncapsulationKind as TaggedUnion>::KIND_LIST,
            crate::encapsulates::ENCAPSULATION_TARGET_LIST,
        ));
        assert!(std::ptr::eq(
            <crate::export::ArtifactSource as TaggedUnion>::KIND_LIST,
            crate::export::ARTIFACT_KIND_LIST,
        ));
        assert!(std::ptr::eq(
            <crate::export::VectorChannel as TaggedUnion>::KIND_LIST,
            crate::export::CHANNEL_KIND_LIST,
        ));
    }

    // -------------------------------------------------------------------
    // `TaggedUnion::variant` default method — substrate primitive every
    // production `.variant()` inherent method delegates to. Pin the
    // four-outcome truth table (Empty on all-none, Ambiguous on many,
    // Ok on exactly-one at every position) directly on the sibling-
    // shaped local parent + local kind + local variant scaffold, so a
    // regression on the default body's short-circuit or
    // ClosedSet::ALL iteration shape fails here — before any per-parent
    // inherent test surfaces the drift.
    // -------------------------------------------------------------------

    /// Every populated position across [`LocalKind::ALL`] resolves to
    /// its own [`LocalVariant`] arm through the default body's
    /// `resolve_or_err(<Kind as ClosedSet>::ALL.iter().copied()
    /// .map(|k| k.select(self)), KIND_LIST)` sweep. Pin every position
    /// so a regression that drifts the iteration order (or drops the
    /// `.iter().copied()` bridge to owned-`Copy` Kinds) fails at ONE
    /// substrate boundary rather than at four per-parent inherent test
    /// sites.
    #[test]
    fn tagged_union_default_variant_resolves_each_populated_slot() {
        let mut p = LocalParent {
            alpha: Some(11),
            ..Default::default()
        };
        assert_eq!(
            <LocalParent as TaggedUnion>::variant(&p).unwrap(),
            LocalVariant::Alpha(&11)
        );
        p = LocalParent {
            beta: Some(22),
            ..Default::default()
        };
        assert_eq!(
            <LocalParent as TaggedUnion>::variant(&p).unwrap(),
            LocalVariant::Beta(&22)
        );
        p = LocalParent {
            gamma: Some(33),
            ..Default::default()
        };
        assert_eq!(
            <LocalParent as TaggedUnion>::variant(&p).unwrap(),
            LocalVariant::Gamma(&33)
        );
    }

    /// A [`LocalParent`] with no populated slot resolves through the
    /// default body to a [`TaggedUnionError::empty`] carrier whose
    /// payload IS the trait's [`TaggedUnion::KIND_LIST`] constant —
    /// pin identity via [`std::ptr::eq`] so a regression that
    /// composes a fresh `&'static str` at the empty arm (instead of
    /// carrying the trait's constant verbatim) is caught here. This
    /// is the substrate-wide guarantee the four production sites'
    /// operator diagnostics depend on: a rename at
    /// `<Parent as TaggedUnion>::KIND_LIST` reaches the error surface
    /// intact through ONE `&'static str` handoff.
    #[test]
    fn tagged_union_default_variant_empty_carries_kind_list_by_pointer() {
        let empty = LocalParent::default();
        let err = <LocalParent as TaggedUnion>::variant(&empty).unwrap_err();
        match err {
            LocalParentError::Empty(list) => {
                assert!(
                    std::ptr::eq(list, <LocalParent as TaggedUnion>::KIND_LIST),
                    "TaggedUnion::variant default must carry KIND_LIST by pointer, not by re-composition",
                );
            }
            LocalParentError::Ambiguous => {
                panic!("expected Empty carrier, got Ambiguous");
            }
        }
    }

    /// A [`LocalParent`] with two populated slots resolves through
    /// the default body to a [`TaggedUnionError::ambiguous`] carrier —
    /// pin the Many arm at the substrate boundary so a regression
    /// that drops the short-circuit (or misroutes the Many arm to
    /// Empty) is caught here.
    #[test]
    fn tagged_union_default_variant_ambiguous_on_multiple_populated_slots() {
        let p = LocalParent {
            alpha: Some(1),
            beta: Some(2),
            gamma: None,
        };
        assert_eq!(
            <LocalParent as TaggedUnion>::variant(&p).unwrap_err(),
            LocalParentError::Ambiguous
        );
    }

    /// Every one of the four production `.variant()` inherent methods
    /// dispatches through the trait's default body byte-identically —
    /// pin the delegation shape (inherent forwarder → trait default)
    /// on a probe per parent so a regression that copies the pre-lift
    /// hand-rolled `resolve_or_err(...)` body back into the inherent
    /// method (instead of the `<Self as TaggedUnion>::variant(self)`
    /// one-line delegation) reaches this substrate boundary before it
    /// reaches any operator diagnostic.
    #[test]
    fn every_production_inherent_variant_dispatches_through_trait_default() {
        use crate::encapsulates::{EncapsulationKind, EncapsulationKindError};
        use crate::export::{ArtifactError, ArtifactSource, ChannelError, VectorChannel};
        use crate::intent::{Intent, IntentError};

        // Intent: default of all-None resolves to Empty via the delegation.
        let i = Intent::default();
        match (i.variant(), <Intent as TaggedUnion>::variant(&i)) {
            (Err(IntentError::Empty(a)), Err(IntentError::Empty(b))) => assert!(
                std::ptr::eq(a, b),
                "Intent inherent and trait dispatch must return the same &'static str",
            ),
            (a, b) => panic!("Intent inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
        }

        // EncapsulationKind: same Empty projection through both dispatch paths.
        let k = EncapsulationKind::default();
        match (k.variant(), <EncapsulationKind as TaggedUnion>::variant(&k)) {
            (Err(EncapsulationKindError::Empty(a)), Err(EncapsulationKindError::Empty(b))) => {
                assert!(
                std::ptr::eq(a, b),
                "EncapsulationKind inherent and trait dispatch must return the same &'static str",
            )
            }
            (a, b) => {
                panic!("EncapsulationKind inherent/trait mismatch: inherent={a:?}, trait={b:?}")
            }
        }

        // ArtifactSource: same Empty projection through both dispatch paths.
        let s = ArtifactSource::default();
        match (s.variant(), <ArtifactSource as TaggedUnion>::variant(&s)) {
            (Err(ArtifactError::Empty(a)), Err(ArtifactError::Empty(b))) => assert!(
                std::ptr::eq(a, b),
                "ArtifactSource inherent and trait dispatch must return the same &'static str",
            ),
            (a, b) => panic!("ArtifactSource inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
        }

        // VectorChannel: same Empty projection through both dispatch paths.
        let c = VectorChannel::default();
        match (c.variant(), <VectorChannel as TaggedUnion>::variant(&c)) {
            (Err(ChannelError::Empty(a)), Err(ChannelError::Empty(b))) => assert!(
                std::ptr::eq(a, b),
                "VectorChannel inherent and trait dispatch must return the same &'static str",
            ),
            (a, b) => panic!("VectorChannel inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
        }
    }

    // -------------------------------------------------------------------
    // `declare_tagged_union_impls!` macro — the three-block impl stanza
    // (inherent `.variant()` forwarder + `VariantSelector<Parent>` on
    // the Kind + `TaggedUnion` on the parent) as ONE authoring surface.
    // Pin the macro's shape against a sibling-shaped local family so a
    // regression on any of the three emitted blocks fails here before
    // it reaches the four production sites.
    // -------------------------------------------------------------------

    /// Local sibling-shaped Kind for the macro-emitted-impls test — a
    /// dedicated closed set so this test can't share substrate with the
    /// hand-rolled [`LocalKind`] block above. Uses
    /// [`tatara_closed_set::DeriveClosedSet`] so the macro's
    /// `TaggedUnion` bound (`Kind: ClosedSet + VariantSelector<Self>`)
    /// is satisfied through the derive.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
    #[closed_set(via = "as_str", generate_unknown)]
    enum MacroLocalKind {
        Foo,
        Bar,
    }

    impl MacroLocalKind {
        const ALL: [Self; 2] = [Self::Foo, Self::Bar];
        const fn as_str(self) -> &'static str {
            match self {
                Self::Foo => "foo",
                Self::Bar => "bar",
            }
        }
        fn select<'a>(self, parent: &'a MacroLocalParent) -> Option<MacroLocalVariant<'a>> {
            match self {
                Self::Foo => parent.foo.as_ref().map(MacroLocalVariant::Foo),
                Self::Bar => parent.bar.as_ref().map(MacroLocalVariant::Bar),
            }
        }
    }

    /// Local sibling-shaped parent for the macro-emitted-impls test —
    /// distinct from [`LocalParent`] so the macro's emitted impls
    /// don't collide with the hand-rolled trait impls above.
    ///
    /// Derives [`serde::Serialize`] with `skip_serializing_if =
    /// "Option::is_none"` on every slot so the wire-format primitive
    /// [`assert_single_slot_key_matches_label`] can be exercised
    /// through the macro-emitted `TaggedUnion` impl path — pins the
    /// substrate-wide guarantee that a fifth sibling landing through
    /// [`declare_tagged_union_impls!`] picks up the wire-alignment
    /// check for free.
    #[derive(Default, serde::Serialize)]
    struct MacroLocalParent {
        #[serde(skip_serializing_if = "Option::is_none")]
        foo: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        bar: Option<u32>,
    }

    /// Borrowed-view of a populated slot on [`MacroLocalParent`] — the
    /// return type of the macro-emitted inherent `.variant()`.
    #[derive(Debug, PartialEq)]
    enum MacroLocalVariant<'a> {
        Foo(&'a u32),
        Bar(&'a u32),
    }

    impl VariantKind<MacroLocalKind> for MacroLocalVariant<'_> {
        fn variant_kind(&self) -> MacroLocalKind {
            match self {
                Self::Foo(_) => MacroLocalKind::Foo,
                Self::Bar(_) => MacroLocalKind::Bar,
            }
        }
    }

    crate::declare_tagged_union_error! {
        pub(super) MacroLocalError,
        empty = "macro-local parent has no variant set (one of {0} required)",
        ambiguous = "macro-local parent has multiple variants set; exactly one required",
    }

    /// Slash-joined kind list — literal peer of
    /// [`crate::intent::INTENT_KIND_LIST`] etc. that the macro's
    /// `KIND_LIST` associated const borrows verbatim.
    const MACRO_LOCAL_KIND_LIST: &str = "foo/bar";

    // ONE macro call emits: inherent `MacroLocalParent::variant`,
    // `impl VariantSelector<MacroLocalParent> for MacroLocalKind`, and
    // `impl TaggedUnion for MacroLocalParent`. The four production
    // sites bind through this exact same call shape.
    crate::declare_tagged_union_impls! {
        parent = MacroLocalParent,
        kind = MacroLocalKind,
        variant = MacroLocalVariant,
        error = MacroLocalError,
        kind_list = MACRO_LOCAL_KIND_LIST,
    }

    /// The macro-emitted `impl TaggedUnion` binds the (Kind, Error,
    /// KIND_LIST) triple exactly as a hand-rolled block would — pin
    /// the diagnostic-stability testkit primitive through the macro's
    /// output so a regression on any of the three associated items
    /// (say the macro pulling `KIND_LIST` from the wrong argument
    /// slot) fails here.
    #[test]
    fn macro_emitted_tagged_union_impl_binds_kind_list_coherently() {
        assert_kind_list_matches_closed_set::<MacroLocalParent>();
        assert!(std::ptr::eq(
            <MacroLocalParent as TaggedUnion>::KIND_LIST,
            MACRO_LOCAL_KIND_LIST,
        ));
    }

    /// The macro-emitted inherent `.variant()` forwarder dispatches
    /// through the trait default body — every populated slot resolves
    /// to its own [`MacroLocalVariant`] arm, all-none resolves to
    /// [`TaggedUnionError::empty`] carrying the trait's `KIND_LIST`
    /// by pointer, two-populated resolves to
    /// [`TaggedUnionError::ambiguous`]. The four production sites
    /// exercise the same four-outcome truth table through the same
    /// macro-emitted delegation shape.
    #[test]
    fn macro_emitted_inherent_variant_dispatches_the_four_outcome_truth_table() {
        // Foo populated.
        let p = MacroLocalParent {
            foo: Some(11),
            bar: None,
        };
        assert_eq!(p.variant().unwrap(), MacroLocalVariant::Foo(&11));

        // Bar populated.
        let p = MacroLocalParent {
            foo: None,
            bar: Some(22),
        };
        assert_eq!(p.variant().unwrap(), MacroLocalVariant::Bar(&22));

        // All none — Empty arm carries the trait's KIND_LIST value.
        // The by-pointer preservation across the trait default body is
        // pinned substrate-wide by
        // `tagged_union_default_variant_empty_carries_kind_list_by_pointer`
        // on the sibling hand-rolled `LocalParent`; this test only pins
        // that the macro-emitted `KIND_LIST = MACRO_LOCAL_KIND_LIST`
        // assignment reaches the operator diagnostic value-identically.
        let p = MacroLocalParent::default();
        match p.variant().unwrap_err() {
            MacroLocalError::Empty(list) => assert_eq!(list, MACRO_LOCAL_KIND_LIST),
            MacroLocalError::Ambiguous => panic!("expected Empty, got Ambiguous"),
        }

        // Two populated — Ambiguous.
        let p = MacroLocalParent {
            foo: Some(1),
            bar: Some(2),
        };
        assert_eq!(p.variant().unwrap_err(), MacroLocalError::Ambiguous);
    }

    /// The macro-emitted `VariantSelector` impl's `select` body
    /// delegates to the Kind's inherent `<Kind>::select(self, parent)`
    /// — pin the delegation via `std::ptr::eq` on the returned
    /// borrowed view so a regression that inlines a divergent select
    /// body (rather than reaching the inherent method) is caught here.
    #[test]
    fn macro_emitted_variant_selector_delegates_to_inherent_select() {
        let p = MacroLocalParent {
            foo: Some(7),
            bar: None,
        };
        // Trait-dispatched select projects through the macro-emitted body.
        let via_trait =
            <MacroLocalKind as VariantSelector<MacroLocalParent>>::select(MacroLocalKind::Foo, &p)
                .unwrap();
        // Inherent select projects through the direct impl.
        let via_inherent = MacroLocalKind::Foo.select(&p).unwrap();
        match (via_trait, via_inherent) {
            (MacroLocalVariant::Foo(a), MacroLocalVariant::Foo(b)) => {
                assert!(
                    std::ptr::eq(a, b),
                    "macro-emitted VariantSelector::select must delegate to <Kind>::select — same borrow, not a copy",
                );
            }
            _ => panic!("expected Foo arm on both dispatch paths"),
        }
    }

    /// The trait's default body sweeps `<Kind as ClosedSet>::ALL` in
    /// declaration order — pin the iteration order against the
    /// production `Kind::ALL` inherent const on every implementor so
    /// a regression on `DeriveClosedSet`'s ALL-projection (or a
    /// silent reorder of the enum's variant declarations that drifts
    /// only ONE of the two arrays) fails at ONE substrate boundary.
    #[test]
    fn every_production_kind_closedset_all_matches_inherent_all() {
        use crate::encapsulates::EncapsulationTarget;
        use crate::export::{ArtifactKind, ChannelKind};
        use crate::intent::IntentKind;

        assert_eq!(
            <IntentKind as tatara_closed_set::ClosedSet>::ALL,
            IntentKind::ALL.as_slice(),
        );
        assert_eq!(
            <EncapsulationTarget as tatara_closed_set::ClosedSet>::ALL,
            EncapsulationTarget::ALL.as_slice(),
        );
        assert_eq!(
            <ArtifactKind as tatara_closed_set::ClosedSet>::ALL,
            ArtifactKind::ALL.as_slice(),
        );
        assert_eq!(
            <ChannelKind as tatara_closed_set::ClosedSet>::ALL,
            ChannelKind::ALL.as_slice(),
        );
    }

    // -------------------------------------------------------------------
    // `VariantKind<K>` trait — reverse projection from a borrowed-variant
    // view back into its addressing Kind, and `assert_variant_round_trip`
    // as the substrate testkit primitive that composes it with
    // `VariantSelector::select` on the populated side. Pin the four-arm
    // truth table (every position round-trips through select→variant_kind
    // AND through variant()→variant_kind) directly on the sibling-shaped
    // local scaffold, so a regression on either projection or on the
    // resolver default body fails here — before any per-parent inherent
    // test surfaces the drift.
    // -------------------------------------------------------------------

    /// Every populated position across [`LocalKind::ALL`] round-trips
    /// through both `select→variant_kind` AND `variant()→variant_kind`
    /// on the sibling-shaped local scaffold. Pins the substrate
    /// primitive's four-arm truth table at ONE boundary — a regression
    /// on either projection direction (or on the resolver default
    /// short-circuit / iteration order) fails here before any per-parent
    /// inherent test surfaces the drift.
    #[test]
    fn assert_variant_round_trip_accepts_coherent_local_impl() {
        fn make_local(k: LocalKind) -> LocalParent {
            match k {
                LocalKind::Alpha => LocalParent {
                    alpha: Some(11),
                    ..Default::default()
                },
                LocalKind::Beta => LocalParent {
                    beta: Some(22),
                    ..Default::default()
                },
                LocalKind::Gamma => LocalParent {
                    gamma: Some(33),
                    ..Default::default()
                },
            }
        }
        assert_variant_round_trip::<LocalParent, _>(make_local);
    }

    /// The testkit primitive is a `#[track_caller]` compound-lift: a
    /// factory that fails to populate the addressed slot fails at the
    /// caller's site with a labeled panic message, not silently. Pin
    /// the failing case with a deliberately empty parent factory so a
    /// regression that drops the "select must return Some" check
    /// fails-loudly here — the missing-slot arm is the substrate
    /// primitive's first failure mode.
    #[test]
    #[should_panic(expected = "VariantSelector::select must return Some for populated slot")]
    fn assert_variant_round_trip_rejects_factory_that_leaves_slot_empty() {
        // Factory that returns an all-empty parent regardless of k —
        // every `k.select(&parent)` returns None, so the primitive
        // panics at the "must return Some" arm.
        fn empty_factory(_: LocalKind) -> LocalParent {
            LocalParent::default()
        }
        assert_variant_round_trip::<LocalParent, _>(empty_factory);
    }

    // -------------------------------------------------------------------
    // `assert_two_slots_ambiguous` — the ALL×ALL ambiguity sweep as ONE
    // substrate primitive. Pin the truth table (every off-diagonal pair
    // resolves to `TaggedUnionError::ambiguous`, diagonal pairs are
    // skipped, a factory that yields a non-Ambiguous parent fails-loudly
    // at the caller's site) directly on the sibling-shaped `LocalParent`
    // scaffold — a regression on either the pair-iteration order or the
    // expected-carrier composition fails here before any per-parent test
    // surfaces the drift.
    // -------------------------------------------------------------------

    /// Every off-diagonal pair across [`LocalKind::ALL`] × `ALL`
    /// resolves through the substrate primitive to
    /// [`LocalParentError::Ambiguous`] on the sibling-shaped local
    /// scaffold. Pins the primitive's Ok arm (no false positives on the
    /// coherent-impl side) at ONE boundary — a regression that drops
    /// the diagonal skip, mis-iterates `ClosedSet::ALL`, or composes a
    /// divergent expected carrier fails here before any per-parent
    /// inherent test surfaces the drift.
    #[test]
    fn assert_two_slots_ambiguous_accepts_coherent_local_impl() {
        fn two_local(a: LocalKind, b: LocalKind) -> LocalParent {
            let mut p = LocalParent::default();
            for k in [a, b] {
                match k {
                    LocalKind::Alpha => p.alpha = Some(11),
                    LocalKind::Beta => p.beta = Some(22),
                    LocalKind::Gamma => p.gamma = Some(33),
                }
            }
            p
        }
        assert_two_slots_ambiguous::<LocalParent, _>(two_local);
    }

    /// A factory that yields a single-slot parent for the FIRST kind
    /// (ignoring the second) — every off-diagonal pair resolves to
    /// exactly-one Ok(Variant), NOT Ambiguous — MUST fail-loudly at
    /// the caller's site through the primitive's "two-slot parent
    /// must not resolve to a variant" arm. Pin the Ok-side failure
    /// mode so a regression that mis-routes the substrate primitive's
    /// resolved-Ok arm past the assertion (silently succeeding on a
    /// single-slot factory) is caught here.
    #[test]
    #[should_panic(expected = "two-slot parent must not resolve to a variant")]
    fn assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot() {
        fn single_only(a: LocalKind, _: LocalKind) -> LocalParent {
            let mut p = LocalParent::default();
            match a {
                LocalKind::Alpha => p.alpha = Some(11),
                LocalKind::Beta => p.beta = Some(22),
                LocalKind::Gamma => p.gamma = Some(33),
            }
            p
        }
        assert_two_slots_ambiguous::<LocalParent, _>(single_only);
    }

    /// A factory that yields an all-empty parent (so `.variant()`
    /// resolves to the `Empty` carrier, NOT `Ambiguous`) MUST
    /// fail-loudly at the caller's site through the primitive's
    /// `assert_eq!` arm — the composed expected carrier
    /// [`TaggedUnionError::ambiguous`] mismatches the resolved
    /// [`TaggedUnionError::empty`] carrier. Pin the Empty-arm failure
    /// mode so a regression that mis-projects the None arm of
    /// [`ResolveError`] onto Ambiguous (silently succeeding on an
    /// empty factory) is caught here.
    #[test]
    #[should_panic(expected = "should resolve Ambiguous")]
    fn assert_two_slots_ambiguous_rejects_factory_that_populates_no_slots() {
        fn empty_factory(_: LocalKind, _: LocalKind) -> LocalParent {
            LocalParent::default()
        }
        assert_two_slots_ambiguous::<LocalParent, _>(empty_factory);
    }

    // -------------------------------------------------------------------
    // `assert_single_slot_key_matches_label` — the wire-key / kind-label
    // alignment sweep as ONE substrate primitive. Pin the truth table
    // (every populated slot serializes to exactly one JSON key whose
    // name equals the addressing kind's ClosedSet label; a factory that
    // populates the wrong slot / no slot / multiple slots fails-loudly
    // at the caller's site) directly on the sibling-shaped `LocalParent`
    // scaffold — a regression on either the exactly-one arm or the
    // name-equality arm fails here before any per-parent inherent test
    // surfaces the drift.
    // -------------------------------------------------------------------

    /// Every kind across [`LocalKind::ALL`] serializes through the
    /// substrate primitive to a JSON object with EXACTLY ONE key whose
    /// name equals `<LocalKind as ClosedSet>::label` on the addressed
    /// kind. Pins the primitive's Ok arm (no false positives on the
    /// coherent-impl side) at ONE boundary — a regression that inspects
    /// the wrong serde value (e.g. `to_string` instead of `to_value`),
    /// counts fields off-by-one, or projects the wrong `ClosedSet`
    /// method (`labels_joined` instead of `label`) fails here before any
    /// per-parent inherent test surfaces the drift.
    #[test]
    fn assert_single_slot_key_matches_label_accepts_coherent_local_impl() {
        fn make_local(k: LocalKind) -> LocalParent {
            match k {
                LocalKind::Alpha => LocalParent {
                    alpha: Some(11),
                    ..Default::default()
                },
                LocalKind::Beta => LocalParent {
                    beta: Some(22),
                    ..Default::default()
                },
                LocalKind::Gamma => LocalParent {
                    gamma: Some(33),
                    ..Default::default()
                },
            }
        }
        assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
    }

    /// A factory that returns a single-slot parent for the WRONG kind
    /// (populates `beta` regardless of what kind is asked for) MUST
    /// fail-loudly at the caller's site through the primitive's
    /// name-equality arm — the emitted key does not match the addressed
    /// kind's label. Pins the drift-detection failure mode so a
    /// regression that drops the `assert_eq!(keys[0], label)` arm
    /// (silently succeeding on any-key-at-all) is caught here. The
    /// caller's site is the `#[should_panic]` boundary through the
    /// primitive's `#[track_caller]` compound-lift.
    #[test]
    #[should_panic(expected = "wire-key drift")]
    fn assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot() {
        fn always_beta(_: LocalKind) -> LocalParent {
            LocalParent {
                beta: Some(22),
                ..Default::default()
            }
        }
        assert_single_slot_key_matches_label::<LocalParent, _>(always_beta);
    }

    /// A factory that returns an all-empty parent (so serializing
    /// yields ZERO keys, not exactly-one) MUST fail-loudly at the
    /// caller's site through the primitive's exactly-one arm. Pins the
    /// zero-key failure mode so a regression that projects
    /// `obj.keys().count() >= 1` (rather than `== 1`) is caught here.
    #[test]
    #[should_panic(expected = "exactly one populated field")]
    fn assert_single_slot_key_matches_label_rejects_factory_that_populates_no_slots() {
        fn empty_factory(_: LocalKind) -> LocalParent {
            LocalParent::default()
        }
        assert_single_slot_key_matches_label::<LocalParent, _>(empty_factory);
    }

    /// A factory that returns a parent with TWO populated slots (so
    /// serializing yields two keys, not exactly-one) MUST fail-loudly
    /// at the caller's site through the primitive's exactly-one arm.
    /// Pins the many-keys failure mode so a regression that projects
    /// `obj.keys().count() <= 1` (rather than `== 1`) is caught here.
    /// Cross-pins the substrate promise that a single-slot factory
    /// truly populates ONE slot — a future factory bug that leaks
    /// residual populated slots between calls (e.g. via shared mutable
    /// state) is caught HERE at the primitive boundary.
    #[test]
    #[should_panic(expected = "exactly one populated field")]
    fn assert_single_slot_key_matches_label_rejects_factory_that_populates_two_slots() {
        fn two_slot_factory(_: LocalKind) -> LocalParent {
            LocalParent {
                alpha: Some(1),
                beta: Some(2),
                gamma: None,
            }
        }
        assert_single_slot_key_matches_label::<LocalParent, _>(two_slot_factory);
    }

    /// The macro-emitted [`MacroLocalParent`] scaffold impls
    /// [`TaggedUnion`] through the [`declare_tagged_union_impls!`]
    /// three-block macro AND additionally derives `serde::Serialize` +
    /// `#[serde(skip_serializing_if = "Option::is_none")]` on every
    /// slot — so the wire-key primitive dispatches on the MACRO-emitted
    /// impl path byte-identically with the hand-rolled [`LocalParent`]
    /// path above. Pins the substrate-wide guarantee that a fifth
    /// sibling landing through the macro picks up the wire-alignment
    /// check for free, without a hand-rolled `TaggedUnion` block, so
    /// long as its serde derives match the substrate-wide
    /// `skip_serializing_if = "Option::is_none"` shape every production
    /// site already carries. A regression that mis-routes the
    /// primitive's serialize call through the WRONG entry point (e.g.
    /// calling a bespoke `to_json` that bypasses serde) is caught here.
    #[test]
    fn assert_single_slot_key_matches_label_accepts_macro_emitted_impl() {
        fn make_macro_local(k: MacroLocalKind) -> MacroLocalParent {
            match k {
                MacroLocalKind::Foo => MacroLocalParent {
                    foo: Some(7),
                    bar: None,
                },
                MacroLocalKind::Bar => MacroLocalParent {
                    foo: None,
                    bar: Some(8),
                },
            }
        }
        assert_single_slot_key_matches_label::<MacroLocalParent, _>(make_macro_local);
    }

    // -------------------------------------------------------------------
    // `assert_wire_key_matches_label` — bound-relaxed peer of the
    // `assert_single_slot_key_matches_label` primitive. Pin the truth
    // table (every populated slot serializes to exactly one JSON key
    // whose name equals the addressing kind's ClosedSet label; a
    // factory that populates the wrong slot / no slot / multiple slots
    // fails-loudly at the caller's site) on a NON-TaggedUnion parent
    // scaffold — the delegation-only path from the trait-projected
    // primitive would silently pass this test if the bound-relaxed
    // primitive's body regressed, so the direct-dispatch probes here
    // pin the bound-relaxed pathway independently.
    // -------------------------------------------------------------------

    /// Local parent that carries the wire-format shape (`Option<T>`
    /// slots + `#[serde(skip_serializing_if = "Option::is_none")]`
    /// annotations) but DELIBERATELY does NOT impl [`TaggedUnion`] —
    /// pins the bound-relaxed sweep on the exact shape [`crate::lifetime::Lifetime`]
    /// carries in production (empty resolves to a default variant,
    /// not to a typed error, so the trait's `T::Error` bound doesn't
    /// hold and the trait-projected surface excludes it).
    #[derive(Default, serde::Serialize)]
    struct BareParent {
        #[serde(skip_serializing_if = "Option::is_none")]
        alpha: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        beta: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        gamma: Option<u32>,
    }

    /// The bound-relaxed primitive dispatches Ok on a coherent
    /// non-TaggedUnion impl — pin the happy path directly on the
    /// [`BareParent`] scaffold so a regression that gates the sweep
    /// body on the `T: TaggedUnion` bound (accidentally re-adding it,
    /// or projecting through `T::Kind` instead of the caller-supplied
    /// `K` generic) fails HERE at the primitive-independent boundary
    /// rather than at the [`crate::lifetime::Lifetime`] production
    /// site alone. The Ok arm is the "no drift" outcome; a divergence
    /// surfaces as a labeled assertion failure at the caller site
    /// (this test's own line) via the primitive's `#[track_caller]`.
    #[test]
    fn assert_wire_key_matches_label_accepts_coherent_bare_parent_impl() {
        fn make_bare(k: LocalKind) -> BareParent {
            match k {
                LocalKind::Alpha => BareParent {
                    alpha: Some(11),
                    ..Default::default()
                },
                LocalKind::Beta => BareParent {
                    beta: Some(22),
                    ..Default::default()
                },
                LocalKind::Gamma => BareParent {
                    gamma: Some(33),
                    ..Default::default()
                },
            }
        }
        assert_wire_key_matches_label::<BareParent, LocalKind, _>(make_bare);
    }

    /// A factory that returns a bare-parent for the WRONG kind
    /// (populates `beta` regardless of what kind is asked for) MUST
    /// fail-loudly at the caller's site through the bound-relaxed
    /// primitive's name-equality arm — the emitted key does not match
    /// the addressed kind's label. Pins the drift-detection failure
    /// mode on the non-TaggedUnion pathway so a regression that drops
    /// the `assert_eq!(keys[0], label)` arm (silently succeeding on
    /// any-key-at-all) is caught here — mechanical peer of the
    /// sibling `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`
    /// on the TaggedUnion pathway.
    #[test]
    #[should_panic(expected = "wire-key drift")]
    fn assert_wire_key_matches_label_rejects_factory_that_populates_wrong_slot() {
        fn always_beta(_: LocalKind) -> BareParent {
            BareParent {
                beta: Some(22),
                ..Default::default()
            }
        }
        assert_wire_key_matches_label::<BareParent, LocalKind, _>(always_beta);
    }

    /// A factory that returns an all-empty bare-parent (so serializing
    /// yields ZERO keys, not exactly-one) MUST fail-loudly at the
    /// caller's site through the bound-relaxed primitive's
    /// exactly-one arm. Pins the zero-key failure mode on the
    /// non-TaggedUnion pathway.
    #[test]
    #[should_panic(expected = "exactly one populated field")]
    fn assert_wire_key_matches_label_rejects_factory_that_populates_no_slots() {
        fn empty_factory(_: LocalKind) -> BareParent {
            BareParent::default()
        }
        assert_wire_key_matches_label::<BareParent, LocalKind, _>(empty_factory);
    }

    /// The trait-projected [`assert_single_slot_key_matches_label`]
    /// is a one-line delegation to the bound-relaxed
    /// [`assert_wire_key_matches_label`] peer — pin the delegation
    /// shape at ONE boundary so a regression that inlines a
    /// divergent sweep body into the trait-projected surface (rather
    /// than the one-line dispatch) is caught here. Ok on a coherent
    /// impl means BOTH primitives dispatch through the SAME body on
    /// the same fixture — [`LocalParent`] impls [`TaggedUnion`], so
    /// both the trait-projected surface and the bound-relaxed peer
    /// reach it, and a divergence between the two dispatches would
    /// surface here as one succeeding + the other failing.
    #[test]
    fn assert_single_slot_key_matches_label_delegates_to_wire_key_matches_label() {
        fn make_local(k: LocalKind) -> LocalParent {
            match k {
                LocalKind::Alpha => LocalParent {
                    alpha: Some(11),
                    ..Default::default()
                },
                LocalKind::Beta => LocalParent {
                    beta: Some(22),
                    ..Default::default()
                },
                LocalKind::Gamma => LocalParent {
                    gamma: Some(33),
                    ..Default::default()
                },
            }
        }
        // Both surfaces reach the same body — dispatched here through
        // BOTH entry points so a divergence between them fails one
        // arm while the other passes.
        assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
        assert_wire_key_matches_label::<LocalParent, LocalKind, _>(make_local);
    }

    /// Every one of the five production borrowed-view enums impls
    /// [`VariantKind`] byte-identically with its inherent `.kind()`
    /// (or `.target()` on `EncapsulationKindVariant`) — pin the
    /// delegation shape at ONE substrate boundary so a regression that
    /// inlines a divergent match body into the trait impl (rather than
    /// the one-line delegation) is caught here. `Lifetime`'s
    /// borrowed-view is included even though `Lifetime` isn't a
    /// [`TaggedUnion`] impl — the reverse projection applies uniformly.
    #[test]
    fn every_production_variant_kind_impl_matches_inherent_projection() {
        use crate::encapsulates::{EncapsulationKindVariant, ExistingHelmRelease};
        use crate::export::{ArtifactVariant, ChannelVariant, HttpEventChannel, ReceiptsSource};
        use crate::intent::{IntentVariant, NixIntent};
        use crate::lifetime::{LifetimeVariant, PermanentLifetime};

        let nix = NixIntent {
            flake_ref: "github:a/b".into(),
            attribute: "x".into(),
            system: None,
            attic_cache: None,
            extra_args: vec![],
            delegate_to_nix_build: false,
        };
        let iv = IntentVariant::Nix(&nix);
        assert_eq!(iv.kind(), iv.variant_kind());

        let perm = PermanentLifetime::default();
        let lv = LifetimeVariant::Permanent(&perm);
        assert_eq!(lv.kind(), lv.variant_kind());

        let hr = ExistingHelmRelease {
            namespace: "ns".into(),
            name: "n".into(),
            release_name: "r".into(),
        };
        let ev = EncapsulationKindVariant::ExistingHelmRelease(&hr);
        assert_eq!(ev.target(), ev.variant_kind());

        let rs = ReceiptsSource {};
        let av = ArtifactVariant::Receipts(&rs);
        assert_eq!(av.kind(), av.variant_kind());

        let ch = HttpEventChannel {
            endpoint: None,
            signal_type: "s".into(),
        };
        let cv = ChannelVariant::HttpEvent(&ch);
        assert_eq!(cv.kind(), cv.variant_kind());
    }
}