caixa-core 0.1.15

Manifest types, layout invariants, and version contract for the caixa tatara-lisp package system.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
//! Typed Aplicacao — the fourth caixa kind that turns a graph of
//! Servicos into a single declarative application (mesh).
//!
//! See `theory/MESH-COMPOSITION.md` for the design frame: an
//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
//! `:contratos` (inter-Servico edges), declares mesh-level
//! `:politicas` (timeouts, retries, breakers, mTLS), pins
//! `:placement` strategy (single-node / replicated / sharded), and
//! exposes `:entrada` (gateway).
//!
//! ```lisp
//! (defcaixa
//!   :nome      "checkout"
//!   :versao    "0.1.0"
//!   :kind      Aplicacao
//!   :membros   ((:caixa "catalog"     :versao "^0.1")
//!               (:caixa "cart"        :versao "^0.1")
//!               (:caixa "payment"     :versao "^0.2"))
//!   :contratos ((:de "cart" :para "catalog"
//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
//!               (:de "cart" :para "payment"
//!                :wit "wasi:http/proxy" :endpoint "/charge"))
//!   :politicas ((:timeout "30s")
//!               (:retries 3)
//!               (:circuit-breaker (:max-failures 5 :window "60s"))
//!               (:mtls-required t))
//!   :placement (:estrategia replicated
//!               :clusters   ("rio" "mar" "plo"))
//!   :entrada   (:host  "checkout.quero.cloud"
//!               :para  "cart"
//!               :paths ("/api/cart" "/api/products")))
//! ```
//!
//! All the typed slots compose with the M2 primitives the Servicos
//! they reference already declare (`:limits`, `:behavior`,
//! `:upgrade-from`). The Aplicacao adds the *graph-level*
//! standardization on top.

use std::time::Duration;

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::supervisor; // we reuse the duration-string codec at module scope

// ── inter-Servico contracts ──────────────────────────────────────────

/// One typed edge in the Aplicacao graph. The build refuses any
/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
/// (M3+) cross-checks the `:wit` shape against both Servicos'
/// declared imports/exports.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WitContract {
    /// Caller Servico — must reference an entry in the Aplicacao's
    /// `:membros`. The Servico's caixa.lisp must declare a matching
    /// `:capabilities` import for the `:wit` world.
    pub de: String,

    /// Callee Servico — must reference an entry in `:membros`. The
    /// Servico must declare a matching `:capabilities` export.
    pub para: String,

    /// WIT world reference — e.g. `"wasi:http/proxy"`,
    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
    /// M4 promotes these to a typed enum once the WIT registry
    /// stabilizes in tatara-lisp.
    pub wit: String,

    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoint: Option<String>,

    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,

    /// Key/value or queue slot, present when `:wit` is store-shaped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slot: Option<String>,
}

/// Canonical lowercase byte-prefix set the substrate's WIT-shape
/// dispatch routes `wasi:http/*` / `http:*` values through as the
/// HTTP-shaped arm. The single source of truth every consumer that
/// classifies a `:wit` value as HTTP-shaped consults —
/// [`WitContract::is_http`] on the typed contract, the
/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
/// helper, and every future renderer that routes an L7 emission off a
/// bare `&str` (the M4 per-edge WIT registry resolver, the future
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
/// substrate's accept-set and this crate's dispatch-set is a
/// build-time compile error (unused-import), not a per-renderer
/// silent L7-→-L4 demotion at apply time.
///
/// [iwr]: crate::render::is_wit_world_ref
pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];

/// Canonical lowercase byte-prefix set the substrate's WIT-shape
/// dispatch routes `nats:*` / `kafka:*` values through as the
/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
/// HTTP constant's docstring for the full lift rationale.
pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];

/// Canonical lowercase byte-prefix set the substrate's WIT-shape
/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
/// HTTP constant's docstring for the full lift rationale.
pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];

/// True when `wit` — a raw `:contratos :wit` value — starts with any
/// entry in the `prefixes` accept-set. The single canonical
/// prefix-driven WIT-shape classification combinator every peer
/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
/// [`wit_shape_is_store`]) routes through, closing the 3-site
/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
/// combinator the prior open-coded implementations each carried.
///
/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
/// one new `wit_shape_is_<name>` one-liner routing through this
/// combinator, not a fourth copy of the `iter().any(starts_with)`
/// combinator paired to its own prefix-set. Same "one canonical
/// combinator, thin per-arm projections" discipline the peer
/// [`WitTarget::payload_pair`] (6788ed6) already established for the
/// downstream per-arm `(field, payload)` dispatch, extended to the
/// upstream per-arm `PREFIXES → bool` dispatch.
#[must_use]
pub fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
    prefixes.iter().any(|p| wit.starts_with(p))
}

/// True when `wit` — a raw `:contratos :wit` value — targets an
/// HTTP-shaped WIT world (starts with any prefix in
/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
/// consumer routes L7-HTTP emission through, whether they carry a
/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
/// here) or only the raw `wit` string (the positive-sweep test's
/// payload-dispatch helper, future renderers that classify off a
/// bare `&str`). Lifting to a free function makes the shape-dispatch
/// arm reachable without materializing a scratch [`WitContract`] at
/// every classification point, and pins the six-prefix accept-set at
/// one place so future additions (e.g. an `"https:"` peer of
/// `"http:"`) reach every consumer by construction. Routes through
/// the lifted [`wit_shape_matches`] combinator so the
/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
/// canonical primitive, not one open-coded copy per peer arm.
#[must_use]
pub fn wit_shape_is_http(wit: &str) -> bool {
    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
}

/// True when `wit` — a raw `:contratos :wit` value — targets a
/// pub-sub-shaped WIT world (starts with any prefix in
/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
/// [`wit_shape_is_store`] on the shape-dispatch axis; see
/// [`wit_shape_is_http`] for the lift rationale. Routes through the
/// lifted [`wit_shape_matches`] combinator.
#[must_use]
pub fn wit_shape_is_pubsub(wit: &str) -> bool {
    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
}

/// True when `wit` — a raw `:contratos :wit` value — targets a
/// key/value-store-shaped WIT world (starts with any prefix in
/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
/// [`wit_shape_is_http`] for the lift rationale. Routes through the
/// lifted [`wit_shape_matches`] combinator.
#[must_use]
pub fn wit_shape_is_store(wit: &str) -> bool {
    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
}

impl WitContract {
    /// Substrate-canonical per-`:contratos` caller-Servico scalar
    /// accessor every consumer that reads the edge's source endpoint
    /// keys off — returns the author-declared `:contratos :de`
    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
    /// own [`String`] storage.
    ///
    /// The `:contratos :de` slot names the caller-side member Servico
    /// on a typed inter-Servico edge (validated by
    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
    /// Aplicacao declares — a stray `:de` that doesn't name a member is
    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
    /// caller-attachment miss at cluster-apply time). Peer of the
    /// sibling [`WitContract::destination`] accessor on the same
    /// per-`:contratos` entry — the pair `( source(), destination() )`
    /// jointly names the typed edge every renderer that fans on the
    /// caller-callee identity keys off (the
    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
    /// map, the per-edge dedup key, the per-edge membership-lookup
    /// diagnostic).
    ///
    /// Prior to this lift the `.de` byte-string was accessed inline at
    /// four caixa-core sites (the two validate-side membership lookups
    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
    /// tuple's caller-arm at
    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
    /// — five open-coded `.de.as_str()` field-accesses that expressed
    /// no compile-time link back to the typed slot. A future extension
    /// of the `:contratos :de` axis to a richer author surface (a
    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
    /// canary flow, a per-cluster caller-alias table the operator pins
    /// through a future `:placement`-scoped slot, the M4
    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
    /// admission-webhook that promotes the scalar to a caller-set
    /// projection) would have had to be threaded through every
    /// open-coded copy in lockstep or one consumer would silently
    /// disagree with the peers on which caller Servico a given edge
    /// resolves to. Lifting the resolution rule to a typed method on
    /// the substrate primitive means every downstream caller-facing
    /// consumer reaches for one typed dispatch — the resolver's
    /// accept-set migrates as a unit on any future axis addition.
    ///
    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
    /// axis — same "one typed dispatch on the substrate primitive,
    /// thin projections at each consumer" discipline extended onto the
    /// per-`:contratos` caller-Servico byte-string axis.
    #[must_use]
    pub fn source(&self) -> &str {
        self.de.as_str()
    }

    /// Substrate-canonical per-`:contratos` callee-Servico scalar
    /// accessor every consumer that reads the edge's destination
    /// endpoint keys off — returns the author-declared
    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
    /// from the typed slot's own [`String`] storage.
    ///
    /// The `:contratos :para` slot names the callee-side member Servico
    /// on a typed inter-Servico edge (validated by
    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
    /// Aplicacao declares — a stray `:para` that doesn't name a member
    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
    /// callee-attachment miss at cluster-apply time). Callee-side twin
    /// of the sibling [`WitContract::source`] accessor — the pair
    /// jointly names the typed edge every renderer that fans on the
    /// caller-callee identity keys off, and this accessor is also the
    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
    /// composes with `destination()` at every emit site that projects a
    /// per-edge destination Servico's L4 listener port.
    ///
    /// Prior to this lift the `.para` byte-string was accessed inline
    /// at five sites — four caixa-core (the validate-side membership
    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
    /// — with no compile-time link back to the typed slot. A future
    /// extension of the `:contratos :para` axis to a richer author
    /// surface (a multi-callee weighted-fan-out overlay for canary /
    /// blue-green routing on typed edges, a per-cluster callee-alias
    /// table the operator pins through a future `:placement`-scoped
    /// slot, the M4 CR materializer's per-CR admission-webhook that
    /// promotes the scalar to a callee-set projection) would have had
    /// to be threaded through every open-coded copy in lockstep or one
    /// consumer would silently disagree on which callee Servico a given
    /// edge resolves to (a per-CNP `endpointSelector` that names a
    /// different destination than its L4 port resolver reads for, a
    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
    /// as distinct while the adjacency map collapses them, or vice
    /// versa). Lifting to a typed method on the substrate primitive
    /// means every downstream callee-facing consumer reaches for one
    /// typed dispatch.
    ///
    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
    /// (6db982c) accessor — both name the "destination-Servico
    /// byte-string" concept on their respective mesh-slot atoms (per-
    /// ingress apex vs. per-typed-edge callee), and both extend the
    /// substrate-primitive-owns-the-resolver discipline onto the
    /// per-slot destination-Servico scalar axis. Composes with
    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
    /// emit-side per-edge L4 port reader — the composition
    /// `spec.port_for_destination(c.destination())` pins the CNP per-
    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
    /// `spec.port_for_destination(entrada.destination())`.
    #[must_use]
    pub fn destination(&self) -> &str {
        self.para.as_str()
    }

    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
    /// accessor every consumer that reads the edge's WIT world
    /// discriminator keys off — returns the author-declared
    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
    /// the typed slot's own [`String`] storage.
    ///
    /// The `:contratos :wit` slot names the WIT world the typed edge
    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
    /// be a well-shaped WIT world reference via
    /// [`crate::render::is_wit_world_ref`] and by
    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
    /// [`WitContract::source`] / [`WitContract::destination`] accessors
    /// on the same per-`:contratos` entry — the triple
    /// `( source(), destination(), world_ref() )` jointly names the
    /// typed edge every renderer that fans on the caller-callee-shape
    /// identity keys off (the per-edge dedup key at
    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
    /// [`caixa_mesh::cilium_network_policies`], the
    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
    ///
    /// Prior to this lift the `.wit` byte-string was accessed inline at
    /// five sites — three caixa-core (the `WitContract::is_*` shape-
    /// dispatch predicates' `&self.wit` arg, the validate-side empty
    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
    /// printer's `{}` format-slot at `c.wit`) — five open-coded
    /// `.wit` field-accesses that expressed no compile-time link back to
    /// the typed slot. A future extension of the `:contratos :wit` axis
    /// to a richer author surface (an M4 promotion from `String` to a
    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
    /// lisp per this struct's own `:wit` field docstring, a per-cluster
    /// WIT-alias table the operator pins through a future
    /// `:placement`-scoped slot, a canonicalization pass that lowercases
    /// `wasi:*` prefixes) would have had to be threaded through every
    /// open-coded copy in lockstep or one consumer would silently
    /// disagree with the peers on which WIT shape a given edge resolves
    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
    /// empty-check that missed a whitespace-only string a peer accessor
    /// stripped, or vice versa). Lifting to a typed method on the
    /// substrate primitive means every downstream WIT-shape-facing
    /// consumer reaches for one typed dispatch — the resolver's
    /// accept-set migrates as a unit on any future axis addition.
    ///
    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
    /// 6db982c), per-`:membros` [`Membro::nome`] /
    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
    /// on the substrate primitive, thin projections at each consumer"
    /// discipline extended onto the last unlifted per-`:contratos`
    /// scalar (the WIT-world-reference arm).
    ///
    /// [fag]: caixa-feira/src/cmd/app.rs
    #[must_use]
    pub fn world_ref(&self) -> &str {
        self.wit.as_str()
    }

    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
    /// payload-target scalar accessor every consumer that reads the
    /// edge's L7 HTTP request path payload keys off — returns the
    /// author-declared `:contratos :endpoint` byte-string verbatim as
    /// an `Option<&str>`, borrowed from the typed slot's own
    /// `Option<String>` storage; `None` when the slot is absent (the
    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
    /// [`WitTarget::Capability`] edge carries none of the three).
    ///
    /// The `:contratos :endpoint` slot carries the HTTP request path
    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
    /// — same shape required of `:entrada :paths`, gated by the shared
    /// [`crate::render::is_gateway_api_http_path`] predicate) that
    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
    /// downstream consumer that reads the payload keys off this scalar
    /// (the [`WitContract::target`] Http-arm payload extraction that
    /// materializes [`WitTarget::Http { endpoint }`] under the paired
    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
    /// key's endpoint arm that pins the payload as part of the six-tuple
    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
    /// emission path that lands the payload verbatim as a Cilium L7
    /// `path:` rule).
    ///
    /// Prior to this lift the `.endpoint` field was accessed inline at
    /// two production sites in `caixa-core/src/aplicacao.rs` — the
    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
    /// self.endpoint.as_deref();` binding at the top of the method, and
    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
    /// field-accesses that expressed no compile-time link back to the
    /// typed slot. A future extension of the `:contratos :endpoint`
    /// axis to a richer author surface (an M4 promotion from
    /// `Option<String>` to a typed HTTP path-template enum once the
    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
    /// alias table the operator pins through a future `:placement`-
    /// scoped slot, a canonicalization pass that percent-encodes non-
    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
    /// materializer applies per-tenant) would have had to be threaded
    /// through both open-coded copies in lockstep or the two consumers
    /// would silently disagree on which HTTP path a given edge resolves
    /// to — the [`WitContract::target`] payload-extraction reading
    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
    /// the operator-resolved `"/tenant-a/lookup"` would silently split
    /// the [`WitTarget::Http`]-arm rendered payload from the actual
    /// dedup-key uniqueness axis, a two-consumer split at the validator
    /// far from the source `caixa.lisp` with no field naming the
    /// payload-drift root cause. Lifting the resolution rule to a typed
    /// method on the substrate primitive means every downstream
    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
    /// L7-payload surface reaches for exactly one typed dispatch — the
    /// resolver's accept-set migrates as a unit on any future axis
    /// addition.
    ///
    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
    /// accessors on the M3 mesh-slot family — same "one typed dispatch
    /// on the substrate primitive, thin projections at each consumer"
    /// discipline extended onto the per-`:contratos` HTTP-shaped
    /// payload-carrier `Option<String>` optional-scalar axis. First
    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
    /// atom — opens the "optional per-slot payload-carrier scalar"
    /// projection pattern the sibling per-`:contratos` `:subject` /
    /// `:slot` future lifts fold on, matching the closed
    /// per-`:contratos` scalar-value accessor family
    /// ([`WitContract::source`] / [`WitContract::destination`] /
    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
    /// scalar `String` axes. Named `endpoint()` to match the storage
    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
    /// author-facing label const; the accessor's identity name maps
    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
    /// docstring already carries.
    #[must_use]
    pub fn endpoint(&self) -> Option<&str> {
        self.endpoint.as_deref()
    }

    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
    /// payload-target scalar accessor every consumer that reads the
    /// edge's NATS / Kafka publish subject payload keys off — returns
    /// the author-declared `:contratos :subject` byte-string verbatim
    /// as an `Option<&str>`, borrowed from the typed slot's own
    /// `Option<String>` storage; `None` when the slot is absent (the
    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
    /// [`WitTarget::Capability`] edge carries none of the three).
    ///
    /// The `:contratos :subject` slot carries the NATS / Kafka publish
    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
    /// per-edge target selector — `orders.paid`, `events.>`, whatever
    /// subject namespace the author names on the pub-sub edge) that
    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
    /// arm's `subject: &'a str` payload when the edge's `:wit` world
    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
    /// downstream consumer that reads the payload keys off this scalar
    /// (the [`WitContract::target`] PubSub-arm payload extraction that
    /// materializes [`WitTarget::PubSub { subject }`] under the paired
    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
    /// key's subject arm that pins the payload as part of the six-tuple
    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
    /// future M4 per-edge WIT registry resolver's pub-sub-arm
    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
    /// materializer's per-edge NATS admission webhook, the future
    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
    /// as a NATS subject the operator pins per-CR).
    ///
    /// Prior to this lift the `.subject` field was accessed inline at
    /// two production sites in `caixa-core/src/aplicacao.rs` — the
    /// [`WitContract::target`] payload-shape dispatch's `let subject =
    /// self.subject.as_deref();` binding at the top of the method, and
    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
    /// field-accesses that expressed no compile-time link back to the
    /// typed slot. A future extension of the `:contratos :subject` axis
    /// to a richer author surface (an M4 promotion from `Option<String>`
    /// to a typed NATS-subject-template enum once the WIT registry
    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
    /// struct's own `:wit` field docstring, a per-cluster subject-alias
    /// table the operator pins through a future `:placement`-scoped
    /// slot, a canonicalization pass that lowercases / dedupes wildcard
    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
    /// applies per-tenant) would have had to be threaded through both
    /// open-coded copies in lockstep or the two consumers would silently
    /// disagree on which NATS subject a given edge resolves to — the
    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
    /// resolved `"tenant-a.orders.paid"` would silently split the
    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
    /// key uniqueness axis, a two-consumer split at the validator far
    /// from the source `caixa.lisp` with no field naming the payload-
    /// drift root cause. Lifting the resolution rule to a typed method
    /// on the substrate primitive means every downstream pub-sub-payload-
    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
    /// surface reaches for exactly one typed dispatch — the resolver's
    /// accept-set migrates as a unit on any future axis addition.
    ///
    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
    /// carrier axis — second `Option<&str>`-return accessor on the
    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
    /// key/value-store arm as the last unlifted per-`:contratos`
    /// `Option<String>` axis. Named `subject()` to match the storage
    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
    /// author-facing label const; the accessor's identity name maps
    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
    /// docstring already carries.
    #[must_use]
    pub fn subject(&self) -> Option<&str> {
        self.subject.as_deref()
    }

    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
    /// shaped payload-target scalar accessor every consumer that reads
    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
    /// off — returns the author-declared `:contratos :slot` byte-string
    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
    /// own `Option<String>` storage; `None` when the slot is absent
    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
    /// [`WitTarget::Capability`] edge carries none of the three).
    ///
    /// The `:contratos :slot` slot carries the key/value store
    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
    /// arm's per-edge target selector — `carts/{cart_id}`,
    /// `sessions/{tenant}/{sid}`, whatever key-template the author
    /// names on the store edge) that [`WitContract::target`] projects
    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
    /// accept-set. Every downstream consumer that reads the payload
    /// keys off this scalar (the [`WitContract::target`] Store-arm
    /// payload extraction that materializes [`WitTarget::Store { slot }`]
    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
    /// key's store arm that pins the payload as part of the six-tuple
    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
    /// the future M4 per-edge WIT registry resolver's store-arm
    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
    /// materializer's per-edge key/value admission webhook, the future
    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
    /// as a key-template the operator pins per-CR).
    ///
    /// Prior to this lift the `.slot` field was accessed inline at two
    /// production sites in `caixa-core/src/aplicacao.rs` — the
    /// [`WitContract::target`] payload-shape dispatch's `let slot =
    /// self.slot.as_deref();` binding at the top of the method, and
    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
    /// field-accesses that expressed no compile-time link back to the
    /// typed slot. A future extension of the `:contratos :slot` axis
    /// to a richer author surface (an M4 promotion from `Option<String>`
    /// to a typed key-template enum once the WIT registry stabilizes
    /// key-template parameter shapes in tatara-lisp per this struct's
    /// own `:wit` field docstring, a per-cluster slot-alias table the
    /// operator pins through a future `:placement`-scoped slot, a
    /// canonicalization pass that lowercases the bucket prefix, a
    /// per-CR fully-qualified rewrite the M4 CR materializer applies
    /// per-tenant) would have had to be threaded through both
    /// open-coded copies in lockstep or the two consumers would
    /// silently disagree on which key-template a given edge resolves
    /// to — the [`WitContract::target`] payload-extraction reading
    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
    /// would silently split the [`WitTarget::Store`]-arm rendered
    /// payload from the actual dedup-key uniqueness axis, a
    /// two-consumer split at the validator far from the source
    /// `caixa.lisp` with no field naming the payload-drift root cause.
    /// Lifting the resolution rule to a typed method on the substrate
    /// primitive means every downstream store-payload-facing consumer
    /// of the Aplicacao's per-`:contratos` payload surface reaches for
    /// exactly one typed dispatch — the resolver's accept-set migrates
    /// as a unit on any future axis addition.
    ///
    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
    /// accessors on the M3 mesh-slot payload-carrier axis — third and
    /// final `Option<&str>`-return accessor on the per-`:contratos`
    /// mesh-slot atom, closes the last unlifted per-`:contratos`
    /// `Option<String>` axis and completes the "optional per-slot
    /// payload-carrier scalar" projection pattern the peer HTTP /
    /// pub-sub arms established across the three payload-shape
    /// dispatch arms. Named `slot()` to match the storage field's
    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
    /// author-facing label const; the accessor's identity name maps
    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
    /// docstring already carries.
    #[must_use]
    pub fn slot(&self) -> Option<&str> {
        self.slot.as_deref()
    }

    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
    /// caller-callee-pair accessor every consumer that constructs an
    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
    /// caller-callee pair keys off — returns the author-declared
    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
    /// owned `(String, String)` tuple, projected through the lifted
    /// [`WitContract::source`] / [`WitContract::destination`] scalar
    /// accessors so any future rebrand on the caller-arm / callee-arm
    /// projection axis (an M4 per-cluster caller-alias table the
    /// operator pins through a future `:placement`-scoped slot, a
    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
    /// a per-`:membros` alias overlay from the future `:membros
    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
    /// acknowledges) reaches every diagnostic-construction site by
    /// construction.
    ///
    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
    /// owned form" primitive every per-`:contratos` diagnostic variant on
    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
    /// nine variants [`AplicacaoError::EmptyWit`],
    /// [`AplicacaoError::ContratoEndpointEmpty`],
    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
    /// [`AplicacaoError::ContratoEndpointInvalid`],
    /// [`AplicacaoError::ContratoSubjectEmpty`],
    /// [`AplicacaoError::ContratoSubjectInvalid`],
    /// [`AplicacaoError::ContratoSlotEmpty`],
    /// [`AplicacaoError::ContratoSlotInvalid`], and
    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
    /// para: String` field pair the constructor site reads verbatim off
    /// the [`WitContract`] the diagnostic points at, so a diagnostic
    /// whose `de:` and `para:` labels silently drift off the source
    /// caller/callee — a per-cluster caller-alias rewrite that landed on
    /// one variant's inline `de: c.de.clone()` field access but not on
    /// its sibling variant's, an accidental swap of the `de:` and `para:`
    /// arms in a copy-paste of the constructor block — would emit a
    /// build-time error whose "which caixa is at fault" question the
    /// operator answers wrongly, far from the source `caixa.lisp`.
    ///
    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
    /// pair was inlined at seven [`WitContract::target`] error-
    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
    /// the [`AplicacaoError::ContratoSlotEmpty`] /
    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
    /// two [`AplicacaoSpec::validate`] error-construction sites (the
    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
    /// insert-first-seen closure) — nine open-coded `.de.clone() +
    /// .para.clone()` pairs that expressed no compile-time contract that
    /// the caller-arm and callee-arm arms of the same diagnostic
    /// construction reach for the same [`WitContract`] instance or that
    /// the `de:` and `para:` label pair binds to the fields the author
    /// declared. Any future rebrand on the axis — an M4 per-cluster
    /// caller/callee-alias rewrite the operator pins through a future
    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
    /// per-CR fully-qualified namespace prefix the M4
    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
    /// per-tenant, a canonicalization pass that lowercases the caller +
    /// callee identifiers post-parse — would have had to be threaded
    /// through every open-coded copy in lockstep or one variant's
    /// diagnostic would silently name a different caller/callee pair
    /// than its peer, silently degrading the "which caixa is at fault"
    /// self-locating signal every operator-facing typed diagnostic
    /// exists to carry. Lifting the pair to a typed method on the
    /// substrate primitive means every downstream diagnostic-construction
    /// site reaches for exactly one typed dispatch — the resolver's
    /// projection migrates as a unit on any future axis addition.
    ///
    /// Peer of the sibling per-`:contratos` scalar accessor family
    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
    /// scalar-value axes — first composite-projection accessor on the
    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
    /// form `.clone()` field-accesses that pair the sibling
    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
    /// one typed dispatch. Named `edge_pair()` to reflect the identity
    /// name of the projected tuple (the typed-edge caller-callee pair,
    /// distinct from the sibling triple-projection
    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
    /// closure in [`WitContract::target`] + the paired
    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
    /// site's `(de, para, wit)` triple onto one typed dispatch).
    #[must_use]
    pub fn edge_pair(&self) -> (String, String) {
        (self.source().to_string(), self.destination().to_string())
    }

    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
    /// :wit)` triple every per-edge diagnostic constructor that names
    /// all three axes threads verbatim into its `de:` / `para:` /
    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
    /// / missing-target / invalid-wit / capability-with-payload arms
    /// (eight sites all shape `let (de, para, wit) = edge();
    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
    /// accessor landed) and the sibling
    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
    /// constructor (which paired `edge_pair()` for the `(de, para)`
    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
    /// typed-dispatch + raw-field-access shape the sibling accessor
    /// family already flagged as a drift risk). Nine total call sites
    /// collapse onto this helper.
    ///
    /// Lifted with the same one-source-of-truth discipline
    /// [`WitContract::edge_pair`] carries on the paired
    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
    /// arms compose through the lifted [`WitContract::source`] /
    /// [`WitContract::destination`] / [`WitContract::world_ref`]
    /// scalar accessors byte-for-byte (pinned by the paired
    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
    /// composition-pin), so any future rebrand on the per-`:contratos`
    /// caller / callee / world-ref axis (an M4 per-cluster
    /// caller/callee-alias rewrite the operator pins through a future
    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
    /// per-CR fully-qualified namespace prefix the M4
    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
    /// on `source()` / `destination()`, a per-CR canonicalization pass
    /// that lowercases the WIT world ref post-parse) migrates as a
    /// single caixa-core edit rather than a coordinated rewrite of
    /// nine open-coded triple-constructors.
    ///
    /// Peer of the sibling per-`:contratos` composite-projection
    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
    /// composite-value axes — closes the last unlifted owned-form
    /// composite-tuple axis on the per-`:contratos` diagnostic-
    /// construction surface. Named `edge_triple()` to reflect the
    /// identity name of the projected tuple (the typed-edge
    /// caller-callee-wit triple, sibling to the caller-callee-only
    /// pair `edge_pair()` returns).
    #[must_use]
    pub fn edge_triple(&self) -> (String, String, String) {
        (
            self.source().to_string(),
            self.destination().to_string(),
            self.world_ref().to_string(),
        )
    }

    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
    /// dedups typed edges keys off — routes through the lifted
    /// [`WitContract::source`] / [`WitContract::destination`] /
    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
    /// type alias's six axes migrate as a unit on any future axis
    /// addition (adding a seventh field to [`WitContract`] is one
    /// [`ContratoIdentity`] alias edit + one accessor addition + one
    /// arm here, not a coordinated rewrite of every open-coded
    /// six-tuple builder that dedups on the identity axis).
    ///
    /// Sibling of [`WitContract::edge_pair`] /
    /// [`WitContract::edge_triple`] on the composite-projection axis:
    /// the pair projects the caller-callee axes, the triple extends it
    /// with the world-ref, this method extends it with the three
    /// payload-carrier axes. Every projection returns the same six
    /// scalar accessors' outputs; the three methods differ only in
    /// which arms they surface.
    #[must_use]
    pub fn identity(&self) -> ContratoIdentity<'_> {
        (
            self.source(),
            self.destination(),
            self.world_ref(),
            self.endpoint(),
            self.subject(),
            self.slot(),
        )
    }

    /// True when this contract targets an HTTP-shaped WIT world.
    #[must_use]
    pub fn is_http(&self) -> bool {
        wit_shape_is_http(self.world_ref())
    }

    /// True when this contract targets a pub-sub-shaped WIT world.
    #[must_use]
    pub fn is_pubsub(&self) -> bool {
        wit_shape_is_pubsub(self.world_ref())
    }

    /// True when this contract targets a key/value-shaped WIT world.
    #[must_use]
    pub fn is_store(&self) -> bool {
        wit_shape_is_store(self.world_ref())
    }

    /// True when this contract's caller equals its callee — a
    /// structurally degenerate typed edge that no `:contratos` entry can
    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
    /// Servico B" is an *inter*-Servico contract between two distinct
    /// graph nodes). A Servico contracting with itself resolves to an
    /// in-process call the wasm-engine never routes through the mesh at
    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
    /// per-edge policy can express the intended shape — the pub-sub
    /// path silently rendered a self-allow rule that is a no-op (intra-
    /// pod traffic bypasses the mesh entirely), and the synchronous
    /// paths surfaced as a misleading `ContratoCycle` whose path was
    /// `["cart", "cart"]` — framing a self-edge as a multi-node
    /// deadlock. Every downstream consumer that must reject the shape
    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
    /// gate at caixa-core/src/aplicacao.rs:5559, every future
    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
    /// axis, every future adjacency-graph builder that must skip self-
    /// edges rather than fold them into an incidental cycle) now keys
    /// off exactly one typed dispatch on the substrate primitive, so
    /// any future rebrand on the axis (an M4-typed-caller enum whose
    /// identity comparison rule the accessor could route through, an
    /// operator-side per-cluster caller/callee-alias table the
    /// materializer resolves per-CR before the equality probe, a
    /// promotion of the pointwise `==` to a set-membership check once
    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
    /// so a per-replica self-edge is rejected under the same predicate)
    /// migrates as a single caixa-core edit rather than a coordinated
    /// rewrite of every downstream self-edge consumer. Composes
    /// byte-for-byte through the lifted [`Self::source`] /
    /// [`Self::destination`] scalar accessors — the accessor pair every
    /// per-`:contratos` scalar-value axis already routes through — so
    /// any future rebrand of the underlying `:de` / `:para` storage
    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
    /// a per-Aplicacao interning arena the M4 CR materializer authors,
    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
    /// same one body without a coordinated per-consumer rewrite.
    ///
    /// Sibling in shape to the peer per-`:contratos` shape-predicate
    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
    /// on the `:wit` world-ref axis — extended onto the per-edge
    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
    /// partition the WIT-shape-space; `is_self_loop` partitions the
    /// caller-callee identity-space. Named `is_self_loop()` to reflect
    /// the graph-theoretic identity of the shape (a loop from a graph
    /// node to itself, distinct from the sibling multi-node
    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
    /// variant already carrying the term.
    #[must_use]
    pub fn is_self_loop(&self) -> bool {
        self.source() == self.destination()
    }

    /// Typed view of the contract's payload target. Enforces that the
    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
    /// fields agree, and that each carried value is itself
    /// value-shape valid:
    ///
    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
    ///     `PathPrefix` invariant — same shape required of `:entrada
    ///     :paths`)
    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
    ///     non-empty (NATS / Kafka publish without a subject is a
    ///     no-op subscribe, never the author's intent)
    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
    ///     non-empty (an empty slot template addresses the bucket
    ///     root, defeating the per-key isolation the slot exists for)
    ///   - Anything else ⇒ none of the three; the contract is a pure
    ///     typed capability edge with no payload selector.
    ///
    /// Translates the Apollo Federation discipline ("conflicts are
    /// errors at compile time, not warnings at runtime";
    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
    /// a contract whose WIT shape disagrees with its target field, or
    /// whose target field carries a value-shape-invalid string, is a
    /// build error — not a silent renderer drop. The returned
    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
    /// non-empty (and absolute, for `Http`); every downstream consumer
    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
    /// the M4 per-edge policy resolver) can rely on that without
    /// re-checking.
    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
        // Route the HTTP-shaped payload-target extraction through the
        // lifted [`WitContract::endpoint`] accessor rather than the raw
        // `self.endpoint.as_deref()` field access — the two production
        // consumers of the per-`:contratos :endpoint` HTTP-shaped
        // payload-carrier scalar (this method's Http-arm payload
        // extraction, the [`AplicacaoSpec::validate`] duplicate-
        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
        // off exactly one typed dispatch on the substrate primitive, so
        // any future rebrand on the axis (an M4 per-cluster endpoint-
        // alias rewrite, a per-CR fully-qualified path prefix the M4
        // materializer applies per-tenant, an M4 promotion from
        // `Option<String>` to a typed HTTP path-template enum) migrates
        // as a single caixa-core edit rather than a coordinated rewrite
        // of the two call sites — peer of the sibling M3 per-`:placement`
        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
        let endpoint = self.endpoint();
        let subject = self.subject();
        // Route the store-arm payload-carrier scalar through the
        // lifted [`WitContract::slot`] accessor rather than the raw
        // `self.slot.as_deref()` field access — the two production
        // consumers of the per-`:contratos :slot` key/value-store-
        // shaped payload-carrier scalar (this method's Store-arm
        // payload extraction, the [`AplicacaoSpec::validate`]
        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
        // arm) now key off exactly one typed dispatch on the substrate
        // primitive. Closes the last unlifted per-`:contratos`
        // `Option<String>` axis, completing the payload-carrier
        // accessor family peer of the sibling per-`:contratos`
        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
        // (90de675) lifts across the HTTP / pub-sub arms.
        let slot = self.slot();
        // Route the local `(de, para, wit)` triple-projection closure
        // through the lifted [`WitContract::edge_triple`] typed accessor
        // rather than re-inlining `(self.de.clone(), self.para.clone(),
        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
        // triple-carrying diagnostic constructors below (wrong-target /
        // missing-target on all three payload arms + capability-with-
        // payload + invalid-wit) now key off exactly one typed dispatch
        // on the substrate-primitive composite projection, sibling to
        // the peer [`WitContract::edge_pair`]-routed
        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
        // diagnostic constructors on the same per-`:contratos`
        // diagnostic-construction surface.
        let edge = || self.edge_triple();

        // The `:wit` value drives every downstream dispatch — the
        // is_http/is_pubsub/is_store prefix matchers below, the
        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
        // exclusion. Until this gate landed `target()` accepted any
        // non-empty string and silently demoted unrecognized shapes to
        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
        // package, the paste-from-binary footgun a multi-line blob
        // accidentally landing in the slot, the un-percent-encoded
        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
        // routing, got L4-only" footgun. Empty is still pre-checked at
        // the [`AplicacaoSpec::validate`] call site via the narrower
        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
        // validate layer); the value-shape gate here picks up the
        // structurally-invalid non-empty cases the empty check misses,
        // and remains correct under direct `target()` calls outside
        // validate (the predicate's defensive empty arm returns a
        // parser-shaped reason rather than silently falling through to
        // the Capability arm). Same trajectory as c4213a4 (WitContract
        // endpoint/subject/slot value-shape gates lifted into
        // `target()`) on the peer payload axes.
        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
            let (de, para, wit) = edge();
            return Err(AplicacaoError::ContratoWitInvalid {
                de,
                para,
                wit,
                reason,
            });
        }

        if self.is_http() {
            if subject.is_some() || slot.is_some() {
                let (de, para, wit) = edge();
                return Err(AplicacaoError::ContratoWrongTarget {
                    de,
                    para,
                    wit,
                    expected: WitTarget::HTTP_FIELD_NAME,
                });
            }
            let ep = endpoint.ok_or_else(|| {
                let (de, para, wit) = edge();
                AplicacaoError::ContratoMissingTarget {
                    de,
                    para,
                    wit,
                    expected: WitTarget::HTTP_FIELD_NAME,
                }
            })?;
            if ep.is_empty() {
                let (de, para) = self.edge_pair();
                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
            }
            if !ep.starts_with('/') {
                let (de, para) = self.edge_pair();
                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
                    de,
                    para,
                    endpoint: ep.to_string(),
                });
            }
            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
            // API v1 HTTPPathMatch.value admission grammar with the
            // sibling `:entrada :paths` axis. Until this gate landed
            // `target()` only refused the empty string + the missing-
            // leading-`/` form; a structurally invalid endpoint
            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
            // path-traversal segment, the >1024-byte slug) silently
            // passed validate and the failure surfaced at apply time
            // as a Cilium policy rejection / silent traffic drop, far
            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
            // grammar `:entrada :paths` already gates (55410e4), now
            // shared with `:contratos :endpoint` through the lifted
            // `crate::render::is_gateway_api_http_path` predicate.
            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
                let (de, para) = self.edge_pair();
                return Err(AplicacaoError::ContratoEndpointInvalid {
                    de,
                    para,
                    endpoint: ep.to_string(),
                    reason,
                });
            }
            return Ok(WitTarget::Http { endpoint: ep });
        }
        if self.is_pubsub() {
            if endpoint.is_some() || slot.is_some() {
                let (de, para, wit) = edge();
                return Err(AplicacaoError::ContratoWrongTarget {
                    de,
                    para,
                    wit,
                    expected: WitTarget::PUBSUB_FIELD_NAME,
                });
            }
            let s = subject.ok_or_else(|| {
                let (de, para, wit) = edge();
                AplicacaoError::ContratoMissingTarget {
                    de,
                    para,
                    wit,
                    expected: WitTarget::PUBSUB_FIELD_NAME,
                }
            })?;
            if s.is_empty() {
                let (de, para) = self.edge_pair();
                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
            }
            // The `:subject` lands at runtime as the NATS subject the
            // producer publishes to and the consumer subscribes from.
            // Until this gate landed `target()` only refused the
            // empty string; a structurally invalid subject
            // (`"foo..bar"` — empty token between separators,
            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
            // server's subject parser rejects, `"foo bar"` —
            // un-percent-encoded whitespace, `"foo.café"` —
            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
            // empty leading/trailing tokens, the >256-byte
            // paste-from-binary slug) silently passed validate and
            // the failure surfaced at runtime as a NATS server-side
            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
            // a silent message drop, far from the source caixa.lisp.
            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
            // trajectory `:contratos :endpoint` (4f0390b) and
            // `:contratos :wit` (6226bf4) already gate, now shared
            // with `:contratos :subject` through the lifted
            // `crate::render::is_nats_subject` predicate.
            if let Err(reason) = crate::render::is_nats_subject(s) {
                let (de, para) = self.edge_pair();
                return Err(AplicacaoError::ContratoSubjectInvalid {
                    de,
                    para,
                    subject: s.to_string(),
                    reason,
                });
            }
            return Ok(WitTarget::PubSub { subject: s });
        }
        if self.is_store() {
            if endpoint.is_some() || subject.is_some() {
                let (de, para, wit) = edge();
                return Err(AplicacaoError::ContratoWrongTarget {
                    de,
                    para,
                    wit,
                    expected: WitTarget::STORE_FIELD_NAME,
                });
            }
            let sl = slot.ok_or_else(|| {
                let (de, para, wit) = edge();
                AplicacaoError::ContratoMissingTarget {
                    de,
                    para,
                    wit,
                    expected: WitTarget::STORE_FIELD_NAME,
                }
            })?;
            if sl.is_empty() {
                let (de, para) = self.edge_pair();
                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
            }
            // Value-shape gate on the third (and last) typed payload
            // axis the `WitContract::target` dispatch carries — the
            // peer of [`crate::render::is_gateway_api_http_path`] for
            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
            // for `:subject` (63e18a0). Until this gate landed
            // `target()` only refused the empty string; a structurally
            // invalid slot (`"check out/$order"` — un-percent-encoded
            // whitespace whose runtime behavior varies unpredictably
            // across kv backends, `"checkout/\x01order"` — control
            // character that Redis admits but corrupts on next read
            // and DynamoDB rejects outright, `"chéckout/$order"` —
            // un-percent-encoded non-ASCII byte each backend re-encodes
            // differently, `"checkout\n/$order"` — embedded newline,
            // the 513-byte paste-from-binary slug) silently passed
            // validate and surfaced at runtime as a per-backend kv
            // write rejection (DynamoDB / etcd) or as a silent
            // next-read corruption (Redis-via-RESP3), far from the
            // source caixa.lisp with no field naming which `:contratos`
            // edge carried the typo. The lifted predicate makes the
            // kv-backend intersection-floor a substrate-level
            // invariant at validate time, not a runtime "this passed
            // validate but the kv backend rejected on first write"
            // surprise — closes the typed payload-axis value-shape
            // trajectory across all three legs of the four
            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
            // that caixa-mesh + the future kv emitters land in.
            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
                let (de, para) = self.edge_pair();
                return Err(AplicacaoError::ContratoSlotInvalid {
                    de,
                    para,
                    slot: sl.to_string(),
                    reason,
                });
            }
            return Ok(WitTarget::Store { slot: sl });
        }

        // Unrecognized WIT world — must not carry any payload target.
        if endpoint.is_some() || subject.is_some() || slot.is_some() {
            let (de, para, wit) = edge();
            return Err(AplicacaoError::ContratoWrongTarget {
                de,
                para,
                wit,
                expected: WitTarget::CAPABILITY_EXPECTED,
            });
        }
        Ok(WitTarget::Capability)
    }
}

/// Borrowed identity key for the typed-graph duplicate-`:contratos`
/// gate (see [`AplicacaoSpec::validate`]): every field that
/// distinguishes one contract from another, in declaration order
/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
/// with equal [`ContratoIdentity`]s are the same typed edge declared
/// twice — the graph-edge analogue of duplicate `:membros` /
/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
/// clippy's `type_complexity` lint (and so a future axis added to
/// `WitContract` is one alias edit, not a coordinated rewrite of
/// every set instantiation).
pub type ContratoIdentity<'a> = (
    &'a str,
    &'a str,
    &'a str,
    Option<&'a str>,
    Option<&'a str>,
    Option<&'a str>,
);

/// Typed view of a [`WitContract`]'s payload target. Each variant
/// carries the field its WIT shape requires; constructing a `Http`
/// view without an endpoint is impossible by the type system.
///
/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
/// instead of probing `Option<String>` fields one by one — the
/// "which payload field is set?" question is answered once, at
/// validation time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
pub enum WitTarget<'a> {
    /// HTTP-shaped WIT world. Carries the configured request path.
    Http { endpoint: &'a str },
    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
    ///
    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
    /// method name byte-identical to the sibling
    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
    /// arm-discriminator that routes through
    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
    /// through `matches!` on the variant), so the two arm-discriminator
    /// axes — target-side variant-arm and shape-side ref-prefix — reach
    /// every downstream consumer through the same `is_pubsub()` name.
    #[is_variant(name = "pubsub")]
    PubSub { subject: &'a str },
    /// Key-value-shaped WIT world. Carries the slot template.
    Store { slot: &'a str },
    /// A typed capability edge with no payload selector — the WIT
    /// world stands on its own (rare; reserved for plain capability
    /// imports or M4-and-later WIT worlds we haven't shaped yet).
    Capability,
}

impl<'a> WitTarget<'a> {
    /// Canonical author-facing `:contratos` payload field name for the
    /// HTTP-shaped arm — the `expected: &'static str` scalar the
    /// [`AplicacaoError::ContratoMissingTarget`] /
    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
    /// the `feira app graph` verb prints. Peer of
    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
    /// on the payload-field-name axis; declared as a peer const next
    /// to the [`WitTarget::Http`] variant so a future rename on the
    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
    /// :endpoint …)))` field lands in exactly one place, not scattered
    /// across the [`WitContract::target`] gate's six `expected:`
    /// literals, the label template, and every downstream consumer
    /// that prints a per-arm prefix. Same trajectory as the peer
    /// [`WitTarget::label`] lift (174e96a): a single source of truth
    /// for the arm's shape, next to the variant declaration.
    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
    /// Canonical author-facing `:contratos` payload field name for the
    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
    /// Canonical author-facing `:contratos` payload field name for the
    /// key/value-store-shaped arm. Peer of
    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
    /// on the payload-field-name axis; see
    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
    pub const STORE_FIELD_NAME: &'static str = "slot";

    /// Canonical stable human-readable label the payload-less
    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
    /// the byte-string every consumer that formats a payload-less
    /// typed capability edge as text lands on (the
    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
    /// naming which identical edge was declared twice, the future
    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
    /// policy resolver's audit view, the operator's mesh-graph audit).
    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
    /// author-facing label-scalar consts — the same
    /// "one canonical declaration per arm, next to the variant, so a
    /// future rename lands in one place" discipline extended to the
    /// payload-less arm. Until this lift landed the byte-string sat
    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
    /// match arm, once in the pin test asserting the label's
    /// [`WitTarget::Capability`] output — with no compile-time link
    /// between the two: a rebrand on either side (an operator-facing
    /// vocabulary shift, a per-consumer disambiguation like
    /// `"(capability — no payload; typed edge only)"`) would silently
    /// desynchronize until a downstream consumer surfaced the drift at
    /// runtime.
    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";

    /// Canonical `expected:` scalar the
    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
    /// through for the payload-less [`WitTarget::Capability`] arm — the
    /// byte-string authors read as "this WIT world's shape is not one
    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
    /// [`Self::STORE_FIELD_NAME`] consts on the
    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
    /// same "which payload field name goes in the diagnostic" dispatch
    /// the three payload-arm consts cover, extended to the payload-less
    /// arm. Until this lift landed the byte-string sat twice — once
    /// inline in the [`Self::target`] Capability-arm rejection at the
    /// production dispatch, once in the pin test asserting the
    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
    /// no compile-time link between the two: a rebrand on either side
    /// (an author-facing vocabulary shift to `"capability"` /
    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
    /// [`WitTarget::Capability`] into per-shape peers) would silently
    /// desynchronize until a downstream consumer surfaced the drift at
    /// runtime. Same "one canonical declaration per arm, next to the
    /// variant, so a future rename lands in one place" discipline the
    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
    /// established for the payload-less arm's human-readable label
    /// axis; this lift extends it onto the peer diagnostic-scalar axis
    /// so both halves of the "how does the Capability arm surface at
    /// its two consumer axes (human-readable label, wrong-target
    /// diagnostic)" pipeline route through peer consts declared next
    /// to the variant.
    ///
    /// Pairwise-distinctness against the three payload-arm scalars
    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
    /// test — the 4-way closure of the 3-way
    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
    /// the `ContratoWrongTarget::expected` axis, matching the peer
    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
    /// scalar-value distinctness discipline the sibling M3 typed-enum
    /// discriminator axis already carries.
    pub const CAPABILITY_EXPECTED: &'static str = "none";

    /// The `(author-facing field name, payload)` pair this typed target
    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
    /// [`Self::Store`], `None` for the payload-less
    /// [`Self::Capability`] arm.
    ///
    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
    /// (formats `":{field} {payload:?}"` on `Some`, falls to
    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
    /// (returns the first component) route through, so a future
    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
    /// exactly one new match-arm here (a compile-time exhaustiveness
    /// error otherwise), not a coordinated three-way rewrite of the
    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
    /// + every downstream consumer that reaches for the pair.
    ///
    /// Until this lift landed the three payload arms sat in
    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
    /// invocations (one per variant, each hand-quoting the paired
    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
    /// "same shape, written N times" duplication THEORY.md §I.3.5
    /// ("Generation first, composition second, hand-authoring last;
    /// the duplication budget is zero") promotes to a build-time
    /// concern, with each per-arm site paired to its own const with no
    /// compile-time link between the format template and the arm's
    /// payload extraction.
    #[must_use]
    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
        match *self {
            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
            WitTarget::Capability => None,
        }
    }

    /// The canonical author-facing `:contratos` payload field name
    /// this typed target arm carries (`Http` → `Some("endpoint")`,
    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
    /// `None` for the payload-less `Capability` arm.
    ///
    /// Routes through [`Self::payload_pair`] — the single 4-arm
    /// dispatch [`Self::label`] also reads — so a future variant
    /// addition is one match-arm edit at [`Self::payload_pair`], not a
    /// per-consumer rewrite. Same "exhaustive-match at one canonical
    /// dispatch, thin projections at each consumer" trajectory the
    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
    #[must_use]
    pub const fn field_name(&self) -> Option<&'static str> {
        match self.payload_pair() {
            Some((f, _)) => Some(f),
            None => None,
        }
    }

    /// Render this typed target as a stable human-readable label
    /// (`:endpoint "/charge"`, `:subject "events.x"`,
    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
    /// the WIT world is a pure capability edge).
    ///
    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
    /// gate so the diagnostic names *which* identical edge was
    /// declared twice (not just which `(de, para, wit)` triple).
    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
    /// on the payload-carrying arms (`Some((field, payload)) →
    /// format!(":{field} {payload:?}")`) and through the lifted
    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
    /// [`Self::Capability`] arm — so a future variant addition (the
    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
    /// `Queue`-shaped peer) becomes a single new match-arm on
    /// [`Self::payload_pair`] rather than a rewrite of this template
    /// (and every downstream consumer that reaches for the label
    /// shape: the per-edge policy resolver in M4, the `feira app
    /// graph` view, the operator's mesh-graph audit). Until this
    /// lift landed the three payload arms carried three near-identical
    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
    /// [`Self::Capability`] arm carried the payload-less byte-string
    /// twice (once inline here, once in the pin test) — closing the
    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
    /// / 4a1e490) peer-const lifts already established for the
    /// payload-carrying arms.
    #[must_use]
    pub fn label(&self) -> String {
        match self.payload_pair() {
            Some((field, payload)) => format!(":{field} {payload:?}"),
            None => Self::CAPABILITY_LABEL.to_string(),
        }
    }
}

/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
/// pretty-printed byte-string every consumer that formats a typed
/// payload target as user-facing text lands on (the
/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
/// graph` per-`:contratos`-edge payload column that reaches the graph
/// verb through `format!("{target}")`, the future M4 per-edge policy
/// resolver's per-edge audit-log line, the operator's mesh-graph
/// per-edge inspection view) reaches for the same lifted
/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
/// routes through — extending the three-path-convergence
/// (`Debug` for structural inspection, `Display` for user-facing text,
/// per-arm typed accessor for the canonical byte-string) discipline the
/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
/// onto the fourth (and only remaining) typed-shape-discriminator axis
/// on the caixa surface.
///
/// Pre-lift the two paths were structurally independent — every consumer
/// reaching for a payload byte-string past the [`WitTarget::label`]
/// helper had to pick between three paths ([`WitTarget::label`],
/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
/// that reached for `format!("{target}")` — the canonical shape every
/// user-facing pretty-print site on the sibling typed-enum axes already
/// uses — would silently land on the `Debug` derive's structural output
/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
/// than the `label()` helper's stable byte-string (`:endpoint
/// "/charge"` — the author-facing `:contratos` keyword form) the
/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
/// already threads through. The two spellings would diverge silently in
/// every downstream diagnostic / graph / audit line reached through
/// `format!` rather than through the `label()` helper. Routing
/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
/// path: every `format!("{v}")` call reaches the same
/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
/// and the duplicate-`:contratos` gate already route through, so a
/// future variant addition (the M4-and-later per-edge WIT registry may
/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
/// consumer at exactly one place — the [`WitTarget::payload_pair`]
/// match — rather than fanning out through hand-rolled per-arm
/// [`std::fmt::Display`] arms.
///
/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
/// is the typed view returned by [`WitContract::target`], not a
/// closed-set discriminator enum with a gen-platform Discriminant
/// registration, so the `Debug` derive's structural output (which every
/// `{v:?}` consumer still reaches) stays distinct from the `Display`
/// helper's stable pretty-printed byte-string. `Debug` reveals variant
/// shape for structural inspection; `Display` (via `label`) reveals the
/// stable author-facing payload projection.
///
/// Pin tests
/// [`tests::wit_target_display_routes_through_label_helper`] and
/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
/// assert the two paths agree byte-for-byte on every variant, so a
/// future variant addition or `label()` reimplementation that hand-rolls
/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
/// build error visible at caixa-core test time, not a silent
/// per-consumer dispatch miss at diagnostic / audit / graph time.
impl std::fmt::Display for WitTarget<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.label())
    }
}

// ── one Aplicacao member ─────────────────────────────────────────────

/// A Servico participating in the Aplicacao. Same shape as
/// `crate::supervisor::ChildSpec` but without a restart policy —
/// supervision is per-Servico (each member has its own
/// `:supervisor`), the Aplicacao orchestrates *placement*.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Membro {
    /// Member caixa's `:nome`. Resolves through the same dep
    /// resolution path as `crate::dep::Dep`.
    pub caixa: String,

    /// Semver constraint.
    pub versao: String,
}

impl Membro {
    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
    /// accessor every consumer that reads the member's Servico identity
    /// keys off — returns the author-declared `:membros :caixa`
    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
    /// own [`String`] storage.
    ///
    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
    /// participating in the Aplicacao — validated by
    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
    /// [`validate_no_self_membership`]) — and every downstream consumer
    /// that fans on the member's identity keys off this scalar (the
    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
    /// lookup, the per-`:membros` duplicate gate's dedup key, the
    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
    /// identity, the self-membership gate, the
    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
    /// CR materializer's per-member resolver).
    ///
    /// Prior to this lift the `.caixa` byte-string was read inline at
    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
    /// set collector at
    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
    /// [`validate_membros`] validation-side member-caixa gate at
    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
    /// per-member duplicate-gate dedup key at
    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
    /// [`validate_no_self_membership`] self-loop gate at
    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
    /// expressed no compile-time link back to the typed slot. Every
    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
    /// `name:` axis, so a future extension of the `:membros :caixa`
    /// axis to a richer author surface — a per-cluster alias table the
    /// operator pins through a future `:placement`-scoped slot, a
    /// namespace-qualified rewrite the M4 CR materializer applies
    /// per-CR, a per-member overlay from the future `:membros
    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
    /// acknowledges — would have had to be threaded through every
    /// open-coded copy in lockstep or one consumer would silently
    /// disagree with the peers on which caixa a given member resolves
    /// to. A member-set lookup that treated the name as `"cart"` while
    /// the peer adjacency map treated it as `"tenant-a/cart"` would
    /// silently split the `:contratos` membership-lookup diagnostic from
    /// the cycle-detector's node identity — a two-consumer split at the
    /// validator far from the source `caixa.lisp` with no field naming
    /// the identity-drift root cause. Lifting the resolution rule to a
    /// typed method on the substrate primitive means every downstream
    /// consumer of the Aplicacao's per-`:membros` identity surface
    /// reaches for exactly one typed dispatch — the resolver's
    /// accept-set migrates as a unit on any future axis addition.
    ///
    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
    /// destination-Servico scalar accessors — same "one typed dispatch
    /// on the substrate primitive, thin projections at each consumer"
    /// discipline extended onto the per-`:membros` member-caixa `:nome`
    /// byte-string axis. Named `nome()` to match the tatara-lisp
    /// author-surface term the field's docstring already reaches for
    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
    /// already carries — the accessor's name maps directly onto the
    /// canonical caixa-identity vocabulary rather than shadowing the
    /// field's storage-side `caixa` label.
    #[must_use]
    pub fn nome(&self) -> &str {
        self.caixa.as_str()
    }

    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
    /// requirement scalar accessor every consumer that reads the
    /// member's version pin keys off — returns the author-declared
    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
    /// from the typed slot's own [`String`] storage.
    ///
    /// The `:membros :versao` slot carries the Cargo-shaped semver
    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
    /// pins which release of the member-caixa the Aplicacao composes
    /// against — the same requirement grammar the peer `:deps :versao`
    /// / `:children :versao` axes carry, resolved through the shared
    /// [`crate::render::require_valid_versao_requirement`] cascade and
    /// the shared [`crate::version::parse_requirement`] parser. Every
    /// downstream consumer that fans on the member's version pin keys
    /// off this scalar (the [`validate_membros`] per-member requirement
    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
    /// m.nome(), m.versao_requirement())` line, every future per-cluster
    /// version-lock overlay the operator pins through a future
    /// `:placement`-scoped slot, the future
    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
    /// version resolver, the future `feira app deploy` pipeline's
    /// per-member lacre BLAKE3-closure lookup).
    ///
    /// Prior to this lift the `.versao` byte-string was accessed inline
    /// at two `&str`-shaped sites — the [`validate_membros`]
    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
    /// …)` and the `feira app graph` per-member printer's `println!(
    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
    /// prior to this lift) — two open-coded field-accesses that expressed
    /// no compile-time link back to the typed slot. A future extension of
    /// the `:membros :versao` axis to a richer author surface (a
    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
    /// flow, a lacre-projected concrete-version rewrite the operator
    /// materializes at CR-admission time, a future `:membros :versao-lock`
    /// per-cluster override slot) would have had to be threaded through
    /// every open-coded copy in lockstep or one consumer would silently
    /// disagree with the peers on which release constraint a given
    /// member resolves to. Lifting the resolution rule to a typed method
    /// on the substrate primitive means every downstream requirement-
    /// facing consumer reaches for exactly one typed dispatch — the
    /// resolver's accept-set migrates as a unit on any future axis
    /// addition.
    ///
    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
    /// member-caixa `:nome` scalar accessor — the pair
    /// `(nome(), versao_requirement())` jointly projects the
    /// `(caixa, versao)` field pair every renderer that fans on
    /// per-member identity + version pin keys off, closing the last
    /// unlifted per-`:membros` scalar axis so every downstream
    /// per-`:membros` reader now routes through a typed dispatch on the
    /// substrate primitive. Named `versao_requirement()` rather than
    /// `versao()` because the field's storage-side `.versao` label is
    /// already the author-surface term (`:versao`); the accessor's name
    /// carries the semantic role — the semver *requirement* string the
    /// shared [`crate::version::parse_requirement`] entry-point consumes
    /// — so a raw field access and a typed dispatch read differently at
    /// every consumer site.
    ///
    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
    /// destination-Servico scalar accessors — same "one typed dispatch
    /// on the substrate primitive, thin projections at each consumer"
    /// discipline extended onto the per-`:membros` member-`:versao`
    /// semver-requirement byte-string axis.
    #[must_use]
    pub fn versao_requirement(&self) -> &str {
        self.versao.as_str()
    }
}

// ── mesh-level policies ──────────────────────────────────────────────

/// Mesh policies that apply to every `:contratos` edge unless
/// overridden per-edge in M4. V0 is a single global policy block.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct MeshPolicy {
    /// Per-call timeout. Authored as a duration string (`"30s"`).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "supervisor::duration_codec"
    )]
    pub timeout: Option<Duration>,

    /// Number of retries on transient failure. None = no retries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retries: Option<u32>,

    /// Circuit breaker config. Trips after N failures within W
    /// duration; closes after a cooldown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub circuit_breaker: Option<CircuitBreaker>,

    /// Whether mTLS is required for every contrato. Default: true
    /// (sandboxing-by-default; explicit opt-out only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mtls_required: Option<bool>,

    /// Token-bucket rate limit. Authored as `"100/s"` or
    /// `"5000/m"`; stored as `(rate, window)`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "rate_limit_codec"
    )]
    pub rate_limit: Option<RateLimit>,
}

impl MeshPolicy {
    /// True when no `:politicas` axis carries a value — every field is
    /// `None`. The same emptiness contract every other M2/M3 typed
    /// surface carries ([`crate::LimitsSpec::is_empty`],
    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
    /// typed slot onto a cluster artifact key off this predicate to
    /// decide "emit the slot" vs "skip the slot entirely", so an
    /// authored-but-unset `:politicas (())` round-trips to a rendered
    /// artifact that's structurally identical to one that omits the
    /// slot. Lifted as a typed predicate (rather than per-renderer
    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
    /// not a coordinated rewrite of every consumer that's reaching
    /// for the emptiness semantic.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.timeout().is_none()
            && self.retries().is_none()
            && self.circuit_breaker().is_none()
            && self.mtls_required().is_none()
            && self.rate_limit().is_none()
    }

    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
    /// per-call-deadline scalar accessor every consumer of the
    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
    /// returns the author-declared `:politicas :timeout` typed
    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
    /// is `Copy`, so the accessor returns by value; no borrow of
    /// `&self` past the call). `None` when the slot is absent (the
    /// "cluster default applies — typically the gateway class's
    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
    /// round-trips to a rendered `HTTPRoute` structurally identical to
    /// one that omits the slot).
    ///
    /// The `:politicas :timeout` slot carries the "no infinite blocking"
    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
    /// the typed slot's `Option<Duration>` accept-set (zero-floor
    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
    /// Every downstream consumer that reads the per-call cap keys off
    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
    /// renderers key off to decide "emit :politicas overlay" vs "skip
    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
    /// fans the deadline into every rule via
    /// [`crate::render::single_field_overlay`], the future M4 per-
    /// Aplicacao Gateway API reconciler materialization pass, the
    /// future per-`:contratos`-edge timeout-override overlay the
    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
    ///
    /// Prior to this lift the `.timeout` field was accessed inline at
    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
    /// …)` call — two open-coded field-accesses that expressed no
    /// compile-time link back to the typed slot. A future extension of
    /// the `:politicas :timeout` axis to a richer author surface — a
    /// per-`:contratos`-edge timeout override the operator pins through
    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
    /// roadmap acknowledges, a per-cluster timeout-default overlay the
    /// M4 CR materializer resolves per-CR, a split of the single
    /// per-call `Duration` into a richer `{request, backendRequest}`
    /// pair once the Gateway API's per-rule `timeouts` block grows the
    /// upstream-facing backendRequest arm alongside the client-facing
    /// request arm — would have had to be threaded through both open-
    /// coded copies in lockstep or the emptiness predicate and the
    /// caixa-mesh emit path would silently disagree on which per-call
    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
    /// == false` while the renderer's overlay-emit path silently read
    /// a drifted other value, or vice versa: an author's `:timeout
    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
    /// the emptiness predicate still classified the policy as non-
    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
    /// | grep -A2 timeouts` audit would land on a route whose author's
    /// typed slot value silently vanished at the renderer layer).
    /// Lifting the resolution to a typed method on the substrate
    /// primitive means every downstream consumer of the Aplicacao's
    /// per-`:politicas` deadline surface reaches for exactly one typed
    /// dispatch — the resolver's accept-set migrates as a unit on any
    /// future axis addition.
    ///
    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
    /// family (sibling of the peer per-`:politicas`
    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
    /// `Option<bool>` accessor — same "one typed dispatch on the
    /// substrate primitive, thin projections at each consumer"
    /// discipline extended onto the peer per-`:politicas` typed-
    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
    /// numeric-Copy-T scalar" projection pattern the sibling
    /// `Option<u32>` / `Option<bool>` lifts opened, since every
    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
    /// than a scalar). Named `timeout()` to match the storage field's
    /// name; the accessor's identity maps onto the canonical MESH-
    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
    #[must_use]
    pub const fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
    /// retry-budget scalar accessor every consumer of the Aplicacao's
    /// Gateway API v1.x per-rule retry-cap keys off — returns the
    /// author-declared `:politicas :retries` typed `u32` verbatim as an
    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
    /// value; no borrow of `&self` past the call). `None` when the slot
    /// is absent (the "cluster default applies — typically 'no retries
    /// beyond a single dispatch attempt'" arm the caixa-mesh
    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
    /// this predicate too, so an authored-but-unset `:politicas
    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
    /// identical to one that omits the slot).
    ///
    /// The `:politicas :retries` slot carries the "transient failure
    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
    /// count scalar the caixa-mesh `retry_overlay` builder writes.
    /// Every downstream consumer that reads the retry cap keys off this
    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
    /// renderers key off to decide "emit :politicas overlay" vs "skip
    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
    /// the value into every rule via [`crate::render::single_field_overlay`],
    /// the future M4 per-Aplicacao Gateway API reconciler
    /// materialization pass, the future per-`:contratos`-edge retry-
    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
    /// acknowledges).
    ///
    /// Prior to this lift the `.retries` field was accessed inline at
    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
    /// …)` call — two open-coded field-accesses that expressed no
    /// compile-time link back to the typed slot. A future extension of
    /// the `:politicas :retries` axis to a richer author surface — a
    /// per-`:contratos`-edge retry override the operator pins through a
    /// future `:contratos :retries` slot, a per-cluster retry-default
    /// overlay the M4 CR materializer resolves per-CR, a promotion of
    /// the plain `u32` attempt-count to a richer `{attempts, codes,
    /// backoff}` sub-block once the Gateway API grows the peer
    /// `retry.codes` / `retry.backoff` axes — would have had to be
    /// threaded through both open-coded copies in lockstep or the
    /// emptiness predicate and the caixa-mesh emit path would silently
    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
    /// (a `:politicas` block whose only axis is a `Some :retries` would
    /// satisfy `is_empty() == false` while the renderer's overlay-emit
    /// path silently read a drifted other value, or vice versa: an
    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
    /// block while the emptiness predicate still classified the policy
    /// as non-empty). Lifting the resolution to a typed method on the
    /// substrate primitive means every downstream consumer of the
    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
    /// one typed dispatch — the resolver's accept-set migrates as a
    /// unit on any future axis addition.
    ///
    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
    /// family (sibling of the peer per-`:politicas`
    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
    /// same "one typed dispatch on the substrate primitive, thin
    /// projections at each consumer" discipline extended onto the
    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
    /// fold on). Named `retries()` to match the storage field's name;
    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
    /// §III.2 vocabulary the slot's docstring already carries.
    #[must_use]
    pub const fn retries(&self) -> Option<u32> {
        self.retries
    }

    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
    /// enforcement-toggle scalar accessor every consumer of the
    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
    /// — returns the author-declared `:politicas :mtls-required` typed
    /// bool verbatim as an `Option<bool>`, copied out of the typed
    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
    /// the accessor returns by value; no borrow of `&self` past the
    /// call). `None` when the slot is absent (the "cluster default
    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
    /// this predicate too, so an authored-but-unset `:politicas
    /// (:mtls-required ())` round-trips to a rendered
    /// `CiliumNetworkPolicy` structurally identical to one that omits
    /// the slot).
    ///
    /// The `:politicas :mtls-required` slot carries the "explicit opt-
    /// out only, sandboxing-by-default" mTLS-enforcement toggle
    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
    /// `{None, Some(true), Some(false)}` accept-set maps onto the
    /// Cilium `authentication.mode` bijection through
    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
    /// handshake enforced), `Some(false) → "disabled"` (handshake
    /// skipped — the debug-edge opt-out), `None` → omit the block
    /// (cluster default applies). Every downstream consumer that
    /// reads the toggle keys off this scalar (the
    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
    /// off to decide "emit :politicas overlay" vs "skip entirely", the
    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
    /// ingress rule via [`crate::render::single_field_overlay`], the
    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
    /// materialization pass, the future per-`:contratos`-edge mTLS
    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
    ///
    /// Prior to this lift the `.mtls_required` field was accessed
    /// inline at two sites — [`MeshPolicy::is_empty`]'s
    /// `self.mtls_required.is_none()` arm and caixa-mesh's
    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
    /// two open-coded field-accesses that expressed no compile-time
    /// link back to the typed slot. A future extension of the
    /// `:politicas :mtls-required` axis to a richer author surface —
    /// a per-`:contratos`-edge mTLS override the operator pins through
    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
    /// M4 CR materializer resolves per-CR, a three-valued
    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
    /// would have had to be threaded through both open-coded copies in
    /// lockstep or the emptiness predicate and the caixa-mesh emit
    /// path would silently disagree on which toggle a given
    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
    /// axis is a `Some`
    /// `:mtls-required` would satisfy `is_empty() == false` while the
    /// renderer's overlay-emit path silently read a drifted other
    /// value, or vice versa). Lifting the resolution to a typed method
    /// on the substrate primitive means every downstream consumer of
    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
    /// for exactly one typed dispatch — the resolver's accept-set
    /// migrates as a unit on any future axis addition.
    ///
    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
    /// family (peer of the sibling per-`:placement`
    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
    /// same "one typed dispatch on the substrate primitive, thin
    /// projections at each consumer" discipline extended onto the
    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
    /// the "optional per-slot Copy-T scalar" projection pattern the
    /// sibling per-`:politicas` `:retries` (Option<u32>) /
    /// `:timeout` (Option<Duration>) future lifts fold on). Named
    /// `mtls_required()` to match the storage field's name; the
    /// accessor's identity maps onto the canonical MESH-COMPOSITION
    /// §III.2 vocabulary the slot's docstring already carries.
    #[must_use]
    pub const fn mtls_required(&self) -> Option<bool> {
        self.mtls_required
    }

    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
    /// `local_rate_limit`-mesh token-bucket-declaration scalar
    /// accessor every consumer of the Aplicacao's per-`:politicas`
    /// per-`(rate, window)` rate-limit surface keys off — returns the
    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
    /// verbatim as an `Option<RateLimit>`, copied out of the typed
    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
    /// `Copy`, so the accessor returns by value; no borrow of `&self`
    /// past the call). `None` when the slot is absent (the "cluster
    /// default applies — typically 'no per-Aplicacao rate declaration,
    /// gateway-class per-listener default applies'" arm the future
    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
    /// `rate_limit().is_none()` arm reads this predicate too, so an
    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
    /// identical to one that omits the slot).
    ///
    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
    /// token-bucket rate declaration" contract (MESH-COMPOSITION
    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
    /// (rate lower-bounded by 1 through
    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
    /// `:politicas` overlay emits. Every downstream consumer that
    /// reads the rate declaration keys off this scalar (the
    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
    /// off to decide "emit :politicas overlay" vs "skip entirely", the
    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
    /// `rl.window` against [`is_canonical_rate_limit_window`], the
    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
    /// the future per-`:contratos`-edge rate-limit override the
    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
    ///
    /// Prior to this lift the `.rate_limit` field was accessed inline
    /// at two sites — [`MeshPolicy::is_empty`]'s
    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
    /// field-accesses that expressed no compile-time link back to the
    /// typed slot. A future extension of the `:politicas :rate-limit`
    /// axis to a richer author surface — a per-`:contratos`-edge
    /// rate-limit override the operator pins through a future
    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
    /// the M4 CR materializer resolves per-CR, a promotion of the
    /// plain `(rate, window)` scalar pair to a richer
    /// `{rate, window, burst, key}` sub-block once Envoy's
    /// `local_rate_limit` grows the peer `burst_size` /
    /// `descriptor_key` axes — would have had to be threaded through
    /// both open-coded copies in lockstep or the emptiness predicate
    /// and the validate gate would silently disagree on which rate
    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
    /// block whose only axis is a `Some :rate-limit` would satisfy
    /// `is_empty() == false` while the validate path silently read a
    /// drifted other value, or vice versa: an author's
    /// `:rate-limit "100/s"` would omit the value-shape gate while the
    /// emptiness predicate still classified the policy as non-empty).
    /// Lifting the resolution to a typed method on the substrate
    /// primitive means every downstream consumer of the Aplicacao's
    /// per-`:politicas` rate-limit surface reaches for exactly one
    /// typed dispatch — the resolver's accept-set migrates as a unit
    /// on any future axis addition.
    ///
    /// First `Option<Copy-composite-T>`-return accessor on the M3
    /// mesh-slot family — closes the last un-lifted per-`:politicas`
    /// scalar-value axis. Peer of the sibling per-`:politicas`
    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
    /// "one typed dispatch on the substrate primitive, thin
    /// projections at each consumer" discipline extended onto the
    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
    /// sub-accessors rather than a top-level accessor because
    /// consumers reach for the axes not the aggregate). Named
    /// `rate_limit()` to match the storage field's name; the
    /// accessor's identity maps onto the canonical MESH-COMPOSITION
    /// §III.2 vocabulary the slot's docstring already carries.
    #[must_use]
    pub const fn rate_limit(&self) -> Option<RateLimit> {
        self.rate_limit
    }

    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
    /// declaration scalar accessor every consumer of the Aplicacao's
    /// per-`:politicas` breaker declaration keys off — returns the
    /// author-declared `:politicas :circuit-breaker` typed
    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
    /// copied out of the typed slot's own `Option<CircuitBreaker>`
    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
    /// by value; no borrow of `&self` past the call). `None` when the
    /// slot is absent (the "cluster default applies — typically 'no
    /// per-Aplicacao breaker declaration, gateway-class per-listener
    /// default applies'" arm the future caixa-mesh
    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
    /// arm reads this predicate too, so an authored-but-unset
    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
    /// that omits the slot).
    ///
    /// The `:politicas :circuit-breaker` slot carries the
    /// "per-Aplicacao consecutive-transient-failure trip declaration"
    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
    /// zero-floor rejected through
    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
    /// canonical-form pinned through
    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
    /// bijection the future `CiliumClusterwideEnvoyConfig`
    /// per-`:politicas` overlay emits. Every downstream consumer that
    /// reads the breaker declaration keys off this scalar (the
    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
    /// off to decide "emit :politicas overlay" vs "skip entirely", the
    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
    /// that brackets `cb.max_failures()` against
    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
    /// [`POLICY_BREAKER_WINDOW_MAX`] via
    /// [`crate::render::require_positive_canonical_bounded_duration`],
    /// the future M4 per-Aplicacao Envoy reconciler materialization
    /// pass, the future per-`:contratos`-edge breaker override the
    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
    ///
    /// Prior to this lift the `.circuit_breaker` field was accessed
    /// inline at two sites — [`MeshPolicy::is_empty`]'s
    /// `self.circuit_breaker.is_none()` arm and the
    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
    /// bind — two open-coded field-accesses that expressed no
    /// compile-time link back to the typed slot. A future extension of
    /// the `:politicas :circuit-breaker` axis to a richer author
    /// surface — a per-`:contratos`-edge breaker override the operator
    /// pins through a future `:contratos :circuit-breaker` slot the
    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
    /// breaker-default overlay the M4 CR materializer resolves per-CR,
    /// a promotion of the plain `(max_failures, window)` scalar pair to
    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
    /// sub-block once Envoy's `outlier_detection` grows the peer
    /// ejection-percentage / ejection-time axes — would have had to be
    /// threaded through both open-coded copies in lockstep or the
    /// emptiness predicate and the validate gate would silently
    /// disagree on which breaker declaration a given [`MeshPolicy`]
    /// resolves to (a `:politicas` block whose only axis is a
    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
    /// the validate path silently read a drifted other value, or vice
    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
    /// "60s"))` would omit the value-shape gate while the emptiness
    /// predicate still classified the policy as non-empty). Lifting
    /// the resolution to a typed method on the substrate primitive
    /// means every downstream consumer of the Aplicacao's
    /// per-`:politicas` breaker surface reaches for exactly one typed
    /// dispatch — the resolver's accept-set migrates as a unit on any
    /// future axis addition.
    ///
    /// Second `Option<Copy-composite-T>`-return accessor on the M3
    /// mesh-slot family (sibling of the peer per-`:politicas`
    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
    /// on the same composite-Copy shape, and of the sibling per-
    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
    /// same "one typed dispatch on the substrate primitive, thin
    /// projections at each consumer" discipline extended onto the last
    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
    /// match the storage field's name; the accessor's identity maps
    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
    /// docstring already carries. Closes the last unlifted
    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
    /// reader now routes through a typed dispatch on the substrate
    /// primitive.
    #[must_use]
    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
        self.circuit_breaker
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CircuitBreaker {
    pub max_failures: u32,
    #[serde(with = "supervisor::duration_codec_required")]
    pub window: Duration,
}

impl CircuitBreaker {
    /// Substrate-canonical per-`:politicas :circuit-breaker`
    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
    /// breaker trip-count keys off — returns the author-declared
    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
    /// so the accessor returns by value; no borrow of `&self` past the
    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
    /// axis; a `CircuitBreaker` past pattern-match is definitionally
    /// present, and its `:max-failures` field carries the trip count as a
    /// required-axis scalar).
    ///
    /// The `:politicas :circuit-breaker :max-failures` axis carries the
    /// "consecutive-transient-failure trip threshold" contract
    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
    /// (zero-floor rejected through
    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
    /// Every downstream consumer that reads the trip threshold keys off
    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
    /// canonical `require_positive_bounded_u32` helper, the future M4
    /// per-Aplicacao Envoy config reconciler materialization pass, the
    /// future per-`:contratos`-edge breaker-override overlay the
    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
    ///
    /// Prior to this lift the `.max_failures` field was accessed inline
    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
    /// open-coded field-access that expressed no compile-time link back
    /// to the typed sub-struct axis. A future extension of the
    /// `:max-failures` axis to a richer author surface — a
    /// per-`:contratos`-edge breaker override the operator pins through a
    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
    /// #3 roadmap acknowledges, a per-cluster max-failures-default
    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
    /// plain `u32` trip count to a richer
    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
    /// tuple once Envoy's `outlier_detection` block's peer axes come into
    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
    /// count arms — would have had to be threaded through every open-
    /// coded copy in lockstep or the validate gate and the future M4
    /// emit path would silently disagree on which trip threshold a given
    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
    /// would satisfy validate while the emit path silently read a drifted
    /// other value, or vice versa: a validated typed slot would land at
    /// the emit boundary as a no-op breaker whose trip threshold is
    /// structurally never reached). Lifting the resolution to a typed
    /// method on the substrate primitive means every downstream consumer
    /// of the Aplicacao's per-`:politicas :circuit-breaker`
    /// trip-threshold surface reaches for exactly one typed dispatch —
    /// the resolver's accept-set migrates as a unit on any future axis
    /// addition.
    ///
    /// First sub-struct scalar accessor on the M3 mesh-slot family
    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
    /// closes the last unlifted per-`:politicas` scalar-value axis after
    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
    /// Same "one typed dispatch on the substrate primitive, thin
    /// projections at each consumer" discipline the peer
    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
    /// [`Membro::versao_requirement`] (a40b0e3),
    /// [`Entrada::destination`] (6db982c) accessors carry on their
    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
    /// match the storage field's name; the accessor's identity maps onto
    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
    /// docstring already carries.
    #[must_use]
    pub const fn max_failures(&self) -> u32 {
        self.max_failures
    }

    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
    /// Envoy-outlier-detection rolling-observation-interval scalar
    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
    /// breaker rolling-window duration keys off — returns the
    /// author-declared `:politicas :circuit-breaker :window` typed
    /// `Duration` verbatim, copied out of the typed slot's own
    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
    /// by value; no borrow of `&self` past the call). Non-optional (the
    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
    /// `CircuitBreaker` past pattern-match is definitionally present,
    /// and its `:window` field carries the rolling-observation interval
    /// as a required-axis scalar).
    ///
    /// The `:politicas :circuit-breaker :window` axis carries the
    /// "consecutive-transient-failure rolling-observation interval"
    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
    /// `Duration` accept-set (zero-floor rejected through
    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
    /// residue rejected through
    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
    /// Envoy `outlier_detection.interval` per-cluster
    /// ejection-observation-interval scalar (equivalently the future
    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
    /// consumer that reads the rolling-observation interval keys off
    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
    /// integer-millisecond canonical-form + cap bracket at
    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
    /// [`crate::render::require_positive_canonical_bounded_duration`]
    /// helper, the future M4 per-Aplicacao Envoy config reconciler
    /// materialization pass, the future per-`:contratos`-edge
    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
    /// acknowledges).
    ///
    /// Prior to this lift the `.window` field was accessed inline at
    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
    /// `require_positive_canonical_bounded_duration(cb.window, …)`
    /// call — one open-coded field-access that expressed no compile-
    /// time link back to the typed sub-struct axis. A future extension
    /// of the `:window` axis to a richer author surface — a
    /// per-`:contratos`-edge window override the operator pins through
    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
    /// #3 roadmap acknowledges, a per-cluster window-default overlay
    /// the M4 CR materializer resolves per-CR, a promotion of the plain
    /// `Duration` observation interval to a richer
    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
    /// once Envoy's `outlier_detection` block's peer axes come into
    /// scope, a per-Envoy-cluster minimum-request-volume gate before
    /// the window arms — would have had to be threaded through every
    /// open-coded copy in lockstep or the validate gate and the future
    /// M4 emit path would silently disagree on which observation
    /// interval a given [`CircuitBreaker`] resolves to (an author's
    /// `:window "60s"` would satisfy validate while the emit path
    /// silently read a drifted other value, or vice versa: a validated
    /// typed slot would land at the emit boundary as a breaker whose
    /// observation window is structurally so wide that no realistic
    /// failure-rate shape can trip it). Lifting the resolution to a
    /// typed method on the substrate primitive means every downstream
    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
    /// observation-window surface reaches for exactly one typed
    /// dispatch — the resolver's accept-set migrates as a unit on any
    /// future axis addition.
    ///
    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
    /// required-axis, extended onto the per-sub-struct required-`Duration`
    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
    /// axis. Same "one typed dispatch on the substrate primitive, thin
    /// projections at each consumer" discipline the peer
    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
    /// [`Membro::versao_requirement`] (a40b0e3),
    /// [`Entrada::destination`] (6db982c) accessors carry on their
    /// respective per-mesh-slot-atom scalar-value axes, extended onto
    /// the per-sub-struct required-`Duration` axis. Named `window()` to
    /// match the storage field's name; the accessor's identity maps onto
    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
    /// docstring already carries.
    #[must_use]
    pub const fn window(&self) -> Duration {
        self.window
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimit {
    /// Requests per window.
    pub rate: u32,
    /// Window duration.
    pub window: Duration,
}

impl RateLimit {
    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
    /// every consumer of the Aplicacao's per-`:contratos`-edge
    /// rate-limit-bucket capacity keys off — returns the author-declared
    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
    /// returns by value; no borrow of `&self` past the call). Non-optional
    /// (the surrounding `Option<RateLimit>` is the "slot present?"
    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
    /// `RateLimit` past pattern-match is definitionally present, and its
    /// `:rate` field carries the token-bucket capacity as a required-axis
    /// scalar).
    ///
    /// The `:politicas :rate-limit` `:rate` axis carries the
    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
    /// the typed slot's `u32` accept-set (zero-floor rejected through
    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
    /// token-bucket-capacity scalar (equivalently the future
    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
    /// consumer that reads the token-bucket capacity keys off this
    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
    /// cap bracket that gates on the canonical
    /// [`crate::render::require_positive_bounded_u32`] helper, the
    /// [`rate_limit_codec::render`] `Duration → unit` projection that
    /// emits the `<n>/<s|m|h>` author surface, the future M4
    /// per-Aplicacao Envoy config reconciler materialization pass, the
    /// future per-`:contratos`-edge rate-limit-override overlay the
    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
    ///
    /// Prior to this lift the `.rate` field was accessed inline at three
    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
    /// field-accesses that expressed no compile-time link back to the
    /// typed sub-struct axis. A future extension of the `:rate` axis
    /// to a richer author surface — a per-`:contratos`-edge rate
    /// override the operator pins through a future `:contratos :rate`
    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
    /// per-cluster rate-default overlay the M4 CR materializer resolves
    /// per-CR, a promotion of the plain `u32` token capacity to a
    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
    /// before the token arms — would have had to be threaded through
    /// every open-coded copy in lockstep or the validate gate, the
    /// codec's render path, and the future M4 emit path would silently
    /// disagree on which token capacity a given [`RateLimit`] resolves
    /// to (an author's `:rate-limit "100/s"` would satisfy validate
    /// while the render / emit paths silently read a drifted other
    /// value, or vice versa: a validated typed slot would land at the
    /// emit boundary as a no-op limiter whose token capacity is
    /// structurally so high that no realistic per-edge traffic shape
    /// can drain it). Lifting the resolution to a typed method on the
    /// substrate primitive means every downstream consumer of the
    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
    /// reaches for exactly one typed dispatch — the resolver's
    /// accept-set migrates as a unit on any future axis addition.
    ///
    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
    /// in shape to the peer per-`CircuitBreaker`
    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
    /// on the peer per-sub-struct required-axis, extended onto the
    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
    /// required-axis scalar" projection pattern the sibling
    /// [`RateLimit::window`] future lift folds on. Same "one typed
    /// dispatch on the substrate primitive, thin projections at each
    /// consumer" discipline the peer [`WitContract::source`] /
    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
    /// (0804823), [`Membro::nome`] (4a32abf),
    /// [`Membro::versao_requirement`] (a40b0e3),
    /// [`Entrada::destination`] (6db982c),
    /// [`CircuitBreaker::max_failures`] (3a74062),
    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
    /// to match the storage field's name; the accessor's identity maps
    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
    /// docstring already carries.
    #[must_use]
    pub const fn rate(&self) -> u32 {
        self.rate
    }

    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
    /// rate-limit-bucket refill period keys off — returns the
    /// author-declared `:politicas :rate-limit` typed `Duration`
    /// verbatim, copied out of the typed slot's own `Duration` storage
    /// (`Duration` is `Copy`, so the accessor returns by value; no
    /// borrow of `&self` past the call). Non-optional (the surrounding
    /// `Option<RateLimit>` is the "slot present?" projection at the
    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
    /// pattern-match is definitionally present, and its `:window`
    /// field carries the token-bucket refill period as a required-axis
    /// scalar).
    ///
    /// The `:politicas :rate-limit` `:window` axis carries the
    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
    /// — the typed slot's `Duration` accept-set (constrained to the
    /// three canonical windows `{1s, 60s, 3600s}` the
    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
    /// per-cluster token-bucket-refill-period scalar (equivalently the
    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
    /// consumer that reads the token-bucket refill period keys off
    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
    /// canonical-window gate that keys off
    /// [`is_canonical_rate_limit_window`], the
    /// [`rate_limit_codec::render`] `Duration → unit` projection that
    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
    /// [`rate_limit_window_unit`] and non-canonical fallback via
    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
    /// reconciler materialization pass, the future per-`:contratos`-
    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
    /// roadmap acknowledges).
    ///
    /// Prior to this lift the `.window` field was accessed inline at
    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
    /// error-payload construction on refusal, and the two
    /// [`rate_limit_codec::render`] arms
    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
    /// open-coded field-accesses that expressed no compile-time link
    /// back to the typed sub-struct axis. A future extension of the
    /// `:window` axis to a richer author surface — a per-`:contratos`-
    /// edge window override the operator pins through a future
    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
    /// acknowledges, a per-cluster window-default overlay the M4 CR
    /// materializer resolves per-CR, a promotion of the plain
    /// `Duration` refill period to a richer
    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
    /// axis comes into scope, an addition of a `"d"` day suffix once
    /// Envoy's `rate_limit_action` grows daily-bucket support — would
    /// have had to be threaded through every open-coded copy in
    /// lockstep or the validate gate, the codec's render path, and
    /// the future M4 emit path would silently disagree on which
    /// refill period a given [`RateLimit`] resolves to (an author's
    /// `:rate-limit "100/s"` would satisfy validate while the render
    /// / emit paths silently read a drifted other value, or vice
    /// versa: a validated typed slot would land at the emit boundary
    /// as a limiter whose refill period is structurally so long that
    /// no realistic per-edge traffic shape stays inside the token
    /// budget). Lifting the resolution to a typed method on the
    /// substrate primitive means every downstream consumer of the
    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
    /// reaches for exactly one typed dispatch — the resolver's
    /// accept-set migrates as a unit on any future axis addition.
    ///
    /// Second sub-struct scalar accessor on the `RateLimit` axis —
    /// sibling in shape to the just-landed [`RateLimit::rate`]
    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
    /// required-axis, extended onto the per-sub-struct
    /// required-`Duration` axis; closes the last unlifted
    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
    /// per-sub-struct accessor coverage is now complete across both
    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
    /// the substrate primitive, thin projections at each consumer"
    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
    /// [`Membro::nome`] (4a32abf),
    /// [`Membro::versao_requirement`] (a40b0e3),
    /// [`Entrada::destination`] (6db982c) accessors carry on their
    /// respective per-mesh-slot-atom scalar-value axes. Named
    /// `window()` to match the storage field's name; the accessor's
    /// identity maps onto the canonical MESH-COMPOSITION §III.2
    /// vocabulary the slot's docstring already carries.
    #[must_use]
    pub const fn window(&self) -> Duration {
        self.window
    }

    /// Recognize this rate-limit's `:window` as a canonical
    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
    /// exactly matches one of the three closed-set arm-Durations
    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
    /// non-canonical magnitude the codec's round-trip would break on
    /// (sub-second residue, or a second-magnitude outside the set
    /// [`RateLimitUnit::ALL`] enumerates).
    ///
    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
    /// returns `Some` here — the validate gate's
    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
    /// rejects every window this accessor returns `None` on. Downstream
    /// consumers past validate (the codec's [`rate_limit_codec::render`]
    /// path, the future M4 per-Aplicacao Envoy config reconciler's
    /// materialization pass, the future per-`:contratos`-edge rate-limit-
    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
    /// acknowledges) that read the typed unit off a validated slot can
    /// pattern-match on the returned `Some` without re-checking
    /// canonicality at the consumer layer — the typed enum surface is
    /// the load-bearing carrier of the canonicality invariant.
    ///
    /// Preferred over the free [`is_canonical_rate_limit_window`]
    /// module-private helper at any call site that has the typed
    /// [`RateLimit`] in hand (the codec's `render` arm at
    /// [`rate_limit_codec::render`], the validate gate's canonical-form
    /// arm in [`AplicacaoSpec::validate_politicas`], any future
    /// per-`:contratos` edge-override overlay resolver): those consumers
    /// reach for the typed enum without going through the
    /// `.window()` scalar-projection layer, and get the enum value
    /// directly (which the codec's render arm can then format via
    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
    /// "typed sub-struct scalar accessor, one dispatch on the substrate
    /// primitive" discipline the sibling [`RateLimit::rate`] and
    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
    /// projection axis (the third scalar accessor on the [`RateLimit`]
    /// axis, first typed-enum-return projection).
    #[must_use]
    pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
        RateLimitUnit::from_window(self.window)
    }
}

/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
///
/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
/// the `:politicas :rate-limit` unit surface reads from
/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
/// [`is_canonical_rate_limit_window`] predicate the
/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
/// projection) now lives inside this typed enum's `match self` arms — a
/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
/// `rate_limit_action` grows daily-bucket support) is one new variant
/// plus the exhaustiveness arms on the four methods, so every consumer
/// picks it up by compile-time construction rather than a runtime
/// table-scan miss.
///
/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
/// scanned via `find_map` at every projection call — an untyped runtime
/// walk that carried no compile-time link between the parse arm's
/// accepted suffixes, the render arm's emitted suffixes, and the
/// validate gate's accepted windows. A future rate-limit-unit addition
/// that landed one row without threading through the other consumers
/// (or a copy-paste flip that collapsed two rows onto one suffix) would
/// silently split the accepted-set across the three consumers — the
/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
/// for a 24h window that parse can't round-trip, the validate gate
/// misses one canonical window. Lifting the pairs onto a typed
/// closed-set enum with exhaustive `match` arms makes any such
/// half-landed extension a caixa-core build error (the compiler enforces
/// arm coverage on every method), not a silent per-consumer drift
/// surfacing at apply time. Same "closed-set typed-enum discriminator"
/// discipline the sibling [`PlacementStrategy`] (cc8f749),
/// [`crate::supervisor::RestartStrategy`],
/// [`crate::supervisor::RestartPolicy`],
/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
/// closed-set typed enums carry on their respective closed-set axes —
/// extended onto the seventh closed-set typed-enum discriminator axis
/// on the caixa typed surface (the `:politicas :rate-limit :window`
/// canonical-unit axis).
#[derive(
    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
)]
pub enum RateLimitUnit {
    /// 1-second window — canonical author-surface suffix `"s"`
    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
    /// with a 1s magnitude.
    Second,
    /// 1-minute window — canonical author-surface suffix `"m"`
    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
    /// with a 60s magnitude.
    Minute,
    /// 1-hour window — canonical author-surface suffix `"h"`
    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
    /// with a 3600s magnitude.
    Hour,
}

impl RateLimitUnit {
    /// Exhaustive iteration surface for every consumer that reads the
    /// full canonical-unit set (the byte-parity witness against the
    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
    /// webhook's accepted-suffix listing in its rejection body, any
    /// future round-trip fuzz harness). A future variant addition to
    /// [`RateLimitUnit`] extends this slice as a single edit and every
    /// consumer picks up the new entry by construction — the compiler-
    /// checked exhaustiveness on the sibling method `match` arms is the
    /// build-time guarantee that no arm forgets to grow.
    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];

    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
    /// string every `<n>/<unit>` rate-limit shape carries after its
    /// `/` separator. The single source of truth the codec's parse and
    /// render arms both dispatch on: the parse arm matches an incoming
    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
    /// output; the render arm emits the entry's `as_suffix` verbatim
    /// after the rate magnitude.
    #[must_use]
    pub const fn as_suffix(self) -> &'static str {
        match self {
            Self::Second => "s",
            Self::Minute => "m",
            Self::Hour => "h",
        }
    }

    /// Canonical `Duration` for this unit — the token-bucket refill
    /// period the [`RateLimit::window`] axis carries when the surrounding
    /// slot's `:rate-limit` author surface named this unit.
    #[must_use]
    pub const fn window(self) -> Duration {
        Duration::from_secs(match self {
            Self::Second => 1,
            Self::Minute => 60,
            Self::Hour => 3_600,
        })
    }

    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
    /// `None` when `suffix` is outside the closed-set arm-string set
    /// [`Self::as_suffix`] emits. The single `str → Self` projection
    /// [`rate_limit_codec::parse`] consumes.
    #[must_use]
    pub fn from_suffix(suffix: &str) -> Option<Self> {
        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
    }

    /// Recognize a canonical rate-limit `Duration` as one of the three
    /// arms, or `None` when `window` carries sub-second residue or a
    /// second-magnitude outside the closed-set arm-window set
    /// [`Self::window`] emits. The single `Duration → Self` projection
    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
    /// both consume.
    #[must_use]
    pub fn from_window(window: Duration) -> Option<Self> {
        if window.subsec_nanos() != 0 {
            return None;
        }
        Self::ALL.iter().copied().find(|u| u.window() == window)
    }

    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
    /// consumes.
    ///
    /// The peer `Duration → &'static str` axis folded onto the substrate
    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
    /// production consumers ([`rate_limit_codec::render`] and
    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
    /// migrated (61421a6): the free helper's `Duration → &str` projection
    /// is now the two-step composition
    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
    /// reads through the typed accessor. This lift closes the peer
    /// `&str → Duration` axis by folding the vestigial module-private
    /// `rate_limit_window_from_unit` delegate onto this associated method
    /// — the codec's parse arm and every future wire-side consumer of the
    /// `&str → Duration` projection (a future admission-webhook that
    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
    /// before it's promoted to a validated typed slot, a future
    /// `feira lint` shape-probe that reads the author-surface bytes
    /// verbatim) now reach for exactly one typed dispatch on the
    /// substrate primitive.
    ///
    /// Same "closed-set typed-enum discriminator with canonical
    /// projections per axis" discipline the sibling [`Self::as_suffix`]
    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
    /// methods carry — this associated method closes the fifth (and last
    /// unlifted) projection axis on the arm-table, so the closed-set enum
    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
    /// consumer of the `:politicas :rate-limit :window` axis reaches
    /// through. A future rate-limit-unit addition (a `"d"` day suffix
    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
    /// `"ms"` sub-second window once high-throughput per-edge policies
    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
    /// variant plus one arm per method — the compiler enforces
    /// exhaustiveness on every consumer's `match self` arms and picks
    /// the new unit up by construction across all five projections.
    #[must_use]
    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
        Self::from_suffix(suffix).map(Self::window)
    }
}

/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
/// every consumer that formats a canonical rate-limit unit as user-
/// facing text (future M4 admission-webhook rejection bodies naming
/// the accepted-suffix set, future `feira app graph` per-`:politicas`
/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
/// codec's parse arm accepts and the render arm emits. Same
/// as_str-through-Display convergence discipline the sibling
/// [`PlacementStrategy`], [`crate::CaixaKind`],
/// [`crate::supervisor::RestartStrategy`], and
/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
impl std::fmt::Display for RateLimitUnit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_suffix())
    }
}

/// Upper-bound ceiling on the `:politicas :timeout` axis — every
/// validated [`MeshPolicy::timeout`] past
/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
/// (inclusive on both ends, integer-millisecond magnitudes by the
/// canonical-form gate immediately preceding).
///
/// The typed field is `Option<Duration>` (the zero-floor arm
/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
/// `Duration::ZERO`, and the canonical-form arm
/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
/// sub-millisecond residue), so a programmatic struct literal
/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
/// 24h) and the equivalent author-surface form
/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
/// integer-hour magnitude) both round-trip cleanly through serde — a
/// structurally unbounded `Duration` ceiling. A `:timeout` value far
/// above the documented production-playbook band (Envoy default `15s`,
/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
/// at `~3600s`) silently degenerates the mesh-policy contract: the
/// per-call deadline is structurally so long that no realistic
/// synchronous-`:contratos` traversal can reach it, so the typed slot
/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
/// blocking" degenerates to a nominal-only contract on the
/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
/// the sibling `:politicas :retries` axis and the
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
/// `:politicas :circuit-breaker :max-failures` axis — all three close
/// the "structurally unbounded ceiling on a typed `:politicas` axis"
/// footgun the prior zero-floor-and-canonical-form-only checks left
/// open.
///
/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
/// shared duration codec emits (`"<n>h"` for any integer-hour
/// magnitude) — every value in the canonical authoring form's
/// `<integer><unit>` grammar at or below this cap renders to a clean
/// canonical string. The cap sits an order of magnitude above every
/// documented production-playbook recommendation band (Envoy default
/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
/// configured maximum (`proxy_read_timeout` typical max `3600s`),
/// below the clearly-pathological "effectively no timeout" floor
/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
/// want for a long-running synchronous workflow, but a hard wall above
/// which the mesh-level deadline is structurally a non-deadline.
/// Lifted as a typed `pub const` so the bound has exactly one source
/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook and the caixa-mesh-side
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
/// other typed upper bound in this crate carries
/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);

/// Upper-bound ceiling on the `:politicas :retries` axis — every
/// validated [`MeshPolicy::retries`] past
/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
///
/// The typed slot is `Option<u32>` (`None` = no retries on transient
/// failure; `Some(0)` already rejected by the
/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
/// .. }`) and the equivalent author-surface form
/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
/// serde / the codec — a structurally unbounded `u32` ceiling. The
/// runtime substrate that consumes the value (Envoy's
/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
/// admission cap is 10) translates a four-billion-retry policy into a
/// thundering-herd amplification vector on transient failure — the
/// caller's one request fans out to `retries` server-side calls per
/// edge per traversal, multiplying load by `(retries+1)^depth` across
/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
/// invariant "no infinite blocking" pairs with a no-runaway-amplification
/// invariant on the retry axis; both belong at the typed-slot layer.
///
/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
/// upstream mesh-policy schema that documents one) and sits above the
/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
/// every documented production playbook): a value the author can
/// plausibly want, but a hard wall above which the policy is
/// structurally a footgun. Lifted as a typed `pub const` so the bound
/// has exactly one source of truth — a future axis reaching for the
/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook, the caixa-mesh-side
/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
/// one place. Same shape every other typed upper bound in this crate
/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_RETRIES_MAX: u32 = 10;

/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
/// axis — every validated [`CircuitBreaker::max_failures`] past
/// [`AplicacaoSpec::validate_politicas`] lies in
/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
///
/// The typed field is `u32` (the zero-floor arm
/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
/// `0` — a breaker that trips on the first call), so a programmatic
/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
/// and the equivalent author-surface form
/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
/// cleanly through serde — a structurally unbounded `u32` ceiling. A
/// `max_failures` value far above the documented production-playbook
/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
/// typical 5–50) silently disables the breaker's protection role:
/// the threshold is structurally so high that no realistic
/// failures-per-`:window` traffic shape can reach it, so the breaker
/// never trips and the typed slot becomes a no-op carried on every
/// emitted Envoy / Cilium L7 overlay. Pairs with the
/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
/// axis — both close the "structurally unbounded `u32` ceiling on a
/// typed policy axis" footgun the prior zero-floor-only checks left
/// open.
///
/// The `1000` ceiling sits an order of magnitude above every
/// documented upstream production-playbook recommendation band (the
/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
/// the clearly-pathological "effectively no protection"
/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
/// plausibly want at hyperscale, but a hard wall above which the
/// policy is structurally a no-op. Lifted as a typed `pub const` so
/// the bound has exactly one source of truth — the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
/// one place. Same shape every other typed upper bound in this crate
/// carries ([`POLICY_RETRIES_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;

/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
/// every validated [`CircuitBreaker::window`] past
/// [`AplicacaoSpec::validate_politicas`] lies in
/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
/// integer-millisecond magnitudes by the canonical-form gate
/// immediately preceding).
///
/// The typed field is `Duration` (the zero-floor arm
/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
/// `Duration::ZERO`, and the canonical-form arm
/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
/// sub-millisecond residue), so a programmatic struct literal
/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
/// and the equivalent author-surface form
/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
/// integer-hour magnitude) both round-trip cleanly through serde — a
/// structurally unbounded `Duration` ceiling. A `:window` value far
/// above the documented production-playbook band (Hystrix
/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
/// Istio `outlierDetection.interval` default `10s`, Envoy
/// `outlier_detection.interval` default `10s`, AWS App Mesh
/// circuit-breaker time-window typical `30s..=300s`) degenerates the
/// breaker's role: a rolling-window failure counter whose window is
/// hours long is operationally a lifetime counter, the breaker's
/// "recent failures" memory is structurally so long that transient
/// failures are never forgotten, and the typed slot becomes a no-op
/// trigger that trips once and stays tripped for the lifetime of the
/// component carried on every emitted Envoy / Cilium L7 overlay.
///
/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
/// shared duration codec emits (`"<n>h"` for any integer-hour
/// magnitude) — every value in the canonical authoring form's
/// `<integer><unit>` grammar at or below this cap renders to a clean
/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
/// cap on the first typed-`Duration` `:politicas` axis: the two
/// duration-typed `:politicas` axes now share a single uniform top
/// edge so the next typed-slot wiring (the future caixa-mesh
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
/// admission webhook) reaches for either field knowing the value is
/// in `1ms..=1h` without re-validating at the renderer layer. The cap
/// sits two orders of magnitude above every documented upstream
/// production-playbook recommendation band (Hystrix / resilience4j /
/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
/// and below the clearly-pathological "rolling window degenerates to
/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
/// author can plausibly want for a very-low-traffic long-tail
/// failure-detection window, but a hard wall above which the breaker's
/// rolling-window contract is structurally a lifetime-counter contract.
/// Lifted as a typed `pub const` so the bound has exactly one source
/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's admission webhook and the caixa-mesh-side
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
/// other typed upper bound in this crate carries
/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);

/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
/// every validated [`RateLimit::rate`] past
/// [`AplicacaoSpec::validate_politicas`] lies in
/// `1..=POLICY_RATE_LIMIT_MAX`.
///
/// The typed field is `u32` (the zero-floor arm
/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
/// zero-rate limit denies every request, the canonical "I forgot
/// that 0 means deny-everything" footgun), so a programmatic struct
/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
/// round-trip cleanly through serde — a structurally unbounded `u32`
/// ceiling. The runtime substrate consuming the value (Envoy's
/// `local_rate_limit.token_bucket.max_tokens`, the future
/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
/// rate-limit into a no-op rate-limiter: the bucket capacity is
/// structurally so high no realistic per-edge traffic shape can
/// drain it, the limiter never trips, and the typed slot becomes a
/// "rate-limit declared, no enforcement" footgun — the canonical
/// declared-but-inert shape every other `:politicas` cap arm
/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
///
/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
/// above every documented upstream production-playbook recommendation
/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
/// `limit_req_zone` typical `1..=1_000` RPS) and below the
/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
/// `u32::MAX`): a value the author can plausibly want at hyperscale
/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
/// /h-window arm), but a hard wall above which the policy is
/// structurally a no-op carried verbatim on every emitted Envoy /
/// Cilium L7 overlay. The cap brackets all three canonical windows
/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
/// per-endpoint API band). Lifted as a typed `pub const` so the bound
/// has exactly one source of truth — the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
/// one place. Same shape every other typed upper bound in this crate
/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`crate::LIMITS_WALL_CLOCK_MAX`],
/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;

// `:entrada :host` total-length and per-label cap axes route through
// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
// pair of aplicacao-private aliases the previous `validate_entrada_host`
// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
// = 63`) were structurally the same K8s Gateway API v1 Hostname
// admission-schema bounds — the total-length cap on the OpenAPI
// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
// same regex — that the peer axes at the caixa-core::render level pin,
// so hoisting both readers onto the shared lifted constants closes the
// third-occurrence duplication threshold structurally: the M4
// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
// label validator, the future per-`Certificate` SAN emitter, and every
// other per-Gateway-API-Hostname landing site reach the same one place
// as the `:entrada :host` gate does — no per-axis alias drift surface
// between them, by construction.

/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
/// extractor expression — the upper bound `validate_placement_shard_key`
/// enforces on every well-shaped shard-key past validate. The realistic
/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
/// `:placement :affinity` / `:placement :clusters` identifier-shaped
/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
/// in `:shard-key`" footgun at validate time rather than at the future
/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;

/// Reject `:membros :caixa` values the K8s apiserver would refuse at
/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
/// that maps the shared parser-shaped reason into the
/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
/// is self-locating (the offending `caixa:` is named verbatim) and
/// the author can grep their caixa.lisp for `:caixa "<name>"` and
/// fix it in one edit. Same diagnostic shape as
/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
    // Empty is already gated by `MembroCaixaEmpty` at the call site;
    // re-checking here keeps the predicate usable from any future
    // call site (the M4 CR materializer) without an empty-check
    // footgun. The shared
    // [`crate::render::require_valid_dns_1123_label`] helper brackets
    // the empty-first + shape cascade every peer name axis
    // (`:placement :clusters`, `:placement :affinity`, `:contratos
    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
    // `:upgrade-from :module`) routes through, so drift between the
    // eight axes' accepted DNS-1123-label sets is structurally
    // impossible.
    crate::render::require_valid_dns_1123_label(
        caixa,
        || AplicacaoError::MembroCaixaEmpty,
        |reason| AplicacaoError::MembroCaixaInvalid {
            caixa: caixa.to_string(),
            reason,
        },
    )
}

/// Reject `:placement :clusters` entries the K8s apiserver would refuse
/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
/// that maps the shared parser-shaped reason into the
/// [`AplicacaoError::PlacementClusterInvalid`] variant.
///
/// Cluster names land in DNS-1123-label territory across every consumer:
/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
/// the `lareira-fleet-programs` aggregator applies to scope programs to
/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
/// cluster identity the M4 CR materializer round-trips. Each apiserver-
/// side schema enforces the DNS-1123 label rule on admission; a
/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
/// mistaken-identity slug) silently passes the prior empty-/duplicate-
/// only gate and the failure surfaces as a no-match at filter time —
/// the workload doesn't land in the named cluster, with no diagnostic
/// naming the offending `:clusters` entry. Lifting the gate to caixa-
/// build time mirrors the `:membros :caixa` value-shape trajectory
/// (3f9d7a0) on the peer name axis.
///
/// The diagnostic carries the offending `cluster:` verbatim plus a
/// parser-shaped `reason:` naming the specific violation, so the
/// author can grep their caixa.lisp for `:clusters` and fix it in
/// one edit. Same diagnostic shape as
/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
    // Empty is already gated by `PlacementClusterEmpty` at the call
    // site; re-checking here keeps the predicate usable from any
    // future call site (the M4 CR materializer's per-cluster validator)
    // without an empty-check footgun. Routes through the shared
    // [`crate::render::require_valid_dns_1123_label`] gate the peer
    // name axes each land on.
    crate::render::require_valid_dns_1123_label(
        cluster,
        || AplicacaoError::PlacementClusterEmpty,
        |reason| AplicacaoError::PlacementClusterInvalid {
            cluster: cluster.to_string(),
            reason,
        },
    )
}

/// Reject `:placement :affinity` hints whose shape can never legitimately
/// land in any downstream selector or label-keyed routing axis. Thin
/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
/// shared parser-shaped reason into the
/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
/// diagnostic is self-locating (the offending `:affinity` is named
/// verbatim) and the author can grep their caixa.lisp for
/// `:affinity "<hint>"` and fix it in one edit.
///
/// The `:affinity` slot carries a placement-engine hint — canonical
/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
/// compression overlay and the future M4 placement-engine's per-hint
/// routing axis. Each downstream consumer (caixa-mesh's
/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
/// `spec.placement.affinity` admission rule, the future M4 per-hint
/// node-affinity / pod-affinity rule generator keying off the same
/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
/// selector) requires the value to be a DNS-1123 label — K8s label
/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
/// admission rule the apiserver enforces.
///
/// Until this gate landed an `:affinity "DataLocality"` (the canonical
/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
/// Python-module-name leak), `:affinity "data.locality"` (the
/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
/// `:affinity "data-locality-"` (boundary-hyphen violation),
/// `:affinity "data locality"` (paste-from-doc whitespace),
/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
/// 64-byte over-cap slug silently passed the empty-only check and the
/// failure surfaced as a no-match at the M3 Adaptive compression
/// overlay's filter time (`placement.affinity` carried a malformed
/// value, no node matched, the workload landed on the default
/// heuristic) — the canonical "declared-but-inert" footgun mirroring
/// the empty-:affinity / empty-shard-key / zero-:politicas /
/// empty-:contratos-target gates already close on every other
/// declare-but-no-opinion axis. Lifting the rejection to a build-time
/// gate closes the fifth typed slot on the Aplicacao surface to land
/// on the canonical DNS-1123 label floor (after the four Servico-name
/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
/// b0e8748).
///
/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
/// validated values are guaranteed-accepted by the apiserver without
/// re-validation at any downstream renderer or admission layer.
fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
    // Empty is gated separately at the call site for a self-locating
    // diagnostic; re-checking here keeps the predicate usable from any
    // future call site (the M4 CR materializer's per-affinity
    // validator) without an empty-check footgun. Routes through the
    // shared [`crate::render::require_valid_dns_1123_label`] gate the
    // peer name axes each land on.
    crate::render::require_valid_dns_1123_label(
        affinity,
        || AplicacaoError::PlacementAffinityEmpty,
        |reason| AplicacaoError::PlacementAffinityInvalid {
            affinity: affinity.to_string(),
            reason,
        },
    )
}

/// Reject `:placement :shard-key` extractor expressions whose shape can
/// never legitimately drive the future M4 Akka-style cluster-sharding
/// reconciler's hash-extractor pass. Maps the per-byte / length checks
/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
/// diagnostic is self-locating (the offending `:shard-key` value is
/// named verbatim alongside the parser-shaped reason) and the author can
/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
/// edit.
///
/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
/// expression naming the message property to hash on. The realistic
/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
/// property name; `$tenantId` — Akka entity-id placeholder;
/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
/// `${tenant}` — interpolation-style template) all sit in the printable
/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
/// multi-line blob landing in `:shard-key`, an embedded space from a
/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
/// check and the failure surfaces at the future M4 reconciler's hash
/// pass as a runtime extractor-evaluation error far from the source
/// `caixa.lisp`, with no field naming which member's `:shard-key`
/// carried the offending value.
///
/// The contract — the printable ASCII single-token intersection-floor
/// every Akka-style entity-id extractor implementation admits:
///
///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
///     peer DNS-1123-label-shaped `:placement :affinity` /
///     `:placement :clusters` identifier axes; realistic shard-keys sit
///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
///     blob footguns at validate time;
///   - every byte in the printable ASCII range `0x21..=0x7E` —
///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
///     `"$tenantId\n"` from paste-from-aligned-doc /
///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
///     `\x7F` — the canonical "embedded null from a copy-paste-binary
///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
///     un-Punycode-encoded IDN that round-trips inconsistently across
///     NFC/NFD normalization).
///
/// The accepted set is broader than the DNS-1123 label floor the peer
/// `:placement :clusters` / `:placement :affinity` axes use because the
/// `:shard-key` value is not a K8s `metadata.name` / label-selector
/// landing site; it's an extractor expression the future Akka-style
/// reconciler reads as a property reference. The realistic forms
/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
/// but every Akka-style entity-id extractor parses. The
/// printable-ASCII-token floor accepts every shape any such extractor
/// would accept while rejecting the cross-implementation footguns
/// (whitespace breaks token boundaries; non-ASCII round-trips
/// inconsistently across YAML emitters and NFC/NFD normalization;
/// control characters silently corrupt the next read).
///
/// Until this gate landed `validate_placement` only refused the
/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
/// control character from paste-from-binary, the 64-byte over-cap
/// paste-from-doc multi-line slug) silently passed validate. The future
/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
/// would then surface the malformed value either as a runtime
/// extractor-evaluation error (whitespace breaks the extractor's token
/// boundary, no match) or as a silently-different shard assignment
/// across YAML emitters (non-ASCII normalizes differently between the
/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
/// parser, the same entity ID maps to two distinct shards on a
/// re-render). Lifting the shape gate to caixa-build time makes the
/// extractor-floor invariant a structural property of every validated
/// `Placement`: every `Sharded` placement past `validate_placement` has
/// a `:shard-key` the future M4 reconciler can hash without
/// re-validating at the runtime layer.
///
/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
/// [`AplicacaoError::ContratoSubjectInvalid`] /
/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
/// on the peer `:contratos` payload axes — each lifts the
/// runtime-side parser's intersection-floor to a caixa-build-time gate,
/// closing the canonical "this passed validate but the runtime parser
/// rejected it" surprise.
fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
    // Empty is gated separately at the call site via the more
    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
    // re-checking here keeps the predicate usable from any future call
    // site (the M4 CR materializer's per-shard-key validator) without
    // an empty-check footgun.
    if key.is_empty() {
        return Err(AplicacaoError::ShardedKeyEmpty);
    }
    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
        return Err(AplicacaoError::ShardKeyInvalid {
            shard_key: key.to_string(),
            reason: format!(
                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
                 well under 32 bytes, this length suggests a paste-from-doc \
                 multi-line blob landed in `:shard-key` instead of a single-token \
                 extractor expression)",
                key.len()
            ),
        });
    }
    for &b in key.as_bytes() {
        if (0x21..=0x7E).contains(&b) {
            continue;
        }
        let reason = if b == b' ' {
            "contains a space (Akka-style entity-id extractor expressions are \
             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
             whitespace breaks the extractor's token boundary at the runtime layer, \
             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
             a multi-token blob in one `:shard-key` slot)"
                .to_string()
        } else if b == b'\t' {
            "contains a tab character (paste-from-aligned-doc footgun; the \
             Akka-style entity-id extractor reads `:shard-key` as a single-token \
             reference, embedded whitespace breaks the token boundary at the \
             runtime hash-extractor pass)"
                .to_string()
        } else if b == b'\n' || b == b'\r' {
            format!(
                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
                 paste-from-multiline-doc footgun; the Akka-style entity-id \
                 extractor reads `:shard-key` as a single-token reference, embedded \
                 newlines either truncate the value at the YAML emitter layer or \
                 break the token boundary at the runtime hash-extractor pass)"
            )
        } else if b < 0x20 || b == 0x7F {
            format!(
                "contains control character 0x{b:02x} (the canonical \
                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
                 control characters silently corrupt round-trip serialization \
                 across YAML emitters and break the runtime hash-extractor's \
                 single-token parser)"
            )
        } else {
            format!(
                "contains non-ASCII byte 0x{b:02x} (the canonical \
                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
                 across YAML emitter implementations — the same entity ID can \
                 silently map to two distinct shards on a re-render. Use a \
                 printable-ASCII extractor expression like `tenantId`, \
                 `$tenantId`, or `metadata.tenantId`)"
            )
        };
        return Err(AplicacaoError::ShardKeyInvalid {
            shard_key: key.to_string(),
            reason,
        });
    }
    Ok(())
}

/// Reject `:contratos :de` / `:contratos :para` values whose shape
/// can never legitimately match a validated `:membros :caixa`. Thin
/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
/// shared parser-shaped reason into the
/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
/// diagnostic is self-locating (which slot — `:de` or `:para` — and
/// the offending value verbatim) and the author can grep their
/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
/// one edit.
///
/// Until this gate landed an empty or DNS-1123-malformed `:de` /
/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
/// un-Punycode-encoded IDN) silently passed the per-axis check and
/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
/// membership lookup — diagnostic-framed as "this caixa is not in
/// `:membros`" when the root cause is "this `:de` value is not a
/// well-shaped Servico-name identifier and could never legitimately
/// match any validated member". Because every `:membros :caixa` is
/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
/// `names` HashSet structurally never contains an empty / malformed
/// string, so the membership lookup arm misframes every empty /
/// malformed input. Lifting the shape arm ahead of the lookup
/// preserves the legitimate `ContratoMemberMissing` arm (a
/// well-shaped `:de` that simply isn't in `:membros` — a phantom
/// reference) while routing every structurally-impossible-to-match
/// input through the narrower self-locating shape diagnostic.
///
/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
/// to land on the canonical [`crate::render::is_dns_1123_label`]
/// floor. The `slot: &'static str` field carries the kebab-case
/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
/// per-callback-slot diagnostic shape and the
/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
/// (85f102c) cross-list-tag pattern.
fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
    // Routes through the shared
    // [`crate::render::require_valid_dns_1123_label`] gate the peer
    // name axes each land on. The `slot: &'static str` field flows
    // through both error variants so the diagnostic names which
    // per-edge axis (`:de` vs `:para`) the offending value came from.
    crate::render::require_valid_dns_1123_label(
        caixa,
        || AplicacaoError::ContratoCaixaEmpty { slot },
        |reason| AplicacaoError::ContratoCaixaInvalid {
            slot,
            caixa: caixa.to_string(),
            reason,
        },
    )
}

/// Reject `:entrada :para` values whose shape can never legitimately
/// match a validated `:membros :caixa`. Thin wrapper around
/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
/// variant, so the diagnostic is self-locating (the offending
/// `:entrada :para` value is named verbatim) and the author can grep
/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
///
/// Until this gate landed an empty or DNS-1123-malformed `:entrada
/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
/// ADR typo, `:para "my_cart"` the Python-module-name leak,
/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
/// silently passed the per-axis check and surfaced as
/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
/// — diagnostic-framed as "this caixa is not in `:membros`" when the
/// root cause is "this `:entrada :para` value is not a well-shaped
/// Servico-name identifier and could never legitimately match any
/// validated member". Because every `:membros :caixa` is shape-
/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
/// `HashSet` structurally never contains an empty / malformed string,
/// so the membership lookup arm misframes every empty / malformed
/// input. Lifting the shape arm ahead of the lookup preserves the
/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
/// simply isn't in `:membros` — a phantom reference) while routing
/// every structurally-impossible-to-match input through the narrower
/// self-locating shape diagnostic.
///
/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
/// fourth and last Aplicacao-level Servico-name reference axis to
/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
/// No `slot: &'static str` field because there is only one axis
/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
/// the simpler shape mirrors [`validate_membro_caixa`] and
/// [`validate_placement_cluster`].
fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
    // Empty is gated separately at the call site for a self-locating
    // diagnostic; re-checking here keeps the predicate usable from any
    // future call site (the M4 CR materializer's per-`:entrada`
    // validator) without an empty-check footgun. Routes through the
    // shared [`crate::render::require_valid_dns_1123_label`] gate the
    // peer name axes each land on.
    crate::render::require_valid_dns_1123_label(
        para,
        || AplicacaoError::EntradaParaEmpty,
        |reason| AplicacaoError::EntradaParaInvalid {
            para: para.to_string(),
            reason,
        },
    )
}

/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
/// would refuse at admission time. The contract — exactly the regex
/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
/// and `HTTPRoute.spec.hostnames[]`,
/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
/// (max length 253; per-label max length 63):
///
///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
///     uppercase, no underscore, no Unicode/IDN — IDN must be
///     pre-encoded as Punycode `xn--…` by the author);
///   - exactly one optional leading wildcard label (`*.`); a wildcard
///     in any non-leading label position is rejected;
///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
///   - total length 1..=253 bytes;
///   - no IPv4 literal (Gateway API forbids IP literals);
///   - no scheme (`https://`, `http://`), no port (`:8080`), no
///     whitespace, no path (`/`).
///
/// Lifted as a typed gate (rather than an inline cascade in
/// `validate()`) so the contract lives in one place — every future
/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
/// materializer's host validator, the future per-`:entrada` SAN
/// emission for cert-manager Certificates, the multi-`:entrada`
/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
/// for the same predicate, not its own. Same compounding shape as
/// `is_canonical_rate_limit_window` (808017c) and
/// [`WitTarget::label`] (previously the free `contrato_target_label`
/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
/// per-variant label match is compiler-checked-exhaustive).
///
/// The diagnostic carries the offending `host:` verbatim plus a
/// parser-shaped `reason:` naming the specific violation, so the
/// author can grep their caixa.lisp for `:host "<host>"` and fix it
/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
/// (9888b13).
fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
    // Empty is already gated by `EmptyEntradaHost` at the call site;
    // re-checking here keeps the predicate usable from any future
    // call site (M4 CR materializer) without an empty-check footgun.
    if host.is_empty() {
        return Err(AplicacaoError::EmptyEntradaHost);
    }
    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: format!(
                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
                host.len(),
                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
            ),
        });
    }
    if host.contains("://") {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
                     Gateway API takes the bare hostname)"
                .to_string(),
        });
    }
    if host.contains('/') {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
                     matching is in `:entrada :paths`)"
                .to_string(),
        });
    }
    // After the `://` scheme-prefix and `/` path arms have ruled out the
    // two `:`-bearing shapes the Gateway API actively rejects with
    // location-shaped diagnostics, any remaining `:` in the host body is
    // either the canonical "I put the port in the `:host` slot"
    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
    // slot lives one axis away on the same `:entrada` block) or an
    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
    // Hostname forbids identically to the IPv4-literal arm below. Both
    // shapes silently fell through the `://` and `/` arms before this
    // lift and surfaced as a deep `label "<rest>:<port>" contains
    // invalid character ':'` diagnostic from the per-byte loop near the
    // bottom of this predicate, which named the offending byte but not
    // the canonical authoring fix — for the port case the author has to
    // know the `:entrada` block carries a separate `:port u16` slot
    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
    // move the value over; for the IPv6 case the author has to know
    // Gateway API v1 forbids IP literals across the board. The contract
    // doc-comment above already promises "no port (`:8080`)" verbatim
    // in the rejected-shape enumeration but the predicate's
    // implementation refused the `:` only as a side-effect of the
    // per-label `[a-z0-9-]` character-class loop; this arm brings the
    // implementation in line with the documented contract by surfacing
    // the canonical fix at the top-level shape gate, peer with how the
    // `://` arm names the scheme prefix and the `/` arm names the
    // `:entrada :paths` axis. Same compounding trajectory the recent
    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
    // — the typed slot's rejected set matches the apiserver's rejected
    // set, structurally, with a self-locating diagnostic at the
    // offending axis instead of a deep parser-shape leak.
    if host.contains(':') {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
                     slot — a separate `u16` axis on the same `:entrada` block, \
                     defaulting to 8080 — not in the host body; drop the `:<port>` \
                     suffix and author the bare hostname. If you intended an IPv6 \
                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
                     Hostname forbids IP literals identically to the IPv4-literal \
                     arm — use a DNS name)"
                .to_string(),
        });
    }
    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
    // predicate — the same single source of truth every peer
    // ASCII-whitespace scan in caixa-core flows through: the four
    // typed-magnitude codec sites (`limits::parse_byte_size` backing
    // `:limits :memory`, `limits::parse_duration` backing `:limits
    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
    // `aplicacao::rate_limit_codec::parse` backing `:politicas
    // :rate-limit`) and the shared duration codec
    // (`supervisor::duration_codec::parse`) backing `:supervisor
    // :restart-window` / `:politicas :timeout` / `:politicas
    // :circuit-breaker :window`. This landing closes the last string-typed
    // slot in caixa-core still calling `.bytes().any(|b|
    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
    // across every typed slot now shares one predicate, so a future
    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
    // deliberately excluded from the peer non-ASCII predicate) can
    // extend at this shared site in one edit rather than seven
    // independent scans diverging over time. Naming the offending byte
    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
    // the offending byte verbatim" discipline every peer codec site
    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: format!(
                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
                 Hostname is a single-token DNS name — leading, trailing, \
                 or embedded whitespace breaks the K8s apiserver's Hostname \
                 regex at admission time; the paste-from-aligned-doc / \
                 paste-from-shell-history / paste-from-CSV footgun silently \
                 lands a multi-token blob in `:entrada :host`. Strip every \
                 whitespace byte and author the bare hostname — space \
                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
                 refuse identically)"
            ),
        });
    }
    // Peer of the ASCII-whitespace scan above: route the non-ASCII
    // subset of Unicode `White_Space` through the shared
    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
    // single source of truth every peer non-ASCII-whitespace scan in
    // caixa-core flows through: `limits::parse_byte_size` (`:limits
    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
    // `limits::parse_millicores` (`:limits :cpu`),
    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
    // and `supervisor::duration_codec::parse` (`:supervisor
    // :restart-window` / `:politicas :timeout` / `:politicas
    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
    // paste-from-web-doc), or an EM-SPACE-split host
    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
    // survived this predicate's ASCII byte-scan (none of the UTF-8
    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
    // `u8::is_ascii_whitespace`), then landed on the per-label
    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
    // predicate with the generic `label "…" must start and end with an
    // alphanumeric` diagnostic — a "far from source at build-time"
    // leak that names the label-shape violation but not the
    // paste-from-typography origin the author actually needs to fix.
    // Peer with the four codec sites the 1b75b38 landing pinned: the
    // typed slot's diagnostic axis names the offending codepoint
    // (`U+XXXX`) verbatim rather than laundering the value through a
    // downstream label-shape arm, so the author can grep their
    // caixa.lisp for the invisible codepoint at the surfaced position
    // rather than eyeball a multi-byte host for embedded NBSP / LINE
    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
    // drift between any two typed-slot sites' non-ASCII-whitespace
    // rejection set becomes a single-edit fix at the shared predicate
    // rather than N independent inline scans diverging over time, and
    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
    // `char::is_whitespace`" class the peer non-ASCII predicate's
    // doc-comment names as the follow-up trajectory) extends at the
    // shared predicate in one edit rather than seven.
    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: format!(
                "contains non-ASCII Unicode whitespace character {ch:?} \
                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
                 single-token DNS name limited to `[a-z0-9-]` labels; \
                 the paste-from-typography footgun silently lands an \
                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
                 `U+3000`, and every other member of the Unicode \
                 `White_Space` property outside the ASCII byte range) \
                 in `:entrada :host`, which the K8s apiserver's \
                 Hostname regex refuses at admission time far from the \
                 caixa.lisp source line. Strip every non-ASCII \
                 whitespace character and author the bare hostname \
                 with only ASCII bytes (write \"checkout.quero.cloud\" \
                 verbatim)",
                codepoint = ch as u32,
            ),
        });
    }

    // Strip the optional single leading wildcard label *before* the
    // trailing-dot check so the bare `"*."` form surfaces the more
    // self-locating "wildcard without domain" diagnostic instead of
    // the generic "trailing dot" one.
    let (had_wildcard, rest) = match host.strip_prefix("*.") {
        Some(r) => (true, r),
        None => (false, host),
    };
    if had_wildcard && rest.is_empty() {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
        });
    }
    if rest.contains('*') {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
                     no inner or trailing `*` labels"
                .to_string(),
        });
    }
    if rest.ends_with('.') {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: "must not have a trailing `.` (Gateway API hostnames are not \
                     fully-qualified with a root dot; the apiserver regex rejects \
                     trailing dots)"
                .to_string(),
        });
    }

    // Reject pure IPv4 literals: four dot-separated labels, every
    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
    // literals as Hostnames.
    let labels: Vec<&str> = rest.split('.').collect();
    if labels.len() == 4
        && labels
            .iter()
            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
    {
        return Err(AplicacaoError::EntradaHostInvalid {
            host: host.to_string(),
            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
                     literals; use a DNS name)"
                .to_string(),
        });
    }

    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
    // hyphen, with non-hyphen at both boundaries.
    for label in &labels {
        if label.is_empty() {
            return Err(AplicacaoError::EntradaHostInvalid {
                host: host.to_string(),
                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
            });
        }
        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
            return Err(AplicacaoError::EntradaHostInvalid {
                host: host.to_string(),
                reason: format!(
                    "label {label:?} exceeds DNS-1123 label max length of \
                     {cap} bytes (got {} bytes)",
                    label.len(),
                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
                ),
            });
        }
        let bytes = label.as_bytes();
        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
            return Err(AplicacaoError::EntradaHostInvalid {
                host: host.to_string(),
                reason: format!(
                    "label {label:?} must start and end with an alphanumeric \
                     (no leading or trailing `-`)"
                ),
            });
        }
        for &b in bytes {
            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
            if !valid {
                let msg = if b.is_ascii_uppercase() {
                    format!(
                        "label {label:?} contains uppercase character {ch:?} \
                         (Gateway API hostnames are lowercase-only; use {lower:?})",
                        ch = b as char,
                        lower = label.to_ascii_lowercase()
                    )
                } else if b == b'_' {
                    format!(
                        "label {label:?} contains `_` (Gateway API hostnames \
                         allow only `[a-z0-9-]`; use `-` instead)"
                    )
                } else {
                    format!(
                        "label {label:?} contains invalid character {ch:?} \
                         (Gateway API hostnames allow only `[a-z0-9-]`)",
                        ch = b as char
                    )
                };
                return Err(AplicacaoError::EntradaHostInvalid {
                    host: host.to_string(),
                    reason: msg,
                });
            }
        }
    }
    Ok(())
}

/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
/// would refuse at admission time. Thin wrapper around
/// [`crate::render::is_gateway_api_http_path`] that maps the shared
/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
/// variant, preserving the more self-locating
/// [`AplicacaoError::EntradaPathEmpty`] /
/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
/// path fails those narrower invariants first.
///
/// The contract is the canonical HTTP-path grammar — `1..=
/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
/// whitespace/control/non-ASCII bytes — shared with the
/// `:contratos :endpoint` axis through the lifted predicate so drift
/// between either landing site and the K8s apiserver-side
/// HTTPPathMatch.value OpenAPI schema is a build error visible at
/// the predicate, not a per-renderer "this passed validate but failed
/// admission" surprise. The diagnostic carries the offending `path:`
/// verbatim plus a parser-shaped `reason:` naming the specific
/// violation, so the author can grep their caixa.lisp for `:paths`
/// and fix it in one edit. Same diagnostic shape as
/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
/// axis.
fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
    // Empty and missing-leading-`/` are already gated at the call
    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
    // checking here keeps the per-axis narrower diagnostics in force
    // when the predicate is reached directly (and `is_gateway_api_http_path`
    // itself defends against `bytes[0]`-style indexing on empty
    // input).
    if path.is_empty() {
        return Err(AplicacaoError::EntradaPathEmpty);
    }
    if !path.starts_with('/') {
        return Err(AplicacaoError::EntradaPathNotAbsolute {
            path: path.to_string(),
        });
    }
    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
        AplicacaoError::EntradaPathInvalid {
            path: path.to_string(),
            reason,
        }
    })
}

mod rate_limit_codec {
    // `Duration` is no longer named here — the codec routes through
    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
    // closed-set enum's arm-table rather than through vestigial free-helper
    // delegates.
    use super::{RateLimit, RateLimitUnit};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
        match v {
            Some(rl) => s.serialize_str(&render(*rl)),
            None => s.serialize_none(),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
        let opt: Option<String> = Option::deserialize(d)?;
        match opt {
            None => Ok(None),
            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
        }
    }

    fn parse(s: &str) -> Result<RateLimit, String> {
        // Whitespace-rejection arm — peer with the leading-`+`
        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
        // same canonical-form render-determinism axis. Until this gate
        // landed the parser silently tolerated leading / trailing /
        // internal whitespace via the top-level `s.trim()` and the
        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
        // serde silently round-tripped to `"100/s"` on the next emit
        // (a *different* canonical string) — breaking the THEORY.md
        // Part V render-determinism contract on the same
        // canonical-form-drift axis the leading-`+` arm below (the
        // 4eeae98 predecessor) and the leading-zero arm below (the
        // 4f46830 predecessor) already close.
        //
        // The canonical author shape is `<integer>/<s|m|h>` with no
        // whitespace bytes anywhere — every string [`render`] emits
        // carries none, so the parser's accepted set must match for
        // serialize / deserialize to round-trip losslessly. This gate
        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
        // `unit.trim()` calls below strict no-ops on the accepted set
        // (every byte-position match they would perform is now already
        // trimmed away by the accepted set itself), while the arm
        // surfaces every rejected whitespace-carrying shape with a
        // self-locating diagnostic naming the offending byte and the
        // canonical form the author intended, peer with every prior
        // canonical-form-drift arm on this codec.
        //
        // Routed through the lifted
        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
        // same source of truth the four peer typed-magnitude codec
        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
        // `limits::parse_millicores`, `supervisor::duration_codec`)
        // share. `u8::is_ascii_whitespace()` at the predicate covers
        // the five WhatWG-conformant ASCII whitespace bytes (space,
        // tab, LF, FF, CR); the "single lifted predicate" discipline
        // the peer non-ASCII arm below carries on the strictly-
        // complementary Unicode `White_Space` class extends here to
        // the ASCII byte set as well.
        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
            return Err(format!(
                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
                 on first serialize — breaking the THEORY.md Part V render-determinism \
                 contract every typed slot carries. Strip every whitespace byte (write \
                 `\"100/s\"` verbatim)"
            ));
        }
        // Non-ASCII Unicode `White_Space` arm — the strictly-
        // complementary class the ASCII arm above cannot see.
        // `str::trim` at the top of every peer codec uses
        // `char::is_whitespace` (Unicode `White_Space`, strictly
        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
        // survives the byte-scan (its UTF-8 bytes are not in
        // `is_ascii_whitespace`), gets silently stripped by the
        // top-level `s.trim()` below, and the value round-trips
        // through `render` to a *different* canonical form
        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
        // render-determinism contract every typed slot carries.
        // Closed here (`:politicas :rate-limit`) and at the three
        // peer codec sites (`limits::parse_byte_size`,
        // `limits::parse_duration`, `supervisor::duration_codec`)
        // through the shared
        // [`crate::render::find_non_ascii_whitespace_char`] predicate
        // — the "single lifted predicate across all four codec sites
        // in one follow-up run" the 24a8ad4 commit body's `Forward
        // compounding` bullet named as the next compounding step.
        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
            return Err(format!(
                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
                 silently strips it at parse entry, and the value round-trips through \
                 `render` to a *different* canonical form (`\"100/s\"`) on first \
                 serialize — breaking the THEORY.md Part V render-determinism contract \
                 every typed slot carries. Strip every non-ASCII whitespace character \
                 (write `\"100/s\"` verbatim with only ASCII bytes)",
                cp = ch as u32
            ));
        }
        let s = s.trim();
        let (rate_str, unit) = s
            .split_once('/')
            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
        let rate_trim = rate_str.trim();
        // The canonical authoring form for `:politicas :rate-limit` is
        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
        // non-negative integer with no decimal point and no leading
        // sign, so the parser's accepted set must match for
        // serialize/deserialize to round-trip without canonical-form
        // drift. Until this gate landed the parser accepted any
        // `u32::from_str`-shaped magnitude — and current Rust
        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
        // serde silently round-tripped to `"100/s"` on the next emit
        // (a *different* canonical string) — breaking the THEORY.md
        // Part V render-determinism contract on the fifth typed-codec
        // surface in caixa-core (peer with the four duration codecs the
        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
        // already covered: `supervisor::duration_codec` backing three
        // typed-duration slots, `limits::parse_duration` backing
        // `:limits :wall-clock`, `limits::parse_byte_size` backing
        // `:limits :memory`). The fractional / decimal-shaped sibling
        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
        // existing rejection arm, but the diagnostic is value-laundered
        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
        // doesn't name the canonical-form remediation or the round-trip
        // drift the next emit would produce); this gate lifts the
        // fractional arm onto the same canonical-form diagnostic the
        // peer codecs carry.
        //
        // Strict canonical form: every byte of the magnitude is an
        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
        // inputs the gate distinguishes "non-canonical-but-numeric"
        // (parses as f64 or i64 — surfaced with a self-locating
        // diagnostic naming the canonical authoring form and the
        // round-trip drift the rejected shape would produce on first
        // serialize) from "garbage" (parses as neither — surfaced with
        // the existing narrower `"not a u32"` wording so its
        // diagnostic shape remains stable for the parser-shape footgun
        // case).
        //
        // Routed through the lifted
        // [`crate::render::is_digit_only_magnitude`] predicate — the
        // same source of truth the four peer typed-magnitude codec
        // sites share.
        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
        if !digit_only {
            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
            if numeric {
                return Err(format!(
                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
                     canonical authoring form for `:politicas :rate-limit` is \
                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
                     with no decimal point and no leading `+` / `-` sign. A fractional / \
                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
                     through `render` to a *different* canonical form (`\"1/s\"`, \
                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
                     THEORY.md Part V render-determinism contract every typed slot \
                     carries. Pick an integer rate that fits the desired window \
                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
                ));
            }
            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
        }
        // Leading-zero arm — peer with the prior `"+100/s"` arm above
        // (4eeae98's predecessor) on the same canonical-form
        // render-determinism axis. The digit-only gate accepts
        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
        // them losslessly (= 100, 0, 7), but `render` emits the
        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
        // a *different* canonical string on the next emit, breaking
        // the THEORY.md Part V render-determinism contract the same
        // way `"+100/s"` did before the leading-`+` arm landed. The
        // single-byte magnitude `"0"` itself round-trips losslessly
        // through `render` (`render(0)` emits `"0/s"`) — the
        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
        // what refuses rate-zero authoring, so `"0/s"` stays in the
        // accepted set at this codec layer and the diagnostic
        // partitioning between canonical-form drift (this arm) and
        // semantic-zero (the downstream gate) remains stable.
        // Peer with the future leading-zero arms on the three peer
        // typed-magnitude codecs the trajectory acknowledges:
        // `supervisor::duration_codec`, `limits::parse_duration`,
        // `limits::parse_byte_size` — each carries the same
        // canonical-form-drift class today; this gate lands the
        // discipline on the fourth typed-magnitude codec in
        // caixa-core first because the peer `"+100/s"` arm above is
        // the closest predecessor on the trajectory.
        //
        // Routed through the lifted
        // [`crate::render::is_leading_zero_padded_magnitude`]
        // predicate — the same source of truth the four peer
        // typed-magnitude codec sites share.
        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
            return Err(format!(
                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
                 canonical authoring form for `:politicas :rate-limit` is \
                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
                 first serialize — breaking the THEORY.md Part V render-determinism \
                 contract every typed slot carries. Strip the leading zeros (write \
                 `\"100/s\"` instead of `\"0100/s\"`)"
            ));
        }
        // The digit-only gate guarantees every byte is `[0-9]`, and
        // the leading-zero arm above guarantees the magnitude is
        // either the single byte `"0"` or starts with `[1-9]`, so
        // the only way `u32::from_str` can fail here is overflow
        // (the magnitude exceeds `u32::MAX`). Surface that with an
        // overflow-shaped wording so the diagnostic names the
        // offending magnitude verbatim rather than collapsing onto
        // the non-canonical arm. Same shape
        // `supervisor::duration_codec` (1c55a2a) carries on the peer
        // duration-codec axis.
        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
        })?;
        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
        // arm reads the `&str → Duration` projection through the
        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
        // with [`super::RateLimitUnit::window`]) rather than the vestigial
        // module-private `rate_limit_window_from_unit` free helper the
        // predecessor 61421a6 left as the last unlifted delegate on this
        // axis. One typed dispatch on the substrate primitive instead of
        // one runtime call through the free-helper delegate; the sole
        // production consumer of the `&str → Duration` axis (this parse
        // arm) now reaches for exactly one typed method on the closed-set
        // enum, sibling to the codec's render arm's
        // [`super::RateLimit::canonical_unit`] dispatch on the paired
        // `Duration → RateLimitUnit` axis and to the validate gate's
        // [`super::RateLimit::canonical_unit`] shape-probe on the
        // canonical-window axis. A future rate-limit-unit addition (a
        // `"d"` day suffix once Envoy's `rate_limit_action` grows
        // daily-bucket support, a `"ms"` sub-second window once
        // high-throughput per-edge policies come into scope per
        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
        // on the closed-set enum, and the compiler enforces exhaustiveness
        // on every consumer's `match self` arms — this parse arm's
        // accepted-suffix set, the render arm's emitted-suffix set, the
        // validate gate's canonical-window set, and every future
        // per-`:contratos`-edge rate-limit-override overlay all pick it up
        // by construction.
        let unit = unit.trim();
        let window = RateLimitUnit::window_from_suffix(unit)
            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
        Ok(RateLimit { rate, window })
    }

    fn render(rl: RateLimit) -> String {
        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
        // this render arm reads the `Duration → RateLimitUnit` projection
        // through the substrate primitive [`super::RateLimit::canonical_unit`]
        // (returns `None` on every non-canonical window — the sub-second /
        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
        // formats the returned typed enum through its
        // [`std::fmt::Display`] impl (which routes through
        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
        // the substrate primitive instead of one runtime `find_map`
        // walk through the free-helper delegate chain
        // [`super::rate_limit_window_unit`] (the vestigial free helper's
        // sole production consumer was this arm; every other consumer of
        // the `Duration → unit` axis — the validate gate below and the
        // future M4 per-Aplicacao Envoy config reconciler — now reads
        // the same typed method).
        //
        // A future rate-limit-unit addition (a `"d"` day suffix once
        // Envoy's `rate_limit_action` grows daily-bucket support) is
        // one variant + one arm per method on the closed-set enum, and
        // the compiler enforces exhaustiveness on every consumer's
        // `match self` arms — the codec's `parse` accepted-suffix set,
        // this render arm's emitted-suffix set, the validate gate's
        // canonical-window set, and every future per-`:contratos`-edge
        // rate-limit-override overlay all pick it up by construction.
        if let Some(unit) = rl.canonical_unit() {
            format!("{}/{unit}", rl.rate())
        } else {
            // Defensive fallback for non-canonical windows. Note:
            // [`AplicacaoSpec::validate_politicas`] rejects any
            // non-canonical `:rate-limit :window` via
            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
            // a validated `RateLimit` never reaches this branch. The
            // emitted `<n>/<k>s` form is *not* round-trippable through
            // [`parse`] (which accepts only the closed-set
            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
            // explicit count) — the validate gate is what makes the
            // round-trip a structural property; this branch exists only
            // so a programmatic non-validated serialize doesn't panic.
            format!("{}/{}s", rl.rate(), rl.window().as_secs())
        }
    }
}

// ── placement strategy ───────────────────────────────────────────────

/// How the Aplicacao distributes across clusters. Three options:
///
/// - `SingleNode` — one cluster runs the app at a time; takeover on
///   death (Erlang/OTP distributed-app semantics).
/// - `Replicated` — every named cluster runs an instance (active-active).
/// - `Sharded` — entities distribute by hash key across clusters
///   (Akka cluster sharding).
#[derive(
    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
)]
pub enum PlacementStrategy {
    SingleNode,
    Replicated,
    Sharded,
}

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

impl PlacementStrategy {
    /// Canonical camelCase-schema discriminator scalar this variant
    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
    /// every substrate consumer that dispatches on the strategy (the
    /// `lareira-fleet-programs` aggregator, the future `app-operator`
    /// reconciler, the M3 Adaptive compression pass) reads the same
    /// byte-string the `Serialize` derive emits — the pin test in
    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
    /// asserts the two paths agree.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
        }
    }
}

/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
/// the pretty-printed byte-string every consumer that formats the strategy
/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
/// per-Aplicacao strategy line, the future M4 CR materializer's per-
/// admission-webhook rejection body) reaches for the same lifted
/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
/// `Serialize` derive already emits under
/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
/// [`PlacementStrategy::as_str`] helper already returns.
///
/// Until this lift landed the sibling OTP-shape typed enums —
/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
/// so [`std::fmt::Display`] routes through the same discriminant string
/// the wire format emits) — carried a stable [`std::fmt::Display`]
/// surface but [`PlacementStrategy`] did not; every consumer reaching
/// for a strategy byte-string past the wire format had to pick between
/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
/// derive), any two of which a future variant rename or
/// `#[serde(rename_all = "kebab-case")]` attribute would silently
/// desynchronize — with the failure surfacing as a downstream renderer /
/// operator's per-strategy dispatch reading one spelling while the wire
/// format emitted another, far from the source rebrand commit and with
/// no field naming the drift. Routing `Display` through
/// [`PlacementStrategy::as_str`] makes the three paths
/// (`Debug` for structural inspection, `Display` for user-facing text,
/// `Serialize` for the wire format) converge on the same lifted
/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
/// the diagnostic byte-string, and the pretty-printed byte-string move
/// as a single unit through one canonical declaration each, by
/// construction. Same trajectory as [`PlacementStrategy::as_str`]
/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
/// closes the third path.
///
/// Pin tests
/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
/// and
/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
/// assert the three paths agree byte-for-byte on every variant, so a
/// future variant rename or per-arm serde attribute drift is a build
/// error visible at caixa-core test time, not a silent per-consumer
/// dispatch miss at apply / reconcile time.
impl std::fmt::Display for PlacementStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Where the Aplicacao runs.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Placement {
    /// Distribution strategy.
    #[serde(default)]
    pub estrategia: PlacementStrategy,

    /// Named clusters that host this Aplicacao. Required for
    /// `Replicated` and `SingleNode`; for `Sharded` declares the
    /// shard pool.
    #[serde(default)]
    pub clusters: Vec<String>,

    /// Optional hint to the placement engine: `"data-locality"`,
    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub affinity: Option<String>,

    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shard_key: Option<String>,
}

impl Placement {
    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
    /// `:shard-key` extractor-expression scalar accessor every consumer
    /// of the Aplicacao's hash-keyed distribution routing keys off —
    /// returns the author-declared `:placement :shard-key` byte-string
    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
    /// own `Option<String>` storage; `None` when the slot is absent
    /// (the canonical shape under `:estrategia Replicated` /
    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
    /// partition — `validate` refuses any `Placement` past this call
    /// that lands `Some` on a non-`Sharded` strategy or `None` on
    /// `Sharded`).
    ///
    /// The `:placement :shard-key` slot carries the Akka-style
    /// cluster-sharding entity-id extractor expression
    /// (MESH-COMPOSITION §II.4) — validated by
    /// [`validate_placement_shard_key`] to be a non-empty printable-
    /// ASCII single-token reference (`tenantId`, `$tenantId`,
    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
    /// future M4 Akka-style cluster-sharding reconciler hashes without
    /// re-validating at the runtime layer), and every downstream
    /// consumer that reads the key keys off this scalar (the
    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
    /// declared-but-inert refusal diagnostic, the caixa-mesh
    /// per-Aplicacao `placement.shardKey` emit path the substrate
    /// operator's per-entity hash-routing reader consumes, the future
    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
    /// per-shard-key resolver).
    ///
    /// Prior to this lift the `.shard_key` field was accessed inline at
    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
    /// — two open-coded field-accesses that expressed no compile-time
    /// link back to the typed slot. A future extension of the
    /// `:placement :shard-key` axis to a richer author surface — a
    /// per-cluster override the operator pins through a future
    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
    /// alias table the M4 CR materializer resolves per-CR, a
    /// per-Aplicacao dynamic `:shard-key` derivation the future
    /// adaptive placement engine computes from `:affinity` weights —
    /// would have had to be threaded through both open-coded copies in
    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
    /// arm refusal would silently disagree on which extractor
    /// expression a given Placement resolves to. Lifting the resolution
    /// rule to a typed method on the substrate primitive means every
    /// downstream consumer of the Aplicacao's per-`:placement`
    /// hash-key surface reaches for exactly one typed dispatch — the
    /// resolver's accept-set migrates as a unit on any future axis
    /// addition.
    ///
    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
    /// [`WitContract::destination`] / [`WitContract::world_ref`]
    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
    /// typed dispatch on the substrate primitive, thin projections at
    /// each consumer" discipline extended onto the per-`:placement`
    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
    /// — opens the "optional per-slot scalar" projection pattern the
    /// sibling per-`:placement` `:affinity`, per-`:politicas`
    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
    /// match the storage field's name; the accessor's identity name
    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
    /// slot's docstring already carries.
    #[must_use]
    pub fn shard_key(&self) -> Option<&str> {
        self.shard_key.as_deref()
    }

    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
    /// compression-hint scalar accessor every weighting-consumer of the
    /// Aplicacao's per-hint routing surface keys off — returns the
    /// author-declared `:placement :affinity` byte-string verbatim as
    /// an `Option<&str>`, borrowed from the typed slot's own
    /// `Option<String>` storage; `None` when the slot is absent (the
    /// canonical shape of an Aplicacao that leaves the compression
    /// weighting up to the placement engine's cluster-default arm — no
    /// author-authored `data-locality` / `low-latency` / etc. hint
    /// biases the routing).
    ///
    /// The `:placement :affinity` slot carries the M3 Adaptive-
    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
    /// by [`validate_placement_affinity`] to be a DNS-1123 label
    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
    /// K8s-conformant label-selector shape every apiserver-side pod-
    /// affinity / node-affinity materializer already gates on
    /// admission), and every downstream consumer that reads the hint
    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
    /// `placement.affinity` overlay emit path the substrate operator's
    /// per-hint weighting-consumer reads, the future M4
    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
    /// pod-affinity / node-affinity selector resolver).
    ///
    /// Prior to this lift the `.affinity` field was accessed inline at
    /// the sole caixa-core site — the
    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
    /// `if let Some(a) = &self.placement.affinity { …
    /// validate_placement_affinity(a)? … }` cascade — one open-coded
    /// field-access that expressed no compile-time link back to the
    /// typed slot. A future extension of the `:placement :affinity`
    /// axis to a richer author surface — a per-cluster override the
    /// operator pins through a future `:placement :affinity-overrides`
    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
    /// tenant hint alias table the M4 CR materializer resolves per-CR,
    /// a per-Aplicacao dynamic `:affinity` derivation the future
    /// adaptive placement engine computes from `:clusters` topology —
    /// would have had to be threaded through the open-coded copy in
    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
    /// materializer reader that landed on the axis, or the per-hint
    /// value-shape gate and its downstream weighting consumers would
    /// silently disagree on which hint a given Placement resolves to.
    /// Lifting the resolution rule to a typed method on the substrate
    /// primitive means every downstream consumer of the Aplicacao's
    /// per-`:placement` compression-hint surface reaches for exactly
    /// one typed dispatch — the resolver's accept-set migrates as a
    /// unit on any future axis addition.
    ///
    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
    /// optional-scalar axis — same "one typed dispatch on the substrate
    /// primitive, thin projections at each consumer" discipline extended
    /// onto the per-`:placement` M3-Adaptive-compression-hint
    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
    /// return accessor on the M3 mesh-slot family; closes the last
    /// un-lifted per-`:placement` `Option<String>` axis. Named
    /// `affinity()` to match the storage field's name; the accessor's
    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
    /// vocabulary the slot's docstring already carries.
    #[must_use]
    pub fn affinity(&self) -> Option<&str> {
        self.affinity.as_deref()
    }

    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
    /// strategy scalar accessor every consumer that dispatches on the
    /// Aplicacao's per-cluster distribution shape keys off — returns the
    /// author-declared `:placement :estrategia` variant verbatim as a
    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
    /// `PlacementStrategy` storage.
    ///
    /// The `:placement :estrategia` slot carries the closed-set
    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
    /// `Replicated` — active-active across every named cluster; `Sharded`
    /// — Akka-style hash-keyed entity distribution across the cluster pool
    /// per §II.4) that every downstream consumer of the Aplicacao's
    /// per-cluster fan-out shape keys off. Validated by
    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
    /// matches!(estrategia, Sharded)` — the cross-slot partition the
    /// [`Placement::shard_key`] accessor's docstring pins), and every
    /// downstream consumer that reads the strategy keys off this scalar
    /// (the [`AplicacaoSpec::validate_placement`]
    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
    /// declared-but-inert refusal's
    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
    /// emit path the substrate operator's per-strategy fan-out reader
    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
    /// materializer's per-strategy admission-webhook resolver).
    ///
    /// Prior to this lift the `.estrategia` field was accessed inline at
    /// four sites — the [`AplicacaoSpec::validate_placement`]
    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
    /// `estrategia: self.placement.estrategia`, the same method's
    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
    /// partition dispatch, the non-`Sharded`-arm
    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
    /// per-Aplicacao strategy print line at
    /// `println!("… {} …", spec.placement.estrategia, …)`
    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
    /// expressed no compile-time link back to the typed slot. A future
    /// extension of the `:placement :estrategia` axis to a richer author
    /// surface (a per-cluster override the operator pins through a future
    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
    /// derivation the future adaptive placement engine computes from
    /// `:affinity` + `:clusters` topology) would have had to be threaded
    /// through every open-coded copy in lockstep — one consumer reading
    /// the raw variant while a peer read the operator-resolved variant
    /// would silently split the `PlacementWithoutClusters` /
    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
    /// partition-dispatch input, a two-consumer split at the validator
    /// far from the source `caixa.lisp` with no field naming the
    /// strategy-drift root cause. Lifting the resolution rule to a typed
    /// method on the substrate primitive means every downstream consumer
    /// of the Aplicacao's per-`:placement` distribution-strategy surface
    /// reaches for exactly one typed dispatch — the resolver's accept-set
    /// migrates as a unit on any future axis addition.
    ///
    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
    /// same "one typed dispatch on the substrate primitive, thin
    /// projections at each consumer" discipline extended onto the
    /// per-`:placement` distribution-strategy `Copy`-composite-enum
    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
    /// family; first `Copy`-return accessor on the M3 mesh-slot
    /// `Placement` type — companion to the sibling per-`:placement`
    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
    /// optional-scalar axes, closing the last unlifted per-`:placement`
    /// scalar-value axis (the closed-set `PlacementStrategy`
    /// distribution-strategy discriminator) so every downstream
    /// per-`:placement` reader now routes through a typed dispatch on
    /// the substrate primitive. Named `estrategia()` to match the storage
    /// field's name; the accessor's identity name maps onto the
    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
    /// already carries.
    #[must_use]
    pub fn estrategia(&self) -> PlacementStrategy {
        self.estrategia
    }

    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
    /// per-cluster distribution-target slice accessor every consumer that
    /// walks the Aplicacao's declared cluster-pool keys off — returns the
    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
    /// `&[String]` slice-view, borrowed from the typed slot's own
    /// `Vec<String>` storage (a zero-copy slice-view over the same
    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
    /// through). Non-optional: the empty slice is the load-bearing
    /// pre-validation sentinel every downstream consumer of the paired
    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
    /// off — every strategy in the closed
    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
    /// requires a non-empty list (`SingleNode` / `Replicated` use the
    /// list as hosting / takeover candidates per Erlang/OTP distributed-
    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
    /// shard pool per Akka cluster-sharding convention, §II.4), so the
    /// `.is_empty()` probe is the shared pre-condition every
    /// [`AplicacaoSpec::validate_placement`] arm heads on.
    ///
    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
    /// 1123-label per-cluster distribution-target list — the same
    /// set-not-multiset shape the sibling `:membros :caixa` /
    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
    /// pins the shape). Every downstream consumer that fans on the list
    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
    /// pre-flight `.is_empty()` probe that trips
    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
    /// per-cluster value-shape + duplicate-detection fan-out loop, the
    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
    /// that materializes the list verbatim onto every
    /// programs.yaml entry the substrate operator's per-cluster
    /// `placement.clusters | contains .Values.cluster` filter reads,
    /// the `feira app graph` per-Aplicacao cluster print line, the
    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
    /// placement engine's cluster-topology reader).
    ///
    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
    /// inline at three production sites — the
    /// [`AplicacaoSpec::validate_placement`] pre-flight
    /// `self.placement.clusters.is_empty()` refusal probe, the same
    /// method's per-cluster validate loop's
    /// `for c in &self.placement.clusters` traversal head, and the
    /// `feira app graph` per-Aplicacao print line's
    /// `spec.placement.clusters` `{:?}` formatter argument
    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
    /// that expressed no compile-time link back to the typed slot. A
    /// future extension of the `:placement :clusters` axis to a richer
    /// author surface (a per-tenant cluster-pool overlay the operator
    /// pins through a future `:placement :clusters-overrides` slot the
    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
    /// the future M5 adaptive-placement engine computes from
    /// `:affinity` weights + live cluster-topology probes, a promotion
    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
    /// partition once the substrate operator's cluster-membership
    /// reconciler comes into typed scope) would have had to be threaded
    /// through all three open-coded copies in lockstep or one consumer
    /// would silently disagree with the peers on which cluster-pool a
    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
    /// reading the raw slot while the peer per-cluster validate loop
    /// read an operator-resolved slot would silently split the paired
    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
    /// input from the pre-flight input, a three-consumer split at the
    /// validator and formatter far from the source `caixa.lisp` with
    /// no field naming the cluster-pool-drift root cause. Lifting the
    /// resolution rule to a typed method on the substrate primitive
    /// means every downstream consumer of the Aplicacao's
    /// per-`:placement` cluster-pool surface reaches for exactly one
    /// typed dispatch — the resolver's accept-set migrates as a unit
    /// on any future axis addition.
    ///
    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
    /// slot — sibling to the seed M2
    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
    /// slice-return accessor on the peer per-`:supervisor` static-
    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
    /// primitive, thin projections at each consumer" discipline. The
    /// three peer `Vec`-carry axes still unlifted at the time of this
    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
    /// [`crate::UpgradeFromEntry::instructions`]
    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
    /// — inherit this accessor's discipline as future compounding runs
    /// migrate their consumers onto the shared slice-return shape.
    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
    /// type, sibling to the two `Option<&str>`-return
    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
    /// (74ec2d3) accessors and the `Copy`-return
    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
    /// unlifted per-`:placement` field axis (the `Vec<String>`
    /// distribution-target-list carrier) so every downstream
    /// per-`:placement` reader now routes through a typed dispatch on
    /// the substrate primitive. Named `clusters()` to match the storage
    /// field's name verbatim and the tatara-lisp author-surface term
    /// (`:clusters`) the field's own docstring already carries; the
    /// accessor's identity maps onto the canonical MESH-COMPOSITION
    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
    /// for. Returns `&[String]` (not `&Vec<String>`) because every
    /// downstream consumer of the cluster list treats it as a read-only
    /// sequence — the slice-view is the narrowest borrow that supports
    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
    /// `.len()`) without leaking the backing `Vec`'s
    /// grow/push/reserve surface that no consumer of the typed view
    /// reaches for (the storage-side `Vec` remains reachable through
    /// the `pub clusters` field for the mutation-carrying serde
    /// round-trip and per-test fixture-mutation paths).
    #[must_use]
    pub fn clusters(&self) -> &[String] {
        self.clusters.as_slice()
    }
}

impl Default for Placement {
    fn default() -> Self {
        Self {
            estrategia: PlacementStrategy::default(),
            clusters: Vec::new(),
            affinity: None,
            shard_key: None,
        }
    }
}

// ── external entry point ─────────────────────────────────────────────

/// External entry point — what an outside caller sees. Renders to a
/// Gateway / Ingress + a route to the named member Servico.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Entrada {
    /// Public hostname (e.g. `"checkout.quero.cloud"`).
    pub host: String,

    /// Member Servico the gateway routes to. Must be in `:membros`.
    pub para: String,

    /// Optional path filter — if set, only matching paths route to
    /// this Aplicacao (the rest fall through to other route rules).
    #[serde(default)]
    pub paths: Vec<String>,

    /// Default port on the destination Servico (the trigger.service.port).
    #[serde(default = "default_port")]
    pub port: u16,
}

impl Entrada {
    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
    /// every HTTPRoute-aware renderer keys off — returns the author-
    /// declared `:entrada :paths` list verbatim when non-empty, and the
    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
    /// all fallback otherwise (so an Aplicacao author who declares an
    /// external `:entrada` block but no per-path rule surface still
    /// gets a route whose sole `HTTPPathMatch` matches every incoming
    /// request under the paired
    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
    ///
    /// Prior to this lift the "if `:entrada :paths` is empty use the
    /// substrate catch-all; else return each declared path verbatim"
    /// cascade lived inline at
    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
    /// substrate ships today, with no typed method on the substrate
    /// primitive that named the rule. A future path-resolution axis
    /// addition — a per-cluster `:entrada :default-path` override the
    /// operator pins through a future `:placement`-scoped slot, an
    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
    /// admission-webhook floor that materializes the catch-all before
    /// the CR lands, a future per-`:entrada :paths` overlay from a
    /// per-cluster policy the future `feira app deploy` pipeline
    /// consumes — would have to be threaded through every renderer's
    /// inline copy of the cascade in lockstep or one consumer would
    /// silently disagree with the peers on which path list a given
    /// `:entrada` block resolves to. Lifting the rule to a typed
    /// method on the substrate primitive means every downstream
    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
    /// per-cluster overlay resolver, every future per-Aplicacao
    /// snapshot renderer) reaches for exactly one typed dispatch —
    /// the resolver's accept-set moves as a unit on any future axis
    /// addition.
    ///
    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
    /// per-`:entrada` scalar-value axes — extends the "one typed
    /// dispatch on the substrate primitive, thin projections at each
    /// consumer" discipline onto the per-`:entrada` path-list
    /// resolution axis every HTTPRoute-aware renderer consumes. Same
    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
    /// sibling `:politicas` primitive — one typed method on the
    /// substrate primitive that names the cascade every renderer
    /// otherwise re-inlines.
    #[must_use]
    pub fn resolved_paths(&self) -> Vec<&str> {
        // Route the internal cascade-head + per-entry projection reads
        // through the lifted [`Self::paths`] slice accessor rather than
        // the raw `self.paths` field access — the substrate-primitive
        // per-`:entrada` path-list resolver's two internal reads now
        // key off the canonical raw-slot surface every downstream
        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
        // entrada summary line's `{:?}` Debug print) routes through, so
        // any future rebrand on the typed slot's raw-slot reader lands
        // at exactly one place. Same two-consumer coherence discipline
        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
        // the peer M3 mesh-slot `Vec<String>`-carry axis.
        if self.paths().is_empty() {
            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
        } else {
            self.paths().iter().map(String::as_str).collect()
        }
    }

    /// Substrate-canonical per-`:entrada` DNS-hostname singular
    /// accessor every Gateway-API `Listener.hostname` reader keys off
    /// — returns the author-declared `:entrada :host` byte-string
    /// verbatim as a `&str`, borrowed from the typed slot's own
    /// [`String`] storage.
    ///
    /// Named the "singular" half of the DNS-hostname resolver pair on
    /// the substrate primitive: the parent-Gateway per-listener
    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
    /// hostname per listener), and this accessor is the typed dispatch
    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
    /// per-Aplicacao ingress-hostname surface projects onto.
    ///
    /// Prior to this lift the `entrada.host.clone()` byte-string was
    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
    /// per-listener singular `hostname:` axis
    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
    /// per-HTTPRoute plural `spec.hostnames[]` axis
    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
    /// consumers read the same `entrada.host` field but the two-site
    /// duplication expressed no compile-time contract that the singular
    /// Gateway-listener filter and the plural `HTTPRoute` filter list
    /// stay in lockstep on future extensions of the `:entrada` slot to
    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
    /// overlay, a per-cluster SNI fan-out the operator pins through a
    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
    /// Aplicacao` CR materializer's per-listener virtual-host filter
    /// admission-webhook overlay). Any such extension would have to be
    /// threaded through every renderer's inline copy of the resolution
    /// in lockstep or the Gateway listener's `hostname:` filter would
    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
    /// — a Gateway-API-conformance divergence whose apply-time symptom
    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
    /// `NoMatchingParent` — the API server rejects the route because
    /// its `hostnames[]` filter doesn't intersect the parent listener's
    /// `hostname` filter) is far from the source `caixa.lisp` and never
    /// surfaces in the emitted YAML. Lifting the singular and plural
    /// resolvers to typed methods on the substrate primitive means
    /// every consumer of the Aplicacao's ingress-hostname surface
    /// reaches for exactly one typed dispatch, and the pair-invariant
    /// `hostnames() == vec![hostname()]` pinned by the sibling
    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
    /// keeps the two axes in lockstep by construction.
    ///
    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
    /// the substrate primitive, thin projections at each consumer"
    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
    /// `:entrada` scalar-value + list-value axes.
    #[must_use]
    pub fn hostname(&self) -> &str {
        self.host.as_str()
    }

    /// Substrate-canonical per-`:entrada` DNS-hostname plural
    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
    /// keys off — returns the singleton `[hostname()]` list under
    /// today's single-hostname-per-Aplicacao author surface, and the
    /// authoritative multi-hostname list under a future
    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
    ///
    /// Plural half of the DNS-hostname resolver pair — see the
    /// companion [`Entrada::hostname`] docstring for the two-consumer
    /// lift + pair-invariant discipline (`hostnames() ==
    /// vec![hostname()]`, pinned load-bearing by the sibling
    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
    /// test).
    ///
    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
    /// per-rule path-list axis — same `Vec<&str>` shape, same
    /// substrate-primitive-owns-the-resolver discipline extended to
    /// the per-HTTPRoute virtual-host filter-list axis.
    #[must_use]
    pub fn hostnames(&self) -> Vec<&str> {
        vec![self.hostname()]
    }

    /// Substrate-canonical per-`:entrada` destination-Servico scalar
    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
    /// the author-declared `:entrada :para` byte-string verbatim as a
    /// `&str`, borrowed from the typed slot's own [`String`] storage.
    ///
    /// The `:entrada :para` slot names the single member Servico the
    /// external Gateway routes to (validated by
    /// [`AplicacaoSpec::validate`] to be a
    /// [`Membro::caixa`] the Aplicacao declares — a stray
    /// `:para` that doesn't name a member is
    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
    /// backend-attachment miss at cluster-apply time). Under today's
    /// single-destination author surface `:entrada :para` is the ingress
    /// apex Servico's canonical identity; under a hypothetical
    /// future multi-backend author surface (a `:entrada
    /// :split :backends` weighted-fan-out overlay for canary /
    /// blue-green traffic-split rollouts, per-path override for
    /// path-based per-Servico routing beyond the single-apex model,
    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
    /// per-CR admission-webhook that promotes the scalar to a
    /// weighted list) this accessor is the substrate primitive's typed
    /// dispatch every downstream `HTTPRoute`-aware consumer routes
    /// through, so the resolution shape migrates as a unit on one
    /// caixa-core edit rather than a coordinated rewrite across every
    /// renderer's inline field-access.
    ///
    /// Prior to this lift the `entrada.para` byte-string was accessed
    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
    /// `metadata.name` composer's per-destination discriminator arg
    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
    /// (`entrada.para.clone()`,
    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
    /// consumers read the same `entrada.para` field but the two-site
    /// duplication expressed no compile-time contract that the HTTPRoute
    /// name-discriminator and the per-rule backend name stay in
    /// lockstep on future extensions of the `:entrada` slot to a
    /// multi-destination author surface. Any such extension would have
    /// to be threaded through every renderer's inline copy of the
    /// destination projection in lockstep or the HTTPRoute
    /// `metadata.name` would silently reference a different destination
    /// than its own `backendRefs[]` — an operator-side
    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
    /// grep-by-name lookup would land on a route whose `backendRefs[]`
    /// silently point at a peer Servico, dropping every external
    /// `:entrada` flow at the gateway with the destination-drift root
    /// cause invisible in the emitted YAML.
    ///
    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
    /// the per-listener singular / per-HTTPRoute plural filter axes and
    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
    /// typed dispatch on the substrate primitive, thin projections at
    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
    /// sibling per-`:entrada` scalar-value + list-value axes — this
    /// accessor closes the last unlifted per-`:entrada` scalar axis
    /// (the destination-Servico byte-string) so every downstream
    /// per-`:entrada` reader now routes through a typed dispatch on
    /// the substrate primitive.
    #[must_use]
    pub fn destination(&self) -> &str {
        self.para.as_str()
    }

    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
    /// reader keys off — returns the author-declared `:entrada :port`
    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
    /// [`AplicacaoError::EntradaPortZero`], not a silent
    /// admission-webhook rejection at cluster-apply time).
    ///
    /// The `:entrada :port` slot carries the destination Servico's
    /// canonical in-cluster L4 listener port (`trigger.service.port` on
    /// the `pleme-computeunit` library chart), and every downstream
    /// consumer that reads the port keys off this scalar (the
    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
    /// CR materializer's per-Aplicacao gateway port resolver).
    ///
    /// Prior to this lift the `.port` field was accessed inline at two
    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
    /// the [`AplicacaoSpec::port_for_destination`] resolver's
    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
    /// open-coded field-accesses that expressed no compile-time link
    /// back to the typed slot. A future extension of the `:entrada :port`
    /// axis to a richer author surface — a per-cluster override the
    /// operator pins through a future `:placement :default-port` slot the
    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
    /// heterogeneous listener ports, an M4
    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
    /// admission-webhook floor that promotes the scalar to a
    /// per-destination map — would have had to be threaded through both
    /// open-coded copies in lockstep or the structural-floor validator
    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
    /// silently disagree on which port a given [`Entrada`] resolves to.
    /// Lifting the resolution rule to a typed method on the substrate
    /// primitive means every downstream consumer of the Aplicacao's
    /// per-`:entrada` L4-port surface reaches for exactly one typed
    /// dispatch — the resolver's accept-set migrates as a unit on any
    /// future axis addition.
    ///
    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
    /// accessors on the per-`:entrada` scalar-value axis — same "one
    /// typed dispatch on the substrate primitive, thin projections at
    /// each consumer" discipline extended onto the per-`:entrada`
    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
    /// storage field's name; the accessor's identity name maps onto the
    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
    /// already carries.
    #[must_use]
    pub fn port(&self) -> u16 {
        self.port
    }

    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
    /// slice accessor every HTTPRoute-aware renderer keys off when it
    /// wants the raw author-declared path-list (not the fallback-
    /// applied projection [`Self::resolved_paths`] returns) — returns
    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
    /// borrowed from the typed slot's own [`Vec<String>`] storage.
    ///
    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
    /// (1449891) closes the fallback-applying arm every per-Aplicacao
    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
    /// catch-all; non-empty slot → per-entry verbatim projection); this
    /// accessor closes the raw-slot arm every consumer that must see the
    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
    /// external-gateway summary line's `{:?}` Debug print — which must
    /// name the author's declaration, not the substrate's fallback, so
    /// an author reading their graph output can grep their caixa.lisp
    /// for the exact list they authored) routes through.
    ///
    /// Prior to this lift the `.paths` field was accessed inline at four
    /// production sites: the two internal reads in [`Self::resolved_paths`]
    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
    /// value-shape gate's `for p in &e.paths` traversal head, and the
    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
    /// Debug print — four open-coded field-accesses that expressed no
    /// compile-time link back to the typed slot. A future extension of
    /// the `:entrada :paths` axis to a richer author surface — a
    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
    /// spec supports through `matches[].method`), a per-path per-header
    /// filter overlay (`matches[].headers[]`), a per-cluster override
    /// the operator pins through a future `:placement :path-overlay`
    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
    /// per-CR admission-webhook that normalized the list at admission
    /// time — would have had to be threaded through every open-coded
    /// copy in lockstep or the validator's per-entry gate would silently
    /// disagree with the renderer's per-entry emit on which list a given
    /// `:entrada` block resolves to. Lifting the resolution to a typed
    /// method on the substrate primitive means every downstream consumer
    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
    /// exactly one typed dispatch — the resolver's accept-set migrates
    /// as a unit on any future axis addition.
    ///
    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
    /// carry axis — same "one typed dispatch on the substrate primitive,
    /// thin projections at each consumer" discipline extended onto the
    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
    /// carrier) so every downstream per-`:entrada` reader now routes
    /// through a typed dispatch on the substrate primitive. Returns
    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
    /// treats the list as a read-only sequence — the slice-view is the
    /// narrowest borrow that supports every present + roadmapped consumer
    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
    /// view reaches for (the storage-side `Vec` remains reachable through
    /// the `pub paths` field for the mutation-carrying serde round-trip
    /// and per-test fixture-mutation paths).
    #[must_use]
    pub fn paths(&self) -> &[String] {
        self.paths.as_slice()
    }
}

/// Canonical default L4 port every typed Servico exposes on its
/// in-cluster K8s Service (the `trigger.service.port` axis the
/// `pleme-computeunit` library chart emits, the `:entrada :port` author
/// surface defaults to when the author omits the slot, and the
/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
/// `:entrada` block matches the per-`:contratos` destination Servico).
/// The single source of truth all three typed-port consumers reach for:
///
///   - [`Entrada::port`]'s serde default (via the
///     [`default_port`] helper this constant feeds); the author surface
///     `(:entrada (:host … :para …))` without an explicit `:port` slot
///     reads back as a typed [`Entrada`] carrying this exact value;
///   - the
///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
///     fallback, fired when the typed `:entrada` block doesn't name
///     the per-`:contratos` destination Servico — the typed
///     `:contratos` graph carries no per-destination port axis (the
///     destination port is the destination Servico's
///     `lareira-<nome>` chart's `trigger.service.port`, which the
///     Aplicacao-level renderer has no visibility into without a
///     resolver round-trip), so the renderer falls back to the
///     substrate's canonical Servico-port assumption — by
///     construction the same value the destination's own
///     `pleme-computeunit` chart emits, the same value the
///     destination's own typed `:entrada :port` slot defaults to;
///   - every future per-Servico renderer the absorption-roadmap
///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
///     CR materializer's per-edge port resolver, the future
///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
///     emitter's per-route bucket key, the future caixa-otel
///     collector-pipeline emitter's per-Servico scrape port).
///
/// Until this lift landed the value `8080` lived at two production-code
/// call-sites: the [`default_port`] helper at
/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
/// and the `.unwrap_or(8080)` literal at
/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
/// resolver). A future Servico-port rebrand — the substrate moving the
/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
/// gateway grows direct `:80` listeners, to `8443` once the substrate
/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
/// override the operator pins through a future
/// `:placement :default-port` slot — without a coordinated edit on
/// both sides would silently emit Servicos listening on one port and
/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
/// The CNP's apply-time symptom (the policy is admitted but every L4
/// flow on the destination Servico's actual port silently drops because
/// it doesn't match the whitelisted port) is far from the rebrand
/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
/// in hubble traces, not in `kubectl describe`. Lifting the literal to
/// a shared constant closes the drift footgun structurally — both
/// consumers read from the same `u16`, so any rebrand reaches both
/// sites by construction.
///
/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
/// per-renderer canonical-K8s-axis constant — the namespace string
/// and the canonical Servico port both lived as duplicated literals
/// across caixa-core / caixa-mesh / caixa-flux before their respective
/// lifts. Same "the typed constant lives in one place" discipline the
/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
/// shared-string axes.
///
/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
pub const DEFAULT_SERVICO_PORT: u16 = 8080;

/// Structural floor for the typed `:entrada :port` axis — every
/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
///
/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
/// interprets as "let the kernel pick a free port at bind time", not a
/// well-defined destination the substrate's per-`:entrada` Gateway API
/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
/// carrying `port: 0` degenerates to a nominal-only routing target: the
/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
/// at build time rather than at `kubectl apply` time), and the
/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
/// (caixa-mesh/src/lib.rs:2657 through
/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
/// [`Entrada::port`] typed value — silently emits a policy whose
/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
/// actual listener, dropping every L4 flow at the eBPF data plane far
/// from the source caixa.lisp with no field naming the port-zero-drift
/// root cause.
///
/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
/// on the top edge (unlike the peer capped-`u32` `:politicas` /
/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
/// well below `u32::MAX` and therefore need explicit typed caps).
///
/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
/// scalar every `(:entrada (:host … :para …))` slot without an explicit
/// `:port` inherits through the serde default hook; this constant names
/// the accept-set floor every declared port must satisfy. The pair is
/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
/// substrate's default must satisfy its own accept-set floor by
/// construction) — a future rebrand that accidentally moved
/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
/// negative-cast typo, a per-cluster override the operator pins through
/// a future `:placement :default-port` slot that lands out-of-range)
/// would silently invalidate the serde-default emission at every
/// author-side `(:entrada (:host … :para …))` slot — the compile-time
/// invariant pin
/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
/// closes the drift footgun at caixa-core build time.
///
/// Lifted as a typed `pub const` (rather than an inline `0` literal at
/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
/// has exactly one source of truth — the future M4
/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
/// gateway resolver, the future per-Servico
/// `computeunit.trigger.service.port` renderer's per-CR port-value
/// validator, and every downstream test-fixture navigator asserting
/// the accept-set floor all read from one place. Same shape every
/// other typed bracket-floor / bracket-ceiling in this crate carries
/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
/// [`POLICY_RATE_LIMIT_MAX`]).
pub const SERVICO_PORT_MIN: u16 = 1;

const fn default_port() -> u16 {
    DEFAULT_SERVICO_PORT
}

// ── the typed view ───────────────────────────────────────────────────

/// Typed composition view of the flat Aplicacao slots on
/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
/// validation + downstream renderer consumption.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AplicacaoSpec {
    pub membros: Vec<Membro>,
    pub contratos: Vec<WitContract>,
    pub politicas: MeshPolicy,
    pub placement: Placement,
    pub entrada: Option<Entrada>,
}

impl AplicacaoSpec {
    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
    /// per-Aplicacao member-list slice-return accessor every
    /// per-Aplicacao member-list reader keys off — returns the author-
    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
    /// over the same backing buffer the raw `self.membros.as_slice()`
    /// field access borrows from.
    ///
    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
    /// member list — the load-bearing identity of the application graph
    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
    /// accessor) with a `:versao` semver-requirement string (through
    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
    /// and every downstream consumer that fans on the member-set keys
    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
    /// membership-lookup `HashSet<&str>` seed's collect input, the
    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
    /// per-member DNS-1123 / semver-requirement / duplicate-detection
    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
    /// programs.yaml per-`:membros` fan-out emitter's per-entry
    /// mapping-composition loop, the `feira app graph` per-Aplicacao
    /// member-count print line and per-member tree traversal,
    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
    /// placement engine's per-member weight-topology reader).
    ///
    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
    /// inline at six production sites — the [`AplicacaoSpec::validate`]
    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
    /// probe, the same method's per-member `for m in &self.membros`
    /// validate-loop traversal head, the
    /// [`AplicacaoSpec::detect_sync_cycles`]'s
    /// `for m in &self.membros` adjacency-list seed, the
    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
    /// paired with the peer `for m in &spec.membros` per-entry fan-out
    /// loop, and the `feira app graph` per-Aplicacao print line's
    /// `spec.membros.len()` count formatter argument paired with the
    /// peer `for m in &spec.membros` per-member tree traversal — six
    /// open-coded field-accesses that expressed no compile-time link
    /// back to the typed slot. A future extension of the `:membros`
    /// axis to a richer author surface (a per-cluster member-set
    /// overlay the operator pins through a future
    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
    /// roadmap acknowledges, a per-tenant member-alias table the M4
    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
    /// CR at admission time, a per-Aplicacao dynamic member-set
    /// derivation the future adaptive-placement engine computes from
    /// weighted membership topology, a promotion of the plain
    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
    /// Orleans-style virtual-actor dynamic-membership comes into typed
    /// scope) would have had to be threaded through all six open-coded
    /// copies in lockstep or one consumer would silently disagree with
    /// the peers on which member-set a given Aplicacao resolves to —
    /// the `HashSet<&str>` name-set seed reading the raw slot while
    /// the peer `.is_empty()` refusal probe read an operator-resolved
    /// slot would silently split the `:contratos` membership-lookup
    /// input from the pre-flight-refusal input, a six-consumer split
    /// at the validator + programs.yaml emitter + graph printer far
    /// from the source `caixa.lisp` with no field naming the member-
    /// set-drift root cause. Lifting the resolution rule to a typed
    /// method on the substrate primitive means every downstream
    /// consumer of the Aplicacao's per-`:membros` member-list surface
    /// reaches for exactly one typed dispatch — the resolver's accept-
    /// set migrates as a unit on any future axis addition.
    ///
    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
    /// static-child-list `Vec`-carry axis, and to the M3
    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
    /// on the peer per-`:placement` distribution-target-list `Vec`-
    /// carry axis. Same "one typed dispatch on the substrate primitive,
    /// thin projections at each consumer" discipline. The two peer
    /// `Vec`-carry axes still unlifted at the time of this lift —
    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
    /// WIT-typed edge list) and
    /// [`crate::UpgradeFromEntry::instructions`]
    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
    /// — inherit this accessor's discipline as future compounding runs
    /// migrate their consumers onto the shared slice-return shape.
    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
    /// `AplicacaoSpec` type itself, extending the discipline beyond
    /// the inner per-slot types ([`crate::Placement`],
    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
    /// view every renderer consumes. Named `membros()` to match the
    /// storage field's name verbatim and the tatara-lisp author-
    /// surface term (`:membros`) the field's own docstring already
    /// carries; the accessor's identity maps onto the canonical
    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
    /// every downstream consumer of the member list treats it as a
    /// read-only sequence — the slice-view is the narrowest borrow
    /// that supports every present + roadmapped consumer
    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
    /// backing `Vec`'s grow/push/reserve surface that no consumer of
    /// the typed view reaches for (the storage-side `Vec` remains
    /// reachable through the `pub membros` field for the mutation-
    /// carrying serde round-trip and per-test fixture-mutation paths).
    #[must_use]
    pub fn membros(&self) -> &[Membro] {
        self.membros.as_slice()
    }

    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
    /// accessor every per-Aplicacao contract-list reader keys off —
    /// returns the author-declared `:contratos` list verbatim as a
    /// `&[WitContract]` slice-view over the same backing buffer the raw
    /// `self.contratos.as_slice()` field access borrows from.
    ///
    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
    /// WIT-typed edge list — the load-bearing set of directed edges
    /// on the application graph whose nodes are the `:membros` entries
    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
    /// six-tuple is the edge identity every downstream duplicate gate
    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
    /// Servico caller name + a `:para` destination-Servico callee name
    /// (through the lifted [`WitContract::source`] +
    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
    /// caller/callee-Servico axis) with a `:wit` world-reference
    /// (through the lifted [`WitContract::world_ref`] (0804823)
    /// accessor) and the target-shape-appropriate payload-carrier
    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
    /// (ed22b66) accessor on the per-target-shape payload-carrier
    /// axis). Every downstream consumer that fans on the edge-set
    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
    /// name-set / self-edge / target-shape / dedup fan-out loop, the
    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
    /// grouping loop, the `feira app graph` per-Aplicacao contract-
    /// count print line and per-contract tree traversal, every future
    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
    /// mesh-policy overlay resolver's per-contract typed-edge weight
    /// reader).
    ///
    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
    /// accessed inline at four production sites — the
    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
    /// per-edge validate-loop traversal head (which drives every
    /// per-edge name-set membership lookup, self-edge check,
    /// target-shape dispatch, and dedup `HashSet` insert), the
    /// [`AplicacaoSpec::detect_sync_cycles`]'s
    /// `for c in &self.contratos` adjacency-list seed head (which
    /// drives every per-edge sync-vs-pub-sub partition and per-edge
    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
    /// `BTreeMap` grouping loop head (which drives every per-CNP
    /// fan-out emit), and the `feira app graph` per-Aplicacao print
    /// line's `spec.contratos.len()` count formatter argument paired
    /// with the peer `for c in &spec.contratos` per-contract tree
    /// traversal — four open-coded field-accesses that expressed no
    /// compile-time link back to the typed slot. A future extension
    /// of the `:contratos` axis to a richer author surface (a
    /// per-cluster contract overlay the operator pins through a
    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
    /// federation roadmap acknowledges, a per-tenant edge-policy
    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
    /// materializer resolves per-CR at admission time, a per-edge
    /// weight scalar the future adaptive-placement engine reads to
    /// bias sync-subgraph routing, a promotion of the plain
    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
    /// once virtual-actor-style dynamic-edge composition comes into
    /// typed scope) would have had to be threaded through all four
    /// open-coded copies in lockstep or one consumer would silently
    /// disagree with the peers on which edge-set a given Aplicacao
    /// resolves to — the validator's per-edge dedup `HashSet` seed
    /// reading the raw slot while the peer sync-cycle adjacency-list
    /// seed read an operator-resolved slot would silently split the
    /// build-time edge-set gate from the runtime deadlock-detection
    /// gate, a four-consumer split at the validator, the cycle
    /// detector, the CNP emitter, and the graph printer far from
    /// the source `caixa.lisp` with no field naming the edge-set-
    /// drift root cause. Lifting the resolution rule to a typed method on the
    /// substrate primitive means every downstream consumer of the
    /// Aplicacao's per-`:contratos` edge-list surface reaches for
    /// exactly one typed dispatch — the resolver's accept-set
    /// migrates as a unit on any future axis addition.
    ///
    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
    /// static-child-list `Vec`-carry axis, to the M3
    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
    /// on the peer per-`:placement` distribution-target-list `Vec`-
    /// carry axis, and to the immediately-adjacent sibling M3
    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
    /// the peer per-`:membros` node-list `Vec`-carry axis — the
    /// per-`:contratos` edge-list accessor is the natural pair of
    /// the per-`:membros` node-list accessor (graph edges over graph
    /// nodes; every graph-shaped consumer reads both). Same "one
    /// typed dispatch on the substrate primitive, thin projections
    /// at each consumer" discipline. The last remaining `Vec`-carry
    /// axis still unlifted at the time of this lift —
    /// [`crate::UpgradeFromEntry::instructions`]
    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
    /// list) — inherits this accessor's discipline as future
    /// compounding runs migrate its consumers onto the shared slice-
    /// return shape. Second `&[T]`-return accessor on the top-level
    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
    /// `:contratos` are the two `Vec` fields on the outer typed
    /// composition view — `:politicas`, `:placement`, `:entrada` are
    /// scalar/option-shaped and already route through their per-slot
    /// accessor families). Named `contratos()` to match the storage
    /// field's name verbatim and the tatara-lisp author-surface term
    /// (`:contratos`) the field's own docstring already carries; the
    /// accessor's identity maps onto the canonical MESH-COMPOSITION
    /// §III.1 vocabulary the slot's docstring already reaches for.
    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
    /// every downstream consumer of the contract list treats it as a
    /// read-only sequence — the slice-view is the narrowest borrow
    /// that supports every present + roadmapped consumer
    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
    /// backing `Vec`'s grow/push/reserve surface that no consumer of
    /// the typed view reaches for (the storage-side `Vec` remains
    /// reachable through the `pub contratos` field for the mutation-
    /// carrying serde round-trip and per-test fixture-mutation paths).
    #[must_use]
    pub fn contratos(&self) -> &[WitContract] {
        self.contratos.as_slice()
    }

    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
    /// per-Aplicacao mesh-policy composite-reference accessor every
    /// per-Aplicacao policy-block reader keys off — returns the author-
    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
    /// reference over the same backing storage the raw `&self.politicas`
    /// field access borrows from.
    ///
    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
    /// mesh-policy composite — the load-bearing container of every
    /// mesh-level operational-policy axis every downstream mesh-artifact
    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
    /// mesh-policy overlay is the single typed surface a
    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
    /// from). Every per-`:politicas` axis threads through a lifted
    /// per-slot accessor on the [`MeshPolicy`] type: the
    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
    /// accessor. Every downstream consumer that reaches for a policy
    /// axis first passes through this outer accessor onto the composite
    /// and then dispatches onto the per-axis accessor — the two-level
    /// dispatch means every per-`:politicas` reader now routes through
    /// a typed dispatch on the substrate primitive at both altitudes.
    ///
    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
    /// accessed inline at four production sites — the
    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
    /// &self.politicas;` traversal seed (which drives every per-axis
    /// zero-floor + upper-cap + canonical-form bracket dispatch through
    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
    /// `p.rate_limit()` on the axis-level lifted accessors), the
    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
    /// chain (which drives every per-`(:de, :para)` CNP
    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
    /// timeout + retry overlay emitter's paired
    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
    /// open-coded outer-field accesses that expressed no compile-time
    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
    /// future extension of the `:politicas` outer axis to a richer
    /// author surface (a per-cluster policy overlay the operator pins
    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
    /// §V federation roadmap acknowledges, a per-tenant policy-alias
    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
    /// resolves per-CR at admission time, a per-Aplicacao dynamic
    /// policy-composite derivation the future adaptive-placement engine
    /// computes from a per-cluster load-topology reader, a promotion of
    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
    /// partition once virtual-actor-style dynamic-mesh-policy
    /// composition comes into typed scope) would have had to be threaded
    /// through all four open-coded copies in lockstep or one consumer
    /// would silently disagree with the peers on which mesh-policy
    /// composite a given Aplicacao resolves to — the validator's
    /// per-axis bracket-dispatch seed reading the raw slot while the
    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
    /// would silently split the build-time policy-shape gate from the
    /// runtime CNP-emission gate, a four-consumer split at the
    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
    /// the source `caixa.lisp` with no field naming the policy-drift
    /// root cause. Lifting the resolution rule to a typed method on the
    /// substrate primitive means every downstream consumer of the
    /// Aplicacao's per-`:politicas` mesh-policy composite surface
    /// reaches for exactly one typed dispatch — the resolver's accept-
    /// set migrates as a unit on any future axis addition.
    ///
    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
    /// close the two `Vec`-carry axes on the outer typed composition
    /// view; the outer `:politicas` composite-reference axis is the
    /// natural pair to the paired outer `Vec`-carry accessors on the
    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
    /// emitter reads all four axes as one unit (graph nodes + graph
    /// edges + mesh policy + placement pool). Peer to the same
    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
    /// slot: every M2 `SupervisorSpec`-scoped composite reader
    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
    /// `restart_window`, `children`) already routes through the M2
    /// `SupervisorSpec` accessor family — this lift extends the same
    /// "one typed dispatch on the substrate primitive at the outer
    /// composition altitude" discipline to the M3 mesh-slot
    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
    /// remaining peer outer-composite axes still unlifted at the time
    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
    /// inherit this accessor's discipline as future compounding runs
    /// migrate their consumers onto the shared reference-return shape.
    /// Named `politicas()` to match the storage field's name verbatim
    /// and the tatara-lisp author-surface term (`:politicas`) the
    /// field's own docstring already carries; the accessor's identity
    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
    /// slot's docstring already reaches for. Returns `&MeshPolicy`
    /// (not the owning composite by copy or clone) because every
    /// downstream consumer of the mesh-policy composite treats it as a
    /// read-only per-axis dispatch source — the reference-view is the
    /// narrowest borrow that supports every present + roadmapped
    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
    /// emptiness probe) without cloning the composite through every
    /// consumer's fast path.
    #[must_use]
    pub fn politicas(&self) -> &MeshPolicy {
        &self.politicas
    }

    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
    /// per-Aplicacao distribution-composite composite-reference accessor
    /// every per-Aplicacao placement-block reader keys off — returns the
    /// author-declared `:placement` composite verbatim as a `&Placement`
    /// reference over the same backing storage the raw `&self.placement`
    /// field access borrows from.
    ///
    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
    /// distribution composite — the load-bearing container of every
    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
    /// `:affinity` hint). Every per-`:placement` axis threads through a
    /// lifted per-slot accessor on the [`Placement`] type: the
    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
    /// per-cluster distribution-target slice-return accessor, the
    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
    /// optional-scalar accessor, and the [`Placement::shard_key`]
    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
    /// downstream consumer that reaches for a placement axis first passes
    /// through this outer accessor onto the composite and then dispatches
    /// onto the per-axis accessor — the two-level dispatch means every
    /// per-`:placement` reader now routes through a typed dispatch on the
    /// substrate primitive at both altitudes.
    ///
    /// Prior to this lift the `.placement` `Placement` composite was
    /// accessed inline at three production sites — the
    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
    /// cluster `.clusters()` validate-loop traversal head, the per-
    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
    /// paired with the shape-gate cascade's `.shard_key()` /
    /// `.estrategia()` diagnostic-carry pair), the
    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
    /// per-entry placement-block emitter's outer
    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
    /// seed (which fans onto every per-cluster `programs[]` entry as a
    /// self-describing distribution overlay the aggregator filters by),
    /// and the `feira app graph` per-Aplicacao print line's paired
    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
    /// then-inner-accessor chains (which drive the human-readable
    /// distribution summary of the typed Aplicacao view) — three open-
    /// coded outer-field accesses that expressed no compile-time link
    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
    /// extension of the `:placement` outer axis to a richer author surface
    /// (a per-cluster placement overlay the operator pins through a
    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
    /// federation roadmap acknowledges, a per-tenant placement-alias
    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
    /// resolves per-CR at admission time, a per-Aplicacao dynamic
    /// placement-composite derivation the future M5 adaptive-placement
    /// engine computes from a per-cluster load-topology reader, a
    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
    /// partition once Orleans-style virtual-actor dynamic-placement comes
    /// into typed scope) would have had to be threaded through all three
    /// open-coded copies in lockstep or one consumer would silently
    /// disagree with the peers on which placement composite a given
    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
    /// seed reading the raw slot while the peer
    /// `programs_for_aplicacao` emitter read an operator-resolved slot
    /// would silently split the build-time distribution-shape gate from
    /// the runtime programs.yaml distribution-annotation gate, a three-
    /// consumer split at the validator, the programs.yaml emitter, and
    /// the `feira app graph` printer far from the source `caixa.lisp`
    /// with no field naming the placement-drift root cause. Lifting the
    /// resolution rule to a typed method on the substrate primitive
    /// means every downstream consumer of the Aplicacao's per-
    /// `:placement` distribution composite surface reaches for exactly
    /// one typed dispatch — the resolver's accept-set migrates as a unit
    /// on any future axis addition.
    ///
    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
    /// `AplicacaoSpec` type itself — sibling to the seed
    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
    /// composite-reference accessor on the peer per-`:politicas` outer-
    /// composite axis, and to the paired slice-return accessors
    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
    /// the two `Vec`-carry axes on the outer typed composition view; the
    /// outer `:placement` composite-reference axis is the natural pair
    /// to the peer `:politicas` composite-reference axis on the two
    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
    /// how-to-run policy overlay, `:placement` carries the where-to-run
    /// distribution composite — every whole-Aplicacao mesh-artifact
    /// emitter reads both as one unit). Same "one typed dispatch on the
    /// substrate primitive, thin projections at each consumer"
    /// discipline the peer per-`:politicas` composite-reference axis
    /// already routes through. The one remaining outer-composite axis
    /// still unlifted at the time of this lift —
    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
    /// external-gateway composite) — inherits this accessor's discipline
    /// as the next compounding run migrates its consumers onto the shared
    /// reference-return shape, closing the outer-composite altitude on
    /// every M3 mesh-slot axis. Named `placement()` to match the storage
    /// field's name verbatim and the tatara-lisp author-surface term
    /// (`:placement`) the field's own docstring already carries; the
    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
    /// vocabulary the slot's docstring already reaches for. Returns
    /// `&Placement` (not the owning composite by copy or clone) because
    /// every downstream consumer of the placement composite treats it as
    /// a read-only per-axis dispatch source — the reference-view is the
    /// narrowest borrow that supports every present + roadmapped consumer
    /// (per-axis accessor dispatch, serde composite-serialization) without
    /// cloning the composite through every consumer's fast path.
    #[must_use]
    pub fn placement(&self) -> &Placement {
        &self.placement
    }

    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
    /// per-Aplicacao external-gateway composite optional-composite-
    /// reference accessor every per-Aplicacao gateway-block reader
    /// keys off — returns the author-declared `:entrada` composite
    /// verbatim as an `Option<&Entrada>` reference over the same
    /// backing storage the raw `self.entrada.as_ref()` field access
    /// borrows from, with `None` naming the internal-only mesh shape
    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
    /// gateway_routes emitter treats as "emit nothing" and the peer
    /// `feira app graph` printer treats as "internal-only mesh").
    ///
    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
    /// external-gateway composite — the load-bearing container of
    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
    /// hostname axis, §III.4 for the `:para` destination-Servico
    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
    /// axis threads through a lifted per-slot accessor on the
    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
    /// Gateway-API `Listener.hostname` scalar accessor, the paired
    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
    /// backendRefs destination-Servico scalar accessor, the
    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
    /// scalar accessor. Every downstream consumer that reaches for
    /// an entrada axis first passes through this outer accessor onto
    /// the composite and then dispatches onto the per-axis accessor
    /// — the two-level dispatch means every per-`:entrada` reader
    /// now routes through a typed dispatch on the substrate primitive
    /// at both altitudes.
    ///
    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
    /// was accessed inline at four production sites — the
    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
    /// (which drives every per-axis refusal on the composite: the
    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
    /// `EntradaMemberMissing` membership lookup against the
    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
    /// per-path shape gate on each entry of `e.paths`), the
    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
    /// composite-projection seed (which drives the destination-
    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
    /// backendRefs port emitter fans on), the
    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
    /// early-return seed (which drives the "no `:entrada` ⇒ no
    /// external artifacts" partition on the whole-Aplicacao Gateway-
    /// API emitter's fan-out), and the `feira app graph` per-
    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
    /// external-gateway summary emitter (which drives the human-
    /// readable `entrada: host → para (paths=…, port=…)` /
    /// `entrada: (internal-only mesh)` partition on the typed
    /// Aplicacao view) — four open-coded outer-field accesses that
    /// expressed no compile-time link back to the typed slot at the
    /// [`AplicacaoSpec`] altitude. A future extension of the
    /// `:entrada` outer axis to a richer author surface (a
    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
    /// at admission time so an Aplicacao can expose a public-web +
    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
    /// operator can pin a per-cluster hostname override without
    /// re-authoring the `caixa.lisp`, a promotion of the plain
    /// `Option<Entrada>` to a richer `{single, multi}` partition once
    /// the multi-`:entrada` roadmap lands) would have had to be
    /// threaded through all four open-coded copies in lockstep or one
    /// consumer would silently disagree with the peers on which
    /// entrada composite a given Aplicacao resolves to — the
    /// validator's per-axis bracket-dispatch seed reading the raw
    /// slot while the peer `gateway_routes` emitter read an
    /// operator-resolved slot would silently split the build-time
    /// gateway-shape gate from the runtime Gateway + HTTPRoute
    /// emission gate, a four-consumer split at the validator, the
    /// `port_for_destination` L4-port resolver, the `gateway_routes`
    /// emitter, and the `feira app graph` printer far from the
    /// source `caixa.lisp` with no field naming the entrada-drift
    /// root cause. Lifting the resolution rule to a typed method on
    /// the substrate primitive means every downstream consumer of
    /// the Aplicacao's per-`:entrada` external-gateway composite
    /// surface reaches for exactly one typed dispatch — the
    /// resolver's accept-set migrates as a unit on any future axis
    /// addition.
    ///
    /// Third and final `&Composite`-return accessor on the top-level
    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
    /// unlifted outer-composite axis on the outer typed composition
    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
    /// accessor on the per-`:politicas` outer-composite axis and to
    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
    /// distribution-composite composite-reference accessor on the
    /// per-`:placement` outer-composite axis; extends the outer-
    /// composite reference-return discipline the two peers already
    /// route through onto the last unlifted per-`AplicacaoSpec`
    /// outer-composite axis. The `:entrada` outer-composite axis is
    /// the natural pair to the two peer outer-composite axes on the
    /// three operationally-symmetric M3 mesh-slot outer composites
    /// (`:politicas` carries the how-to-run policy overlay,
    /// `:placement` carries the where-to-run distribution composite,
    /// `:entrada` carries the who-can-reach-it external-gateway
    /// composite — every whole-Aplicacao mesh-artifact emitter reads
    /// all three as one unit). Same "one typed dispatch on the
    /// substrate primitive, thin projections at each consumer"
    /// discipline the peer outer-composite axes already route through.
    /// Named `entrada()` to match the storage field's name verbatim
    /// and the tatara-lisp author-surface term (`:entrada`) the
    /// field's own docstring already carries; the accessor's
    /// identity maps onto the canonical MESH-COMPOSITION §III.4
    /// vocabulary the slot's docstring already reaches for. Returns
    /// `Option<&Entrada>` (not the owning composite by copy or
    /// clone) because every downstream consumer of the entrada
    /// composite treats it as a read-only per-axis dispatch source
    /// — the reference-view is the narrowest borrow that supports
    /// every present + roadmapped consumer (per-axis accessor
    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
    /// port-fallback projection, early-return partition on the
    /// `None` arm) without cloning the composite through every
    /// consumer's fast path. The `Option` half of the return-type
    /// preserves the load-bearing "author-omitted `:entrada` ⇒
    /// internal-only mesh" partition (not a default composite the
    /// downstream must reject on emptiness) — the accessor projects
    /// the raw `Option<Entrada>` slot's presence bit through the
    /// reference-return unchanged.
    #[must_use]
    pub fn entrada(&self) -> Option<&Entrada> {
        self.entrada.as_ref()
    }

    /// Validate the typed shape:
    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
    ///     and a non-empty `:versao`; no two entries share the same
    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
    ///     not a multiset)
    ///   - every `:contratos` :de + :para must be in `:membros`
    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
    ///     contract is an inter-Servico edge, so a Servico contracting
    ///     with itself is a build error under every WIT shape
    ///     (MESH-COMPOSITION §III.1)
    ///   - no two `:contratos` entries agree on
    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
    ///     edges are a set, not a multiset (peer of the `:membros` /
    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
    ///   - `:entrada :para` must be in `:membros`
    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
    ///     `:placement Replicated`/`SingleNode` must NOT declare
    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
    ///     between strategy and shard-key is symmetric: every validated
    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
    ///     Sharded`
    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
    ///     the shard pool (MESH-COMPOSITION §III.1)
    ///   - every `:clusters` entry is non-empty and unique
    ///   - `:placement :affinity`, when set, is non-empty
    ///   - the synchronous-`:contratos` subgraph is acyclic
    ///     (MESH-COMPOSITION §III.3)
    ///   - every declared `:politicas` value is operationally meaningful
    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
    ///     omit the field instead to express "no policy on this axis")
    pub fn validate(&self) -> Result<(), AplicacaoError> {
        self.validate_membros()?;
        let names: std::collections::HashSet<&str> =
            self.membros().iter().map(Membro::nome).collect();

        // Identity key for the typed-edge duplicate gate below: every
        // field that distinguishes one contract from another. Two
        // entries that agree on all six are *the same edge declared
        // twice*, the typed-graph analogue of duplicate `:membros` /
        // `:placement :clusters` / `:entrada :paths` entries (which
        // are already build errors at this layer). Rejecting it at the
        // validate gate closes a renderer-side footgun: caixa-mesh's
        // `cilium_network_policies` keys each emitted policy by
        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
        // (de, para) and identical payload would land as two K8s
        // objects with colliding `metadata.name`, rejected at apply
        // time far from the source caixa.lisp.
        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
            std::collections::HashSet::new();
        for c in self.contratos() {
            // Per-axis value-shape gate on every `:contratos` name
            // reference, before any graph-membership lookup. Empty +
            // DNS-1123-malformed `:de`/`:para` values silently fell
            // through to `ContratoMemberMissing` at the lookup arm
            // because every `:membros :caixa` is shape-validated
            // (3f9d7a0), so the `names` set structurally cannot contain
            // an empty / malformed string and the membership-lookup
            // diagnostic always misframed the root cause as
            // "this caixa is not in `:membros`". The shape gate runs
            // ahead of the lookup so structurally-impossible-to-match
            // inputs route through the narrower self-locating
            // diagnostic, preserving the legitimate "well-shaped
            // phantom reference" arm. `:de` runs before `:para` per
            // the canonical edge-direction order the existing
            // membership lookup, self-edge check, target dispatch,
            // and diagnostic strings already use.
            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
            // + the paired [`AplicacaoError::ContratoMemberMissing`]
            // diagnostic's `caixa:` carrier through the lifted
            // [`WitContract::source`] / [`WitContract::destination`]
            // scalar accessors rather than the raw `&c.de` / `&c.para`
            // `&String`-borrow arg site + the raw `c.de.clone()` /
            // `c.para.clone()` field-access `String`-carry sites — the
            // last unlifted per-`:contratos` raw-field-access sites in
            // the M3 mesh-slot validator's per-edge per-arm shape-gate
            // arg + phantom-name diagnostic wrap-envelope emit surface.
            // `c.source()` is byte-identical to `&c.de` (pinned by the
            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
            // + `wit_contract_source_borrows_from_de_storage` accessor
            // tests) and `c.destination()` is byte-identical to `&c.para`
            // (pinned by the sibling
            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
            // + `wit_contract_destination_borrows_from_para_storage`
            // accessor tests) — so a future rebrand of either underlying
            // storage flows through the accessor's one body without a
            // coordinated per-consumer rewrite across the M3 mesh
            // validator's per-edge shape-gate + phantom-name refusal
            // arms. Peer of the sibling per-`:contratos` self-loop
            // arm's `.source().to_string()` / `.world_ref().to_string()`
            // `String`-carry sites the earlier convergence lifted onto
            // the same accessor pair.
            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
            if !names.contains(c.source()) {
                return Err(AplicacaoError::ContratoMemberMissing {
                    caixa: c.source().to_string(),
                });
            }
            if !names.contains(c.destination()) {
                return Err(AplicacaoError::ContratoMemberMissing {
                    caixa: c.destination().to_string(),
                });
            }
            // A `:contratos` entry is an *inter*-Servico contract
            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
            // typed edge between two distinct graph nodes. An edge whose
            // `:de` equals its `:para` is a Servico contracting with
            // itself — a degenerate edge under every WIT shape. The
            // synchronous shapes were caught only incidentally, and with
            // a misleading diagnostic: `detect_sync_cycles` reported
            // `cart → cart` as a `ContratoCycle` whose path is
            // `["cart", "cart"]` — framing a self-edge as a multi-node
            // deadlock. The pub-sub shape slipped through entirely
            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
            // `nats:pub-sub` edge from a member to itself silently
            // validated, then rendered a `CiliumNetworkPolicy` whose
            // endpointSelector and fromEndpoints both name the same
            // program — a self-allow rule that is a no-op, since
            // intra-pod traffic never traverses the mesh). A self-edge's
            // runtime meaning is an in-process call, which doesn't go
            // through the mesh at all, so no `:contratos` edge can carry
            // it. Firing the gate before the `:wit`/`target()` shape
            // checks means the structural "this edge can't exist" error
            // precedes the narrower payload-shape diagnostics, and shape-
            // agnostically covers all four `WitTarget` arms (HTTP / Store
            // / Capability / PubSub) at one point — closing the pub-sub
            // hole and replacing the misleading cycle diagnostic in one
            // gate. Peer of the duplicate-`:contratos` / duplicate-
            // `:membros` set gates: both reject a structurally
            // ill-formed graph at the typed surface, before the renderer
            // emits a K8s object that fails or no-ops far from the source
            // caixa.lisp.
            // Route the per-`:contratos` structural self-edge probe
            // through the lifted [`WitContract::is_self_loop`] typed
            // predicate rather than the raw `c.de == c.para` field-
            // equality check — the one production consumer of the per-
            // `:contratos` caller-equals-callee endpoint-equality axis
            // now keys off exactly one typed dispatch on the substrate
            // primitive, so any future rebrand of the axis (an M4-typed-
            // caller enum whose identity comparison rule the predicate
            // could route through, a per-cluster caller/callee-alias
            // table the M4 CR materializer resolves per-CR before the
            // equality probe) migrates as a single caixa-core edit
            // rather than a coordinated rewrite of the gate + every
            // downstream self-edge consumer. Peer of the sibling
            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
            // [`WitContract::is_store`] shape-predicate routing on the
            // `:wit` world-ref axis, extended onto the per-edge
            // endpoint-equality axis.
            //
            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
            // diagnostic's `caixa:` / `wit:` carriers through the
            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
            // scalar accessors rather than the raw `c.de.clone()` /
            // `c.wit.clone()` field-access `String`-carry sites — the
            // last unlifted per-`:contratos` raw-field-access
            // `.clone()` sites in the M3 mesh-slot validator's self-
            // edge refusal arm. `.source().to_string()` is byte-
            // identical to `.de.clone()` (pinned by the sibling
            // `source_returns_de_byte_equal_across_permutations` accessor
            // test), and `.world_ref().to_string()` is byte-identical
            // to `.wit.clone()` (pinned by the sibling
            // `world_ref_returns_wit_byte_equal_across_permutations`
            // accessor test) — so a future rebrand of either underlying
            // storage flows through the accessor's one body without a
            // coordinated per-consumer rewrite across the M3 mesh
            // validator.
            if c.is_self_loop() {
                return Err(AplicacaoError::ContratoSelfLoop {
                    caixa: c.source().to_string(),
                    wit: c.world_ref().to_string(),
                });
            }
            if c.world_ref().is_empty() {
                let (de, para) = c.edge_pair();
                return Err(AplicacaoError::EmptyWit { de, para });
            }
            // Shape ↔ target consistency — surfaces "HTTP wit without
            // :endpoint", "NATS wit with :endpoint set", etc. as named
            // build errors instead of silent renderer drops. Threaded
            // through the duplicate-edge diagnostic below (via
            // [`WitTarget::label`]) so the "which typed target arm did
            // the duplicate carry" question is answered by the typed
            // enum's variant discriminator, not by re-probing the raw
            // `Option<String>` payload fields.
            let target_view = c.target()?;
            // Contract identity: (de, para, wit, endpoint, subject, slot).
            // Two contracts that match on all six are the same typed edge
            // declared twice — author error, not a legitimate variant of
            // "same caller-callee pair, different payload" (e.g.
            // cart→catalog at /products vs /search), which keeps distinct
            // identity keys via the differing endpoint payloads.
            //
            // Route the six-axis dedup key through the lifted
            // [`WitContract::identity`] composite-projection accessor
            // rather than the inline six-tuple builder — the two
            // substrate primitives on the per-`:contratos` identity axis
            // (the [`ContratoIdentity`] type alias's six axes, this
            // dedup-key's six tuple arms) now migrate as a unit on any
            // future axis addition. Peer of the sibling per-`:contratos`
            // composite-projection [`WitContract::edge_pair`] /
            // [`WitContract::edge_triple`] accessors on the
            // caller-callee / caller-callee-wit prefix axes; extends
            // the discipline onto the full-identity axis that carries
            // the three payload-shape arms too.
            let key = c.identity();
            crate::render::insert_first_seen(&mut seen_contracts, key, || {
                // Route the per-`:contratos` duplicate-gate diagnostic's
                // `(de, para, wit)` triple through the lifted
                // [`WitContract::edge_triple`] typed accessor rather
                // than pairing `edge_pair()` for the `(de, para)` prefix
                // with a raw `c.wit.clone()` for the `wit:` tail — the
                // paired-with-raw-field-access shape was the last
                // per-`:contratos` diagnostic constructor bypassing the
                // substrate-primitive composite projection, sibling to
                // the eight [`AplicacaoError::Contrato*`] triple-
                // carrying constructors [`WitContract::target`]'s edge
                // closure feeds through the same accessor.
                let (de, para, wit) = c.edge_triple();
                AplicacaoError::ContratoDuplicate {
                    de,
                    para,
                    wit,
                    target: target_view.label(),
                }
            })?;
        }

        // Cycles in the synchronous-edge subgraph are build errors
        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
        // are "acyclic by construction" because the publisher fires
        // and forgets, so no caller blocks on a downstream that loops
        // back to it.
        self.detect_sync_cycles()?;

        if let Some(e) = self.entrada() {
            // Route the per-`:entrada` composite-reference read
            // through the lifted [`AplicacaoSpec::entrada`] accessor
            // rather than the raw `&self.entrada` field access — the
            // shape-and-membership gate's traversal head is now the
            // canonical read-side surface every per-Aplicacao entrada
            // consumer routes through, closing the fourth of four
            // open-coded outer-field accesses on the per-`:entrada`
            // outer-composite axis.
            //
            // Shape gate on `:entrada :para` runs ahead of the
            // membership lookup. Every `:membros :caixa` past
            // `validate_membro_caixa` is a valid DNS-1123 label
            // (3f9d7a0), so the `names` set structurally cannot
            // contain an empty / malformed string and the membership-
            // lookup diagnostic always misframed the root cause as
            // "this caixa is not in `:membros`". The shape gate
            // routes structurally-impossible-to-match inputs through
            // the narrower self-locating diagnostic, preserving the
            // legitimate "well-shaped phantom reference" arm — the
            // same trajectory the peer `:membros :caixa` (3f9d7a0),
            // `:placement :clusters` (6c8c00b), and `:contratos :de`
            // / `:para` (8d5af6b) axes already follow. This closes
            // the fourth and last Aplicacao-level Servico-name
            // reference axis on the canonical DNS-1123 floor.
            // Route the per-`:entrada :para` byte-string reads through
            // the lifted [`Entrada::destination`] accessor rather than
            // the raw `e.para` field access — the three
            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
            // (shape-gate `validate_entrada_para` arg, membership
            // lookup, `EntradaMemberMissing` diagnostic carry) now key
            // off exactly one typed dispatch on the substrate
            // primitive, closing the last unlifted per-`:entrada :para`
            // raw-field-access axis on the M3 mesh-slot validator.
            // The `.destination().to_string()` at the diagnostic site
            // is byte-identical to `.para.clone()` — pinned by the
            // sibling `destination_returns_entrada_para_byte_equal` +
            // `destination_borrows_from_entrada_para_storage` accessor
            // tests — so a future rebrand of the underlying `:para`
            // storage (a lift from `String` to a typed
            // `ServicoName(String)` newtype, a per-Aplicacao interning
            // arena the M4 CR materializer authors, a
            // `smol_str::SmolStr` inline-buffer swap) flows through
            // the accessor's one body without a coordinated
            // per-consumer rewrite across the M3 mesh validator.
            validate_entrada_para(e.destination())?;
            if !names.contains(e.destination()) {
                return Err(AplicacaoError::EntradaMemberMissing {
                    para: e.destination().to_string(),
                });
            }
            // Route the per-`:entrada :host` byte-string reads through
            // the lifted [`Entrada::hostname`] accessor rather than
            // the raw `e.host` field access — the emptiness gate and
            // the shape-gate `validate_entrada_host` arg now key off
            // exactly one typed dispatch on the substrate primitive,
            // closing the last unlifted per-`:entrada :host` raw-
            // field-access axis on the M3 mesh-slot validator. Peer
            // of the sibling per-`:entrada :para` convergence above
            // and pinned by the existing
            // `hostname_returns_entrada_host_byte_equal` +
            // `hostnames_returns_singleton_of_hostname_accessor`
            // accessor tests, so any future
            // Gateway-API-shaped host renormalization (a wildcard-
            // label lift, a trailing-`.` FQDN substitution, an IDNA
            // Punycode round-trip the SNI fan-out overlay authors)
            // flows through the accessor's one body without a
            // coordinated per-consumer rewrite across the M3 mesh
            // validator.
            if e.hostname().is_empty() {
                return Err(AplicacaoError::EmptyEntradaHost);
            }
            // The `:host` lands verbatim as a K8s Gateway API v1
            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
            // both apiserver-validated against the same restrictive
            // pattern: lowercase RFC 1123 DNS subdomain, optional
            // single leading wildcard label (`*.`), max length 253,
            // per-label max length 63, no IP literals, no scheme,
            // no port. Until this gate landed `validate()` only
            // refused the empty string (`EmptyEntradaHost`); a
            // structurally invalid hostname (`"https://example.com"`,
            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
            // `"_underscored.example.com"`, `"FOO.example.com"`,
            // `"checkout.quero.cloud."`) silently passed validate
            // and the apiserver `field is invalid` error surfaced at
            // `kubectl apply` time, far from the source caixa.lisp.
            // Lifting the gate to caixa-build time mirrors the
            // `:entrada :paths` value-shape trajectory (eb3456d) and
            // closes the last unstructured `:entrada` axis.
            validate_entrada_host(e.hostname())?;
            // Structural-floor gate on `:entrada :port`: every
            // validated `Entrada::port` past this gate lies in
            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
            // type-inferred ceiling closes the top edge, so no companion
            // upper-cap arm is needed here — unlike the peer capped-
            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
            // `require_positive_bounded_u32` bracket covers both edges).
            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
            // accept-set-floor const rather than the prior inline
            // `if e.port == 0` byte-check so a future rebrand of the
            // accept-set floor (a hypothetical unprivileged-only
            // migration lifting the floor to `1024`, a per-cluster
            // scoping the operator pins through a future
            // `:placement :port-floor` slot as the M4 typed-slot
            // trajectory adds it, the future
            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
            // per-Aplicacao gateway resolver reaching for the same
            // floor) is a one-line edit on the canonical
            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
            // rewrite across the emit site + the pin test + every
            // future per-target renderer the substrate adds.
            if e.port() < SERVICO_PORT_MIN {
                return Err(AplicacaoError::EntradaPortZero);
            }
            // Each `:entrada :paths` entry becomes a K8s Gateway API
            // HTTPRoute `matches[].path.value`. The Gateway API rejects
            // values that don't start with `/` for `type: PathPrefix`,
            // and an empty value is meaningless. Surface those as build
            // errors (MESH-COMPOSITION §III.3) rather than apply-time
            // failures. Empty `:paths` itself is fine — caixa-mesh
            // falls back to a single `/` catch-all.
            let mut seen = std::collections::HashSet::new();
            // Route the per-entry value-shape gate's traversal head
            // through the lifted [`Entrada::paths`] slice accessor
            // rather than the raw `&e.paths` field access — the
            // per-Aplicacao `:entrada :paths` validate loop now keys
            // off the canonical raw-slot surface every downstream
            // per-`:entrada` path-list consumer (the sibling
            // [`Entrada::resolved_paths`] fallback-applying resolver
            // internal reads, `feira app graph`'s per-Aplicacao entrada
            // summary line's `{:?}` Debug print) routes through, so any
            // future rebrand on the typed slot's raw-slot reader lands
            // at exactly one place. Same convergence discipline as the
            // sibling [`Placement::clusters`] (a6e18d7) reader-site
            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
            // axis.
            for p in e.paths() {
                if p.is_empty() {
                    return Err(AplicacaoError::EntradaPathEmpty);
                }
                if !p.starts_with('/') {
                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
                }
                // Per-entry value-shape gate: the path lands verbatim
                // as a K8s Gateway API HTTPRoute `matches[].path.value`
                // (caixa-mesh/src/lib.rs:498), apiserver-validated
                // against `maxLength: 1024` + the Gateway API webhook's
                // path-grammar rules (no `//`, no `/./`, no `/../`, no
                // query/fragment separators, no whitespace, no control
                // characters, no non-ASCII bytes). Until this gate
                // landed `validate` only refused the empty string and
                // missing-leading-slash (eb3456d); a structurally
                // invalid path (`"/api?q=1"`, `"/api#frag"`,
                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
                // 1025-byte URL-shaped slug) silently passed validate
                // and the failure surfaced at `kubectl apply` time as
                // a Gateway API webhook rejection, far from the source
                // caixa.lisp, with no field naming the offending
                // `:paths` entry. Lifting the gate to caixa-build time
                // mirrors the `:entrada :host` value-shape trajectory
                // (c7d05ec) on the sibling axis — every author surface
                // that emits a Gateway API field now matches the
                // apiserver's accepted set at validate time.
                validate_entrada_path(p)?;
                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
                })?;
            }
        }

        self.validate_placement()?;

        self.validate_politicas()?;

        Ok(())
    }

    /// Reject `:membros` values that are operationally meaningless. The
    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
    /// every entry names a Servico that participates in the Aplicacao,
    /// and the rendered programs.yaml fan-out emits one entry per
    /// `:membros`. Three authoring footguns are closed here:
    ///
    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
    ///     a `programs:` entry whose `name:` is the empty string, which
    ///     downstream `lareira-fleet-programs` rejects at template time
    ///     with a non-localized error;
    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
    ///     an empty semver constraint, so the failure surfaces far from
    ///     the source caixa.lisp;
    ///   - duplicate `:caixa` names — two entries with the same name
    ///     produce duplicate programs.yaml entries (one silently
    ///     overwrites the other in the cluster's HelmRelease values), and
    ///     contract membership lookups against `:contratos` collapse the
    ///     two onto one node, masking authoring mistakes.
    ///
    /// Same value-shape discipline as `:placement :clusters` (where empty
    /// + duplicate cluster names are rejected) and `:entrada :paths`
    /// (where empty + duplicate path entries are rejected). Lifting these
    /// invariants to the typed surface mirrors the MESH-COMPOSITION
    /// §III.3 promise that the `:membros` set — the load-bearing identity
    /// of the application graph — is well-formed by construction.
    fn validate_membros(&self) -> Result<(), AplicacaoError> {
        if self.membros().is_empty() {
            return Err(AplicacaoError::NoMembros);
        }
        let mut seen = std::collections::HashSet::new();
        for m in self.membros() {
            // Route the `MembroCaixaEmpty` refusal-arm's per-member
            // empty-`:caixa` shape-gate through the typed
            // [`Membro::nome`] accessor rather than the raw `.caixa`
            // field access — the last un-lifted `.caixa` production-
            // code read site on the per-`:membros` member-caixa `:nome`
            // axis, sibling to the six caixa-core validator read sites
            // (member-set collector, per-member value-shape gate,
            // duplicate dedup key, cycle-detector adjacency-map seed,
            // self-loop gate) the 4a32abf lift already routed through
            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
            // per-`programs[]` entry-`name:` `String`-carry converge.
            // Prior to this converge the `MembroCaixaEmpty` refusal
            // arm was the solitary consumer bypassing the typed
            // dispatch — the same-loop iteration's very next call
            // `validate_membro_caixa(m.nome())` already routed through
            // the accessor, so an author landing an empty-`:caixa`
            // entry hit the accessor on the shape-gate line but
            // bypassed it on the emptiness line one line above. A
            // future extension of the `:membros :caixa` axis to a
            // richer author surface (a per-cluster alias table pinned
            // through a future `:placement`-scoped slot, a namespace-
            // qualified rewrite the M4 CR materializer applies per-CR,
            // a per-member overlay from the future `:membros
            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
            // that lands on the accessor would silently disagree
            // between the emptiness gate and every peer consumer —
            // an author-declared `:caixa "checkout"` value the
            // accessor rewrote to `""` under a future alias arm would
            // pass the raw `.is_empty()` gate here while the peer
            // `validate_membro_caixa(m.nome())` call one line below
            // (and every downstream emit-side consumer routing through
            // the accessor) tripped on the empty-value shape far from
            // this diagnostic. Pinned by the drift-detection test
            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
            // below.
            if m.nome().is_empty() {
                return Err(AplicacaoError::MembroCaixaEmpty);
            }
            // Every emitted cluster artifact's `metadata.name` derives
            // from a `:membros :caixa` value verbatim — the rendered
            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
            // the [`crate::LABEL_PROGRAM`] label value on every CNP
            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
            // `metadata.name` when the member is the `:entrada :para`
            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
            // schema enforces the DNS-1123 label rule on admission;
            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
            // mistaken-identity slug) silently passes the prior empty-/
            // duplicate-only gate and the failure surfaces at `kubectl
            // apply` time as a `metadata.name: Invalid value` rejection,
            // far from the source caixa.lisp, with no field naming the
            // offending `:membros` entry. Lifting the gate to caixa-build
            // time mirrors the `:entrada :host` value-shape trajectory
            // (c7d05ec) on the peer axis — every author surface that
            // emits a K8s name now matches the apiserver's accepted set
            // at validate time.
            validate_membro_caixa(m.nome())?;
            // The author surface for `:versao` is the same Cargo-shaped
            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
            // `"*"`) every `:deps` entry carries — and the lacre pipeline
            // resolves both axes through the same
            // [`crate::version::parse_requirement`] entry-point. The
            // shared [`crate::render::require_valid_versao_requirement`]
            // helper brackets the empty-first + parse cascade both peer
            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
            // route through, so drift between the three axes' accepted
            // requirement sets is structurally impossible and the parse-
            // side no-op the empty-first arm closes (semver's empty
            // parse yields an implicit `*`) lives in exactly one
            // predicate.
            crate::render::require_valid_versao_requirement(
                m.versao_requirement(),
                || AplicacaoError::MembroVersaoEmpty {
                    caixa: m.nome().to_string(),
                },
                |reason| AplicacaoError::MembroVersaoInvalid {
                    caixa: m.nome().to_string(),
                    versao: m.versao_requirement().to_string(),
                    reason,
                },
            )?;
            crate::render::insert_first_seen(&mut seen, m.nome(), || {
                AplicacaoError::MembroDuplicate {
                    caixa: m.nome().to_string(),
                }
            })?;
        }
        Ok(())
    }

    /// Reject `:placement` values that are operationally meaningless or
    /// internally contradictory. Each strategy variant has the same
    /// invariants on `:clusters` (non-empty list, non-empty unique
    /// entries) — the §III.1 author surface is uniform on this axis,
    /// even though the *meaning* of the list differs by strategy
    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
    /// shard pool).
    ///
    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
    /// are the same authoring footgun closed for `:politicas` zero
    /// values and `:entrada` empty paths: the field is *declared* but
    /// carries no meaning, so downstream renderers either skip it
    /// silently (cluster-fanout drops the empty entry, no diagnostic)
    /// or apply it literally and fail at admission time. Lifting both
    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
    /// violation is a build error" promise.
    ///
    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
    /// is required exactly when `:estrategia Sharded` (hash-keyed
    /// distribution, Akka cluster-sharding convention, §II.4) and
    /// refused on `:estrategia Replicated`/`SingleNode` (where no
    /// hash-keyed routing axis consumes it). The partition closes the
    /// "I think I configured sharding" footgun where an author writes
    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
    /// the typed slot's value silently vanishes at the renderer layer
    /// — every validated `Placement` past this call satisfies
    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
    fn validate_placement(&self) -> Result<(), AplicacaoError> {
        // Every strategy needs at least one named cluster: `Replicated`
        // and `SingleNode` use the list as hosting/takeover candidates
        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
        // §II.1), while `Sharded` uses it as the shard pool
        // (Akka cluster-sharding convention — §II.4). An empty list is
        // meaningless under any of the three.
        //
        // Route the paired pre-flight `.is_empty()` refusal probe and
        // the per-cluster validate loop's traversal head through the
        // lifted [`Placement::clusters`] slice-return accessor rather
        // than the raw `self.placement.clusters` field access — the
        // two production consumers of the per-`:placement` cluster-
        // pool `Vec`-carry now key off exactly one typed dispatch on
        // the substrate primitive, so any future rebrand on the axis
        // (a per-tenant cluster-pool overlay the operator pins through
        // a future `:placement :clusters-overrides` slot, a per-
        // Aplicacao dynamic cluster-pool derivation the future M5
        // adaptive-placement engine computes from `:affinity` weights)
        // migrates as a single caixa-core edit rather than a
        // coordinated rewrite of the paired arms — sibling of the
        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
        // arm migration on the per-`:supervisor` static-child-list
        // `Vec`-carry axis.
        //
        // Route the per-`:placement` outer-composite reference read
        // through the lifted [`AplicacaoSpec::placement`] outer accessor
        // rather than the raw `&self.placement` field access — the
        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
        // axis-level lifted accessor family) now routes through the
        // substrate-primitive typed dispatch at the outer composition
        // altitude, the same shape the peer caixa-mesh
        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
        // and the sibling `feira app graph` per-Aplicacao print line
        // now key off after this accessor lift.
        let p = self.placement();
        if p.clusters().is_empty() {
            return Err(AplicacaoError::PlacementWithoutClusters {
                estrategia: p.estrategia(),
            });
        }
        let mut seen = std::collections::HashSet::new();
        for c in p.clusters() {
            // Per-entry value-shape gate: the cluster name lands in
            // every K8s context / `lareira-fleet-programs` aggregator
            // filter / future M4 CR materializer's per-cluster axis
            // a validated `:clusters` entry passes through, each
            // enforcing the DNS-1123 label rule on admission. Same
            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
            // on the peer name axis — both axes' validated values
            // are guaranteed-accepted by the apiserver without
            // re-validation at any downstream renderer or admission
            // layer.
            validate_placement_cluster(c)?;
            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
            })?;
        }
        // Route the per-`:placement :affinity` per-hint value-shape
        // gate through the typed [`Placement::affinity`] accessor rather
        // than the raw `&self.placement.affinity` field access — the
        // sole open-coded field-access site on the per-`:placement`
        // M3-Adaptive-compression-hint axis the accessor lift now owns.
        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
        // the accessor's `Option<&str>` return type;
        // [`validate_placement_affinity`]'s `&str` parameter accepts
        // the narrower borrow without a re-allocation, so the routing
        // change is byte-for-byte in the pass arm and remains
        // byte-for-byte in every failure diagnostic
        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
        // String` field is populated inside
        // [`validate_placement_affinity`] via the peer `.to_string()`
        // path on the same borrowed slice). Peer of the sibling
        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
        // routing through [`Placement::shard_key`] at the caixa-core
        // site above — extends the "read `:placement` optional-scalars
        // through the typed accessor" discipline to the second
        // `Option<String>`-shape slot on the M3 mesh-slot family.
        //
        // Per-hint value-shape gate: the `:affinity` value lands
        // verbatim in the M3 Adaptive compression overlay
        // (caixa-mesh's `placement.affinity` emission) and every
        // future M4 placement-engine routing axis keying off the
        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
        // selector — each enforces the DNS-1123 label rule on
        // admission. Same typed-shape trajectory as `:placement
        // :clusters` (6c8c00b) on the sibling slot and the four
        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
        // on the Aplicacao surface to land on the canonical
        // [`crate::render::is_dns_1123_label`] floor.
        if let Some(a) = p.affinity() {
            validate_placement_affinity(a)?;
        }
        match p.estrategia() {
            // Route the `Sharded`-arm shape-gate cascade through the
            // typed [`Placement::shard_key`] accessor rather than the
            // raw `&self.placement.shard_key` field access — one of the
            // two open-coded field-access sites on the per-`:placement`
            // Akka-cluster-sharding-key axis the accessor lift now
            // owns. The `Some(k)`-bound `k` narrows from `&String` to
            // `&str` under the accessor's `Option<&str>` return type;
            // `str::is_empty` and [`validate_placement_shard_key`]'s
            // `&str` parameter both accept the narrower borrow without
            // a re-allocation.
            PlacementStrategy::Sharded => match p.shard_key() {
                None => return Err(AplicacaoError::ShardedWithoutKey),
                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
                // Per-axis value-shape gate on the Akka-cluster-sharding
                // `:shard-key` extractor expression. The shape gate runs
                // after the more self-locating `ShardedKeyEmpty` arm so
                // a `:shard-key ""` surfaces the narrower empty
                // diagnostic first; every non-empty `:shard-key` past
                // this call is guaranteed to be a printable-ASCII
                // single-token reference the future M4 Akka-style
                // cluster-sharding reconciler can hash without
                // re-validating at the runtime layer. Mirrors the
                // payload-axis shape gates on the peer `:contratos`
                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
                // 63e18a0 / c4213a4) — each lifts the runtime parser's
                // intersection-floor to a caixa-build-time gate.
                Some(k) => validate_placement_shard_key(k)?,
            },
            // `:shard-key` is the Akka-cluster-sharding axis
            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
            // across the cluster pool. `Replicated` (active-active across
            // every named cluster) and `SingleNode` (Erlang/OTP
            // distributed-app takeover/failover, §II.1) have no hash-keyed
            // routing axis to consume the slot; downstream renderers
            // (caixa-mesh's `placement.shardKey` overlay at
            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
            // sharding reconciler) ignore `:shard-key` outside the
            // `Sharded` arm by construction. Until this gate landed an
            // author who wrote `:placement (:estrategia Replicated
            // :shard-key "tenantId")` (an off-by-one strategy typo, a
            // copy-paste from a Sharded sibling caixa, the "I think I
            // configured sharding" footgun) silently passed validate and
            // the typed slot's value vanished at the renderer layer with
            // no diagnostic — the canonical "declared-but-inert" footgun
            // the empty-:affinity / empty-shard-key / zero-:politicas /
            // empty-:contratos-target gates already close on every other
            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
            // Lifting the rejection to a build-time gate closes the
            // Sharded ↔ non-Sharded partition over the typed
            // `:placement` slot: every validated `Placement` past this
            // call has `shard_key.is_some()` iff `estrategia ==
            // Sharded`, structurally — the future Akka reconciler can
            // reach for `placement.shard_key` knowing it's `Some` exactly
            // when the strategy consumes it, without re-deriving the
            // partition from inline strategy probes.
            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
                // Route the non-`Sharded`-arm declared-but-inert refusal
                // through the typed [`Placement::shard_key`] accessor —
                // the second of the two open-coded field-access sites the
                // accessor lift now owns. The `Some(k)`-bound `k` narrows
                // from `&String` to `&str`; the `AplicacaoError::
                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
                // materializes the owned `String` via `k.to_string()`
                // (peer to the sibling per-Membro `String`-carry sites
                // 4127bb6 routed through `m.nome().to_string()` /
                // `m.versao_requirement().to_string()`), so the whole
                // `Sharded` ↔ non-`Sharded` partition on the
                // `:shard-key` axis now flows through the same typed
                // dispatch as the sibling `Sharded`-arm shape gate.
                if let Some(k) = p.shard_key() {
                    return Err(AplicacaoError::ShardKeyOnNonSharded {
                        estrategia: p.estrategia(),
                        shard_key: k.to_string(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Reject `:politicas` values that are operationally meaningless.
    /// Each axis is optional — omitting it expresses "no policy on this
    /// axis". Carrying a *zero* value for a declared axis is the bug
    /// this function rejects: zero is either
    ///
    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
    ///     "every Aplicacao declares :politicas :timeout (no infinite
    ///     blocking)", or
    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
    ///     first call; a 0-rate rate-limit denies every request).
    ///
    /// Lifting these "0 means the opposite of what you think" idioms to
    /// the typed Aplicacao surface as build errors mirrors the §III.3
    /// promise that contract drift, capability leaks, and cycles are all
    /// build errors — not runtime surprises.
    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
        // Route the per-`:politicas` composite-reference read through
        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
        // than the raw `&self.politicas` field access — the per-axis
        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
        // the substrate-primitive typed dispatch at the outer
        // composition altitude AND at every per-axis altitude, matching
        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
        // timeout/retry-overlay emitters that already key off the same
        // per-axis accessor family. The four-axis fan-out is now
        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
        // `p.retries` field-access sites (co-resident with the peer
        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
        // b0e741a / 21a6c3b already lifted) now route through
        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
        // access axis on the M3 mesh-slot family.
        let p = self.politicas();
        if let Some(t) = p.timeout() {
            // Zero-floor + integer-millisecond canonical-form +
            // upper-cap bracket on the typed `:timeout` axis. See
            // [`crate::render::require_positive_canonical_bounded_duration`]
            // for the full three-arm ordering discipline (zero-floor
            // strictly precedes the canonical-form arm so
            // `Duration::ZERO` surfaces the self-locating
            // `PolicyTimeoutZero` diagnostic naming the omit-axis
            // remediation; canonical-form strictly precedes the cap
            // arm so a sub-millisecond above-cap `Duration` surfaces
            // the more fundamental round-trip-shape diagnostic first)
            // and the four peer typed-`Duration` sites that now share
            // this canonical bracket. Every validated value lies in
            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
            // granularity — the same top-and-bottom-edge discipline
            // [`POLICY_RETRIES_MAX`] and
            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
            // capped-`u32` `:politicas` axes.
            crate::render::require_positive_canonical_bounded_duration(
                t,
                POLICY_TIMEOUT_MAX,
                || AplicacaoError::PolicyTimeoutZero,
                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
            )?;
        }
        if let Some(r) = p.retries() {
            // Zero-floor + upper-cap bracket on the typed `:retries`
            // axis. See [`crate::render::require_positive_bounded_u32`]
            // for the ordering discipline (zero-floor arm strictly
            // precedes cap arm so `Some(0)` surfaces the self-locating
            // `PolicyRetriesZero` diagnostic with its omit-axis
            // remediation directly named, not the misleading
            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
            // this bracket landed the top edge ran all the way to
            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
            // Some(100_000), .. }` (or the equivalent author-surface
            // `(:retries 100000)` / `(:retries 4294967295)` typo
            // landing in the slot) silently passed validate. The
            // runtime substrate consuming the value (Envoy's
            // `retry_policy.num_retries`, the future
            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
            // policy into a thundering-herd amplification vector —
            // the caller's one request fans out to `retries`
            // server-side calls per edge per traversal, multiplying
            // load by `(retries+1)^depth` across the
            // synchronous-`:contratos` subgraph at the precise moment
            // the substrate is already failing (transient failure is
            // the trigger), exactly the failure mode AWS App Mesh's
            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
            // the sibling capped-`u32` `:politicas` axes
            // (`max_failures`, `rate_limit.rate`) and the peer capped-
            // `u32` axes in `:supervisor :max-restarts` +
            // `:limits :cpu`; all five now route through the same
            // canonical bracket helper.
            crate::render::require_positive_bounded_u32(
                r,
                POLICY_RETRIES_MAX,
                || AplicacaoError::PolicyRetriesZero,
                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
            )?;
        }
        if let Some(cb) = p.circuit_breaker() {
            // Zero-floor + upper-cap bracket on the typed
            // `:max-failures` axis. See
            // [`crate::render::require_positive_bounded_u32`] for the
            // ordering discipline (zero-floor arm strictly precedes
            // cap arm so `max_failures == 0` surfaces the
            // self-locating `PolicyBreakerZeroFailures` diagnostic
            // with its omit-axis remediation directly named, not the
            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
            // false` cap-arm miss). Until this bracket landed the top
            // edge ran all the way to `u32::MAX` and a struct-literal
            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
            // equivalent author-surface `(:max-failures 100000)` /
            // `(:max-failures 4294967295)` typo landing in the slot)
            // silently passed validate. The runtime substrate
            // consuming the value (Envoy's
            // `outlier_detection.consecutive_5xx`, the future
            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
            // breaker policy into a no-op — the trip threshold is
            // structurally so high that no realistic
            // failures-per-`:window` traffic shape can reach it, the
            // breaker never trips, and every typed-slot consumer
            // emits an Envoy / Cilium L7 overlay carrying a
            // protection that is structurally never enforced. The
            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
            // peer with `retries` and `rate_limit.rate` on the same
            // helper.
            crate::render::require_positive_bounded_u32(
                cb.max_failures(),
                POLICY_BREAKER_MAX_FAILURES_MAX,
                || AplicacaoError::PolicyBreakerZeroFailures,
                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
            )?;
            // Zero-floor + integer-millisecond canonical-form +
            // upper-cap bracket on the typed `:window` axis. See
            // [`crate::render::require_positive_canonical_bounded_duration`]
            // for the full three-arm ordering discipline (peer to the
            // `:timeout` site immediately above); every validated
            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
            // (1ms..=1h), integer-millisecond granularity — the same
            // top-and-bottom-edge discipline
            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
            // duration-typed `:politicas :timeout` axis.
            crate::render::require_positive_canonical_bounded_duration(
                cb.window(),
                POLICY_BREAKER_WINDOW_MAX,
                || AplicacaoError::PolicyBreakerZeroWindow,
                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
            )?;
        }
        if let Some(rl) = p.rate_limit() {
            // Zero-floor + upper-cap bracket on the typed
            // `:rate-limit` rate axis. See
            // [`crate::render::require_positive_bounded_u32`] for the
            // ordering discipline (zero-floor arm strictly precedes
            // cap arm so `rl.rate == 0` surfaces the self-locating
            // `PolicyRateLimitZero` diagnostic with its omit-axis
            // remediation directly named, not the misleading
            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
            // Until this bracket landed the top edge ran all the way
            // to `u32::MAX` and a struct-literal
            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
            // author-surface `(:rate-limit "4294967295/s")` /
            // `(:rate-limit "100000000/m")` typo landing in the slot)
            // silently passed validate. The runtime substrate
            // consuming the value (Envoy's
            // `local_rate_limit.token_bucket.max_tokens`, the future
            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
            // rate-limit policy into a no-op limiter: the bucket
            // capacity is structurally so high that no realistic
            // per-edge traffic shape can drain it, the limiter never
            // trips, and every typed-slot consumer emits a "rate
            // declared" L7 overlay carrying enforcement that is
            // structurally never reached — the canonical
            // declared-but-inert footgun the sibling
            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
            // the peer no-op-breaker shape. The bracket set is
            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
            // `max_failures` on the same helper. The rate bracket
            // strictly precedes the window-canonical gate so a
            // structurally absurd rate magnitude surfaces the more
            // fundamental amplification-shape diagnostic before the
            // narrower codec-round-trip-shape diagnostic on `:window`.
            crate::render::require_positive_bounded_u32(
                rl.rate(),
                POLICY_RATE_LIMIT_MAX,
                || AplicacaoError::PolicyRateLimitZero,
                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
            )?;
            // The `:rate-limit` author surface is the canonical
            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
            // accepts exactly the three-unit set (1s/60s/3600s) the
            // [`rate_limit_codec::render`] formatter emits the canonical
            // unit suffix for. A `RateLimit` whose `:window` is anything
            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
            // programmatically (struct literals in Rust + the typed
            // `Duration` field) but renders to a `<n>/<k>s` fragment
            // (the codec's fall-through) the parser then rejects on
            // round-trip — silently breaking the THEORY.md §V.2.7
            // render-determinism contract for any consumer that
            // serializes-then-deserializes the typed slot. Lifting the
            // canonical-window invariant to a build-time gate at
            // `validate_politicas` makes the codec's round-trip property
            // a structural property of the validated typed value:
            // every `RateLimit` past `AplicacaoSpec::validate` has a
            // window the codec round-trips losslessly, so the next
            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
            // §III.2 #3) reaches for `rate_limit.window` knowing the
            // value is in the codec's accepted set without re-validating
            // at the renderer layer. Same trajectory as c4213a4 (typed
            // WitContract endpoint/subject/slot value-shape gates) and
            // the b0c8389 :behavior + :upgrade-from script-path lifts:
            // the typed slot's valid set matches its codec's accepted
            // set, structurally.
            // Route the canonical-window shape-gate through the substrate
            // primitive [`RateLimit::canonical_unit`] rather than the free
            // module-private [`is_canonical_rate_limit_window`] predicate:
            // both projections resolve `Duration → Option<RateLimitUnit>`
            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
            // arm on the closed-set typed enum), but the accessor is the
            // typed method every downstream consumer of the validated slot
            // ([`rate_limit_codec::render`]'s canonical arm above, the
            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
            // per-`:politicas :rate-limit` admission webhook, the future
            // per-`:contratos`-edge rate-limit-override overlay
            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
            // production consumers of the canonical-unit axis (the codec
            // render and this validate gate) now key off exactly one typed
            // dispatch on the substrate primitive, so any future extension
            // to `canonical_unit` (a per-cluster canonical-window overlay
            // the operator pins through a future `:contratos :rate-limit
            // -unit-overrides` slot, a per-tenant unit-alias table the M4
            // CR materializer resolves per-CR) reaches both consumers by
            // construction rather than a coordinated rewrite of every
            // free-helper call site.
            if rl.canonical_unit().is_none() {
                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
                    window: rl.window(),
                });
            }
        }
        Ok(())
    }

    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
    /// A synchronous edge is any contract whose typed [`WitTarget`] is
    /// `Http`, `Store`, or `Capability` — the caller blocks on the
    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
    /// block on its subscribers, so they can never close a sync loop.
    ///
    /// Iterative DFS with three-coloring; the reported cycle is the
    /// path of caixa names traversed from the back-edge target around
    /// to itself, in declaration order. Adjacency lists and DFS roots
    /// are visited in `BTreeMap` key order so the diagnostic is
    /// deterministic across runs.
    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
        use std::collections::{BTreeMap, BTreeSet};

        #[derive(Clone, Copy, PartialEq, Eq)]
        enum Mark {
            White,
            Gray,
            Black,
        }

        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for m in self.membros() {
            adj.entry(m.nome()).or_default();
        }
        for c in self.contratos() {
            // target() was already called by validate(); re-running here
            // keeps detect_sync_cycles self-contained for callers that
            // reuse it (M4 per-edge policy resolver) without revalidating.
            //
            // The pub-sub-arm check routes through the lifted
            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
            // arm-discriminator predicate rather than a raw `matches!(…,
            // WitTarget::PubSub { .. })` on the variant so a future
            // rebrand on the axis (an M4 per-edge WIT registry split of
            // [`WitTarget::PubSub`] into shape-specific peers, a
            // per-consumer rename that the accept-set already carries)
            // reaches this call site through the derive rather than a
            // scattered per-arm `matches!` rewrite — same
            // `IsVariant`-derived-arm-discriminator discipline the
            // peer closed-set typed enums ([`crate::CaixaKind`] via
            // f5bba80, [`PlacementStrategy`] via 766ec63,
            // [`crate::supervisor::RestartStrategy`] +
            // [`crate::supervisor::RestartPolicy`],
            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
            // already route through on the substrate's other typed-enum
            // arm-discriminator axes.
            if c.target()?.is_pubsub() {
                continue;
            }
            adj.entry(c.source()).or_default().insert(c.destination());
        }

        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();

        // Stable DFS root order — BTreeMap iteration is sorted by key.
        let roots: Vec<&str> = adj.keys().copied().collect();

        // Frame: (node, sorted-neighbours snapshot, next-edge index).
        for root in roots {
            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
                continue;
            }
            let root_neighbors: Vec<&str> = adj
                .get(root)
                .map(|s| s.iter().copied().collect())
                .unwrap_or_default();
            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
            color.insert(root, Mark::Gray);

            loop {
                // Read+advance the top frame in one borrow scope so we
                // can later mutate the stack (push/pop) without holding
                // a borrow across.
                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
                    let node = top.0;
                    if top.2 >= top.1.len() {
                        (node, None)
                    } else {
                        let nxt = top.1[top.2];
                        top.2 += 1;
                        (node, Some(nxt))
                    }
                });
                let Some((node, nxt_opt)) = step else { break };
                let Some(nxt) = nxt_opt else {
                    color.insert(node, Mark::Black);
                    stack.pop();
                    continue;
                };
                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
                match nxt_color {
                    Mark::Gray => {
                        // Reconstruct the cycle from `node` back through
                        // the parent chain to `nxt`, then close.
                        let mut cycle = Vec::new();
                        let mut cur = node;
                        cycle.push(cur.to_string());
                        while cur != nxt {
                            match parent.get(cur).copied() {
                                Some(p) => {
                                    cur = p;
                                    cycle.push(cur.to_string());
                                }
                                None => break,
                            }
                        }
                        cycle.reverse();
                        cycle.push(nxt.to_string());
                        return Err(AplicacaoError::ContratoCycle { cycle });
                    }
                    Mark::White => {
                        parent.insert(nxt, node);
                        color.insert(nxt, Mark::Gray);
                        let nxt_neighbors: Vec<&str> = adj
                            .get(nxt)
                            .map(|s| s.iter().copied().collect())
                            .unwrap_or_default();
                        stack.push((nxt, nxt_neighbors, 0));
                    }
                    Mark::Black => {}
                }
            }
        }
        Ok(())
    }

    /// Substrate-canonical destination-facing TCP port every emitted
    /// per-Aplicacao artifact must key `destination`-shaped port axes
    /// off. Returns the typed `:entrada :port` scalar when this
    /// Aplicacao's `:entrada` block names `destination` under its
    /// `:para` axis (the destination Servico *is* the ingress apex, so
    /// the substrate honors the author-declared listener port
    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
    /// fallback otherwise (every non-apex destination — the internal
    /// mesh Servicos `:contratos` reach across, the future per-edge
    /// policy resolver's per-destination probe targets, the
    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
    /// L4 port resolver — reads the same substrate-canonical port floor
    /// by construction).
    ///
    /// Prior to this lift the "if :entrada matches this destination use
    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
    /// prior to this lift), with no typed method on the substrate primitive
    /// that named the rule. A future per-destination port axis addition
    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
    /// per-Servico listener ports land, a per-cluster override the operator
    /// pins through a future `:placement :default-port` slot — would have
    /// to be threaded through every renderer's inline cascade in lockstep
    /// or one consumer would silently disagree on which port a given
    /// destination Servico's ingress lands at. Lifting the rule to a
    /// typed method on the substrate primitive means the M4 CR
    /// materializer, the future per-edge policy resolver, and every
    /// downstream test-fixture navigator reach for exactly one typed
    /// dispatch — the resolver's accept-set moves as a unit on any
    /// future axis addition.
    ///
    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
    /// the typed primitive, thin projections at each consumer"
    /// discipline lifts on the sibling `:contratos` payload / `:politicas
    /// :rate-limit` unit-suffix axes; extends the discipline onto the
    /// destination-facing port-resolution axis every per-Aplicacao
    /// L4-fallback renderer consumes.
    #[must_use]
    pub fn port_for_destination(&self, destination: &str) -> u16 {
        // Route the per-`:entrada` composite-reference read through
        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
        // the raw `self.entrada.as_ref()` field access — the
        // per-destination L4-port fallback resolver's composite-
        // projection seed is now the canonical read-side surface
        // every per-Aplicacao entrada consumer routes through, peer
        // of the sibling `validate` per-`:entrada` shape-and-
        // membership gate migration on the same outer-composite
        // axis.
        // Route the per-`:entrada` apex-destination membership probe
        // through the lifted [`Entrada::destination`] accessor rather
        // than the raw `e.para == destination` field access — the last
        // un-lifted `.para` production-code read site on the per-
        // `:entrada` `:para` axis, sibling to the four caixa-core
        // consumer sites the peer 15ddd8c converge already routed
        // through the accessor (the three
        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
        // membership gate sites: the `validate_entrada_para` DNS-1123
        // shape gate, the per-`:membros` membership lookup, and the
        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
        // `entrada.para`-projection converge at
        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
        // route-name projection site). Prior to this converge the
        // `port_for_destination` resolver was the solitary consumer
        // bypassing the typed dispatch on the `.para` axis — the two
        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
        // reach through the same accessor family compose with this
        // resolver at the emit boundary via the apex-identity
        // invariant `spec.port_for_destination(entrada.destination())
        // == entrada.port` the sibling
        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
        // pin pins across four permutations. A future extension of the
        // `:entrada :para` axis to a richer author surface (a per-
        // cluster alias overlay the operator pins through a future
        // `:placement`-scoped slot, a namespace-qualified rewrite the
        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
        // §III.2 acknowledges) that lands on the accessor would silently
        // disagree between this resolver and the two `caixa-mesh` emit
        // sites — an author-declared `:para "cart"` value the accessor
        // rewrote to `"cart-v2"` under a future canary arm would leave
        // the resolver's membership arm falling through to
        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
        // `.para`) while the peer emit-site consumers landed on the
        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
        // silently disagreed on which destination port a given typed
        // `:entrada` resolves to at cluster-apply time. Pinned by the
        // drift-detection test
        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
        // below.
        self.entrada()
            .filter(|e| e.destination() == destination)
            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
    }
}

/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
/// entry may name the Aplicacao's own `:nome`.
///
/// An Aplicacao that lists itself as a member is a degenerate self-edge in
/// the typed graph — the application graph is a DAG rooted at the Aplicacao
/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
/// Servicos that compose the app; an Aplicacao is never its own constituent),
/// and the lacre pipeline's closure-resolution would otherwise be handed a
/// node that is its own parent: a one-node cycle it either rejects far from
/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
/// label + lacre closure root), a member whose `:caixa` equals the
/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
/// peer.
///
/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
/// gate `validate_upgrade_from_against_versao` and the supervision-tree
/// self-parent gate `crate::supervisor::validate_no_self_supervision`
/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
/// not a tree/mesh edge" discipline, here on the second typed-graph axis
/// (the Aplicacao :membros set; the supervision-tree :children list was the
/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
/// every validated Supervisor's children are distinct from its `:nome`,
/// every validated Aplicacao's membros are distinct from its `:nome`. The
/// transitive consequence is that `:entrada :para` and `:contratos`
/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
/// name the Aplicacao itself, without re-deriving the partition.
pub fn validate_no_self_membership(
    membros: &[Membro],
    parent_nome: &str,
) -> Result<(), AplicacaoError> {
    for m in membros {
        if m.nome() == parent_nome {
            return Err(AplicacaoError::MembroIsSelfAplicacao {
                caixa: parent_nome.to_string(),
            });
        }
    }
    Ok(())
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum AplicacaoError {
    #[error("Aplicacao must declare at least one :membros entry")]
    NoMembros,
    #[error(
        ":membros entry has empty :caixa (every member must name a Servico; \
         omit the entry instead of carrying an empty name)"
    )]
    MembroCaixaEmpty,
    #[error(
        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
         name / label value the member name lands in; use a lowercase \
         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
    )]
    MembroCaixaInvalid { caixa: String, reason: String },
    #[error(
        ":membros entry {caixa:?} has empty :versao (every member must pin a \
         semver constraint that resolves through the lacre pipeline)"
    )]
    MembroVersaoEmpty { caixa: String },
    #[error(
        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
         carries; the lacre pipeline resolves both through the same parser)"
    )]
    MembroVersaoInvalid {
        caixa: String,
        versao: String,
        reason: String,
    },
    #[error(
        ":membros entry {caixa:?} appears more than once (the graph node set \
         is a set, not a multiset; duplicate members produce duplicate \
         programs.yaml entries and ambiguous :contratos membership lookups)"
    )]
    MembroDuplicate { caixa: String },
    #[error(
        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
         never its own constituent Servico (the application graph is a DAG rooted \
         at the Aplicacao; :membros names the *other* caixas that compose the \
         app, not the app itself). Since every :nome is a globally-unique \
         substrate identity, a member naming the Aplicacao's own :nome is a \
         one-node lacre-closure recursion, not a coincidentally-named peer; \
         drop the self-referential :membros entry or rename it to the actual \
         constituent caixa."
    )]
    MembroIsSelfAplicacao { caixa: String },
    #[error(
        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
         caixa declared in :membros; omit the contract or fill the {slot} field with a \
         member name)"
    )]
    ContratoCaixaEmpty { slot: &'static str },
    #[error(
        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
         :contratos {slot} value names a member of :membros, which is itself a \
         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
         object the member name lands in — Service, Pod, identity-based Cilium \
         selector; use a lowercase alphanumeric + hyphen identifier like \
         `\"checkout\"` or `\"cart-v2\"`)"
    )]
    ContratoCaixaInvalid {
        slot: &'static str,
        caixa: String,
        reason: String,
    },
    #[error("contrato references caixa {caixa:?} not declared in :membros")]
    ContratoMemberMissing { caixa: String },
    #[error(
        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
         entry is an inter-Servico contract whose :de and :para must name distinct \
         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
         the contract, or point :para at the member it actually calls)"
    )]
    ContratoSelfLoop { caixa: String, wit: String },
    #[error("contrato {de:?} → {para:?} has empty :wit")]
    EmptyWit { de: String, para: String },
    #[error(
        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
         {reason} (the substrate dispatches `:wit` values on the canonical \
         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
         kebab-case identifier per segment)"
    )]
    ContratoWitInvalid {
        de: String,
        para: String,
        wit: String,
        reason: String,
    },
    #[error(
        ":entrada :para is empty (every :entrada must route to a caixa declared in \
         :membros; fill the :para field with a member name)"
    )]
    EntradaParaEmpty,
    #[error(
        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
         label per the K8s apiserver's `metadata.name` rule on every object the \
         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
         `\"checkout\"` or `\"cart-v2\"`)"
    )]
    EntradaParaInvalid { para: String, reason: String },
    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
    EntradaMemberMissing { para: String },
    #[error(":entrada must declare a non-empty :host")]
    EmptyEntradaHost,
    #[error(
        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
    )]
    EntradaHostInvalid { host: String, reason: String },
    #[error(":entrada :port must be in 1..=65535, got 0")]
    EntradaPortZero,
    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
    EntradaPathEmpty,
    #[error(
        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
    )]
    EntradaPathNotAbsolute { path: String },
    #[error(
        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
         value: {reason} (the K8s apiserver enforces the same shape on \
         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
         requires percent-encoding `%XX` for non-ASCII and whitespace)"
    )]
    EntradaPathInvalid { path: String, reason: String },
    #[error(":entrada :paths entry {path:?} appears more than once")]
    EntradaPathDuplicate { path: String },
    #[error(
        ":placement {estrategia} requires at least one :clusters entry \
         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
    )]
    PlacementWithoutClusters { estrategia: PlacementStrategy },
    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
    PlacementClusterEmpty,
    #[error(
        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
         identifier like `\"rio\"` or `\"mar-east\"`)"
    )]
    PlacementClusterInvalid { cluster: String, reason: String },
    #[error(":placement :clusters entry {cluster:?} appears more than once")]
    PlacementClusterDuplicate { cluster: String },
    #[error(
        ":placement :affinity must be non-empty when set (omit :affinity to express \
         `no placement hint`)"
    )]
    PlacementAffinityEmpty,
    #[error(
        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
         (placement hints land verbatim in the M3 Adaptive compression overlay's \
         `placement.affinity` field and in every future M4 placement-engine routing \
         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
         selector — both enforce the DNS-1123 label rule on admission; use a \
         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
         `\"low-latency\"`, or `\"anti-affinity\"`)"
    )]
    PlacementAffinityInvalid { affinity: String, reason: String },
    #[error(":placement Sharded requires :shard-key")]
    ShardedWithoutKey,
    #[error(
        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
         hashes every entity onto the same shard, defeating sharding entirely)"
    )]
    ShardedKeyEmpty,
    #[error(
        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
         entity-id extractor expression: {reason} (the future M4 Akka-style \
         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
         as a single-token property reference and hashes the extracted entity ID \
         to compute shard placement; use a printable-ASCII extractor expression \
         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
         `\"${{tenant}}\"`)"
    )]
    ShardKeyInvalid { shard_key: String, reason: String },
    #[error(
        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
         convention); :estrategia Replicated runs every cluster active-active and \
         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
         to :estrategia Sharded if hash-keyed routing is the intent"
    )]
    ShardKeyOnNonSharded {
        estrategia: PlacementStrategy,
        shard_key: String,
    },
    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
    ContratoMissingTarget {
        de: String,
        para: String,
        wit: String,
        expected: &'static str,
    },
    #[error(
        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
         expected `:{expected}` only"
    )]
    ContratoWrongTarget {
        de: String,
        para: String,
        wit: String,
        expected: &'static str,
    },
    #[error(
        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
         that matches no traffic and silently drops every request)"
    )]
    ContratoEndpointEmpty { de: String, para: String },
    #[error(
        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
         :entrada :paths)"
    )]
    ContratoEndpointNotAbsolute {
        de: String,
        para: String,
        endpoint: String,
    },
    #[error(
        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
         and whitespace)"
    )]
    ContratoEndpointInvalid {
        de: String,
        para: String,
        endpoint: String,
        reason: String,
    },
    #[error(
        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
         subject is a no-op subscribe; omit :subject only if the WIT world is not \
         pub-sub-shaped)"
    )]
    ContratoSubjectEmpty { de: String, para: String },
    #[error(
        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
         NATS subject: {reason} (the NATS server's subject parser enforces the \
         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
         single-token and `>` multi-token wildcards — at publish/subscribe time; \
         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
         `\"orders.*.completed\"` — a malformed subject silently drops every \
         message at runtime far from the source caixa.lisp)"
    )]
    ContratoSubjectInvalid {
        de: String,
        para: String,
        subject: String,
        reason: String,
    },
    #[error(
        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
         addresses the bucket root, defeating the per-key isolation the slot exists \
         for; omit :slot only if the WIT world is not store-shaped)"
    )]
    ContratoSlotEmpty { de: String, para: String },
    #[error(
        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
         WASI keyvalue store slot template: {reason} (the substrate enforces \
         the printable-ASCII intersection-floor every kv backend admits — \
         use a single-token path / template expression like `\"checkout/$orderId\"`, \
         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
         slot either gets rejected on write by strict backends or silently \
         corrupts the next read on permissive ones, far from the source caixa.lisp)"
    )]
    ContratoSlotInvalid {
        de: String,
        para: String,
        slot: String,
        reason: String,
    },
    #[error(
        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
        cycle.join("")
    )]
    ContratoCycle { cycle: Vec<String> },
    #[error(
        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
         than once (the typed graph edges are a set, not a multiset; duplicate \
         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
         values that K8s admission rejects far from the source caixa.lisp)"
    )]
    ContratoDuplicate {
        de: String,
        para: String,
        wit: String,
        target: String,
    },
    #[error(
        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
         express `no per-call deadline on this axis`"
    )]
    PolicyTimeoutZero,
    #[error(
        ":politicas :retries must be > 0 when set; omit :retries to express \
         `no retries on transient failure`"
    )]
    PolicyRetriesZero,
    #[error(
        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
         retry policy into a thundering-herd amplification vector on transient \
         failure (one caller request fans out to `(retries+1)^depth` server-side \
         calls across the synchronous-:contratos subgraph), exactly the failure \
         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
         or omit :retries to disable retries entirely"
    )]
    PolicyRetriesExceedsCap { retries: u32 },
    #[error(
        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
         breaker trips on the first call); omit :circuit-breaker to disable it"
    )]
    PolicyBreakerZeroFailures,
    #[error(
        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
         above this cap turns the typed breaker policy into a no-op: the trip \
         threshold is structurally so high that no realistic failures-per-:window \
         traffic shape can reach it, so the breaker never trips and every typed-slot \
         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
         omit :circuit-breaker to disable the breaker entirely"
    )]
    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
    #[error(
        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
         tracks no failures); omit :circuit-breaker to disable it"
    )]
    PolicyBreakerZeroWindow,
    #[error(
        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
         request); omit :rate-limit to disable rate limiting"
    )]
    PolicyRateLimitZero,
    #[error(
        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
         rate-limit policy into a no-op limiter: the token-bucket capacity is \
         structurally so high that no realistic per-edge traffic shape can drain it, \
         so the limiter never trips and every typed-slot consumer (the future \
         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
         to disable rate limiting entirely"
    )]
    PolicyRateLimitExceedsCap { rate: u32 },
    #[error(
        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
         three canonical windows)"
    )]
    PolicyRateLimitWindowNotCanonical { window: Duration },
    #[error(
        ":politicas :timeout must be an integer number of milliseconds — the canonical \
         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
         duration codec round-trips losslessly; got {timeout:?} which carries a \
         sub-millisecond residue that either truncates to a different `Duration` on \
         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
    )]
    PolicyTimeoutNotCanonical { timeout: Duration },
    #[error(
        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
         overlays carry a deadline so long no realistic synchronous-:contratos \
         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
         CSE invariant degenerates to enforcement only at the per-Servico \
         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
         maxes out at the same `3600s` ceiling) or omit :timeout to express \
         `no per-call deadline on this axis` (the synchronous-call deadline then \
         relies entirely on the per-Servico `:limits :wall-clock` axis)"
    )]
    PolicyTimeoutExceedsCap { timeout: Duration },
    #[error(
        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
         the shared duration codec round-trips losslessly; got {window:?} which carries a \
         sub-millisecond residue that either truncates to a different `Duration` on \
         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
    )]
    PolicyBreakerWindowNotCanonical { window: Duration },
    #[error(
        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
         is structurally so long that transient failures are never forgotten, the breaker \
         trips once and stays tripped for the lifetime of the component, and every typed-slot \
         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
         the breaker entirely"
    )]
    PolicyBreakerWindowExceedsCap { window: Duration },
}

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

    fn membro(name: &str, ver: &str) -> Membro {
        Membro {
            caixa: name.into(),
            versao: ver.into(),
        }
    }

    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
        WitContract {
            de: de.into(),
            para: para.into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some(ep.into()),
            subject: None,
            slot: None,
        }
    }

    fn three_member_spec() -> AplicacaoSpec {
        AplicacaoSpec {
            membros: vec![
                membro("catalog", "^0.1"),
                membro("cart", "^0.1"),
                membro("payment", "^0.2"),
            ],
            contratos: vec![
                contract_http("cart", "catalog", "/products/:id"),
                contract_http("cart", "payment", "/charge"),
            ],
            politicas: MeshPolicy {
                timeout: Some(Duration::from_secs(30)),
                retries: Some(3),
                mtls_required: Some(true),
                ..Default::default()
            },
            placement: Placement {
                estrategia: PlacementStrategy::Replicated,
                clusters: vec!["rio".into(), "mar".into()],
                affinity: Some("data-locality".into()),
                shard_key: None,
            },
            entrada: Some(Entrada {
                host: "checkout.quero.cloud".into(),
                para: "cart".into(),
                paths: vec!["/api/cart".into(), "/api/products".into()],
                port: 8080,
            }),
        }
    }

    #[test]
    fn happy_path_validates() {
        three_member_spec().validate().unwrap();
    }

    #[test]
    fn rejects_empty_membros() {
        let mut s = three_member_spec();
        s.membros = vec![];
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
    }

    #[test]
    fn rejects_empty_membro_caixa() {
        // A `:caixa ""` entry has no name to render into programs.yaml
        // and no caixa.lisp to resolve at lacre time.
        let mut s = three_member_spec();
        s.membros[1].caixa = String::new();
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
    }

    #[test]
    fn rejects_empty_membro_versao() {
        // A `:versao ""` entry can't pin a semver constraint, so the
        // lacre pipeline fails far from the source.
        let mut s = three_member_spec();
        s.membros[2].versao = String::new();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_duplicate_membro_caixa() {
        // Two `:membros` entries with the same `:caixa` collapse to one
        // node in the membership HashSet, which masks `:contratos`
        // membership errors and produces duplicate programs.yaml entries.
        let mut s = three_member_spec();
        s.membros.push(membro("cart", "^0.2"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_invalid_membro_versao_requirement() {
        // The fail-before-pass-after pin: a non-empty but malformed
        // semver requirement (`"^bad-version"`) silently passed
        // `validate()` on every pre-gate codebase because the prior
        // shape only refused the empty string. The parse failure
        // surfaced far downstream at lacre-resolve time with a
        // `semver::Error` that didn't name which `:membros` entry
        // carried the typo. The new gate moves the check to caixa-build
        // time at the source caixa.lisp.
        let mut s = three_member_spec();
        s.membros[2].versao = "^bad-version".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
                    if caixa == "payment" && versao == "^bad-version"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_versao_with_double_caret_typo() {
        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
        // Cargo-shaped requirement on first glance but fails the parser
        // because semver doesn't accept stacked operators. Pin this
        // adjacent-shape footgun explicitly so a future relaxation that
        // accepts "looks-canonical-but-isn't" forms surfaces here.
        let mut s = three_member_spec();
        s.membros[0].versao = "^^0.1".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
                    if caixa == "catalog" && versao == "^^0.1"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_versao_with_v_prefixed_tag() {
        // `"v0.1"` is the canonical "git-tag-shape leaking into the
        // semver requirement slot" typo — an author copies the
        // publish-side git-tag string verbatim into `:versao`, but
        // Cargo's semver parser rejects the leading `v` (only digits +
        // canonical operators are valid in the major-version
        // position). The gate's diagnostic names which member entry
        // carried the v-prefix so the fix is one edit, not a grep
        // through every member's `:versao`. (Note: bare `x`-glob
        // shorthands like `^0.1.x` are *accepted* by the semver crate
        // as an `*` wildcard on the patch axis — they're a Cargo-side
        // valid shape, not a typo, so the gate intentionally lets them
        // through.)
        let mut s = three_member_spec();
        s.membros[1].versao = "v0.1".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
                    if caixa == "cart" && versao == "v0.1"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn accepts_canonical_membro_versao_forms() {
        // The four Cargo-shaped requirement forms `:deps :versao`
        // already accepts via `crate::parse_requirement` must pass the
        // membros gate without re-validating at the resolver layer.
        // Pin every leg so a future tightening of the canonical set
        // surfaces here as a test failure.
        for form in [
            "^0.1",      // caret — minor-range pin (the most common shape)
            "~0.1.2",    // tilde — patch-range pin
            "0.1.0",     // exact — single-version pin
            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
            ">=0.1, <2", // multi-range — comma-separated comparators
        ] {
            let mut s = three_member_spec();
            for m in &mut s.membros {
                m.versao = form.into();
            }
            s.validate()
                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
        }
    }

    #[test]
    fn membro_versao_empty_takes_precedence_over_invalid() {
        // Order pin: the existing `MembroVersaoEmpty` diagnostic
        // (which doesn't try to parse) fires before the new
        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
        // `:versao` keeps its narrower error message — `parse_requirement`
        // would also reject `""`, but the empty-string arm is the more
        // self-locating diagnostic for the author.
        let mut s = three_member_spec();
        s.membros[1].versao = String::new();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
            "got {err:?}"
        );
    }

    #[test]
    fn membro_versao_invalid_fires_before_duplicate_check() {
        // Order pin: a malformed requirement on a non-duplicate entry
        // surfaces *its own* diagnostic (which names the offending
        // `:versao` string), even when a later entry would otherwise
        // collapse onto an earlier name. The per-entry shape gate runs
        // inline before the duplicate-key insert, parallel to
        // `membros_validation_runs_before_contratos_membership_check`
        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
        let mut s = three_member_spec();
        s.membros[0].versao = "^bad".into();
        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
        // The diagnostic-shape pin: the error names the offending
        // `:versao` value verbatim so the author can grep their
        // caixa.lisp without re-running the build, and carries a
        // non-empty `reason` from `semver::VersionReq::parse` so the
        // parser's own wording flows through to the diagnostic.
        let mut s = three_member_spec();
        s.membros[2].versao = "not-a-req".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::MembroVersaoInvalid {
            caixa,
            versao,
            reason,
        } = err
        else {
            panic!("expected MembroVersaoInvalid, got other variant");
        };
        assert_eq!(caixa, "payment");
        assert_eq!(versao, "not-a-req");
        assert!(
            !reason.is_empty(),
            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
        );
    }

    #[test]
    fn membro_versao_invalid_runs_before_contratos_check() {
        // A malformed `:versao` on any member must surface its own
        // diagnostic (which names *which* member to fix) before any
        // `:contratos` membership lookup raises `ContratoMemberMissing`.
        // The `:contratos` gate runs after `validate_membros`, so this
        // is structurally guaranteed — pin it explicitly so a future
        // refactor that reorders the gates surfaces here.
        let mut s = three_member_spec();
        s.membros[1].versao = "^^0.1".into();
        // Add a contrato whose `:para` doesn't exist — would normally
        // raise ContratoMemberMissing at the membership lookup, but
        // the membros gate must fire first.
        s.contratos
            .push(contract_http("cart", "phantom", "/never-reached"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
        );
    }

    #[test]
    fn membros_validation_runs_before_contratos_membership_check() {
        // If `:membros` carries a duplicate, the membership-collapse
        // would silently accept a `:contratos :para "phantom"` so long
        // as some entry hashes to "phantom". Pinning order: the
        // duplicate-membros error fires first, regardless of whether
        // contratos reference real members.
        let mut s = three_member_spec();
        s.membros = vec![
            membro("cart", "^0.1"),
            membro("cart", "^0.2"),
            membro("catalog", "^0.1"),
            membro("payment", "^0.1"),
        ];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
            "got {err:?}"
        );
    }

    #[test]
    fn distinct_membros_validate() {
        // Pin the happy-path: every `:membros` entry has a non-empty
        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
        // The fixture already satisfies this; this test makes the
        // invariant explicit so a future refactor of the fixture can't
        // silently break the guarantee.
        three_member_spec().validate().unwrap();
    }

    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────

    #[test]
    fn rejects_membro_caixa_with_uppercase() {
        // The canonical "I copied the Servico's display name verbatim"
        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
        // but author tools often round-trip a TitleCase or CamelCase
        // identifier from an ADR or a sketch. Pin the diagnostic names
        // the offending name and suggests the lower-cased fix in one
        // edit, mirroring the `rejects_entrada_host_with_uppercase`
        // gate's shape (c7d05ec).
        let mut s = three_member_spec();
        s.membros[1].caixa = "Cart".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
            panic!("expected MembroCaixaInvalid, got other variant");
        };
        assert_eq!(caixa, "Cart");
        assert!(
            reason.contains("uppercase"),
            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
        );
        assert!(
            reason.contains("\"cart\""),
            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
        );
    }

    #[test]
    fn rejects_membro_caixa_with_underscore() {
        // The canonical "I'm thinking of a Python module / Postgres
        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
        // label schema. K8s rejects `metadata.name: my_cart` at admission
        // time with an opaque `field is invalid` (no source-citing
        // diagnostic). The gate moves it to caixa-build time.
        let mut s = three_member_spec();
        s.membros[0].caixa = "my_cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
                    if caixa == "my_cart" && reason.contains('_')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_caixa_with_dot() {
        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
        // subdomain — even though K8s `metadata.name` itself accepts
        // dots (DNS-1123 subdomain rule), this string also lands as a
        // K8s Service name (DNS-1035 label — no dots) and as a label
        // value on identity-based Cilium selectors. The strictest floor
        // among the use sites wins. The "I want to namespace my member
        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
        let mut s = three_member_spec();
        s.membros[2].caixa = "team.cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
                    if caixa == "team.cart" && reason.contains('.')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_caixa_with_leading_hyphen() {
        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
        // with an alphanumeric. The K8s apiserver rejects `-cart`
        // outright; the renderer would emit a `metadata.name: "-cart"`
        // that fails admission far from the source caixa.lisp.
        let mut s = three_member_spec();
        s.membros[0].caixa = "-cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
                    if caixa == "-cart" && reason.contains("start and end")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_caixa_with_trailing_hyphen() {
        // The symmetric arm of the boundary rule. Pin separately so
        // both ends of the label are covered against a future relaxation
        // that only checks one boundary.
        let mut s = three_member_spec();
        s.membros[1].caixa = "cart-".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
                    if caixa == "cart-"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_caixa_with_unicode() {
        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
        // (`xn--…`) by the author before it reaches K8s. The byte-by-
        // byte ASCII validity check rejects multi-byte UTF-8 sequences
        // by the first byte that fails the `[a-z0-9-]` predicate.
        let mut s = three_member_spec();
        s.membros[2].caixa = "café".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
                    if caixa == "café"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_caixa_with_whitespace() {
        // Whitespace is the canonical "I pasted from a sketch / doc"
        // footgun. The apiserver rejects every `metadata.name` value
        // carrying whitespace; pin the gate fires at the right boundary.
        let mut s = three_member_spec();
        s.membros[0].caixa = "my cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
                    if caixa == "my cart"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_membro_caixa_too_long() {
        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
        // exactly. The gate's reason names both the cap and the actual
        // length so the author can shorten in one edit.
        let mut s = three_member_spec();
        let too_long = "a".repeat(64);
        s.membros[1].caixa = too_long.clone();
        let err = s.validate().unwrap_err();
        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
            panic!("expected MembroCaixaInvalid");
        };
        assert_eq!(caixa, too_long);
        assert!(
            reason.contains("63") && reason.contains("64"),
            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
        );
    }

    #[test]
    fn membro_caixa_max_length_validates() {
        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
        // so a future tightening (e.g. dropping to 62) surfaces here as
        // a regression, mirroring `entrada_host_max_length_validates`
        // (c7d05ec).
        let mut s = three_member_spec();
        s.membros[2].caixa = "a".repeat(63);
        s.entrada.as_mut().unwrap().para = "a".repeat(63);
        // remove contratos referencing the renamed member; they'd
        // raise ContratoMemberMissing otherwise
        s.contratos
            .retain(|c| c.de != "payment" && c.para != "payment");
        s.validate().unwrap();
    }

    #[test]
    fn accepts_canonical_membro_caixa_forms() {
        // The DNS-1123 label shapes a caixa author is realistically
        // going to write: single-word lowercase, hyphen-joined, ending
        // in a digit-suffixed version (`cart-v2`), starting with a
        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
        // DNS-1035 which requires a letter at position 0), single-
        // character (`a` — boundary). Pin every leg so a future
        // tightening that bans (e.g.) digit-start identifiers surfaces
        // here.
        for form in [
            "checkout",
            "cart",
            "cart-v2",
            "a",
            "c0",
            "3rd-party-shim",
            "x-1-2-3-4",
        ] {
            let mut s = three_member_spec();
            // Renaming a member also requires updating downstream refs;
            // drop everything else and rebuild a minimal spec around
            // just the one renamed member.
            s.membros = vec![membro(form, "^0.1")];
            s.contratos = vec![];
            s.entrada = None;
            s.validate()
                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
        }
    }

    #[test]
    fn membro_caixa_empty_takes_precedence_over_invalid() {
        // Order pin: the existing `MembroCaixaEmpty` diagnostic
        // (which doesn't try to parse) fires before the new
        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
        // `:caixa` keeps its narrower error message — the new gate
        // would also reject `""`, but the empty-string arm is the more
        // self-locating diagnostic for the author. Mirrors the
        // `entrada_host_empty_takes_precedence_over_invalid` pin
        // (c7d05ec).
        let mut s = three_member_spec();
        s.membros[1].caixa = String::new();
        let err = s.validate().unwrap_err();
        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
    }

    #[test]
    fn membro_caixa_invalid_fires_before_versao_check() {
        // Order pin: an invalid-shape `:caixa` surfaces *its own*
        // diagnostic (which names the offending caixa name), even when
        // the same entry's `:versao` is also empty/invalid. The shape
        // gate runs first because the diagnostic is more self-locating —
        // an empty/invalid `:versao` on an invalid-shape caixa name is
        // a downstream-fix-after-the-caixa-rename concern.
        let mut s = three_member_spec();
        s.membros[1].caixa = "Cart".into();
        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn membro_caixa_invalid_fires_before_duplicate_check() {
        // Order pin: a malformed-shape `:caixa` on an earlier entry
        // surfaces *its own* diagnostic, even when a later entry would
        // otherwise collapse onto a duplicate name. The per-entry shape
        // gate runs inline before the duplicate-key insert, parallel
        // to `membro_versao_invalid_fires_before_duplicate_check`.
        let mut s = three_member_spec();
        s.membros[0].caixa = "Catalog".into();
        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
        // The diagnostic-shape pin: the error names the offending
        // `:caixa` value verbatim so the author can grep their
        // caixa.lisp without re-running the build, and carries a
        // non-empty `reason` naming the specific violation. Same
        // shape every typed-shape gate enshrines (c7d05ec's
        // `entrada_host_diagnostic_carries_offending_host`,
        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
        let mut s = three_member_spec();
        s.membros[2].caixa = "BAD_NAME".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
            panic!("expected MembroCaixaInvalid");
        };
        assert_eq!(caixa, "BAD_NAME");
        assert!(
            !reason.is_empty(),
            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
        );
    }

    #[test]
    fn rejects_contrato_with_unknown_de() {
        let mut s = three_member_spec();
        s.contratos.push(contract_http("phantom", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
        );
    }

    #[test]
    fn rejects_contrato_with_unknown_para() {
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "phantom", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
        );
    }

    #[test]
    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
        // The read-path pin: the phantom-`:de` refusal arm's
        // `ContratoMemberMissing.caixa` carrier must be observed through
        // the lifted [`WitContract::source`] accessor, not the raw
        // `.de.clone()` field-access `String`-carry. Peer of the sibling
        // per-`:contratos` self-loop arm's `.source().to_string()` /
        // `.world_ref().to_string()` `String`-carry sites the earlier
        // convergence lifted onto the same accessor pair. A future
        // silent detour that reintroduced the raw `.de.clone()` at the
        // wrap envelope while the shape-gate and membership lookup
        // routed through the accessor would surface here as a byte-equal
        // miss between the fired diagnostic's `caixa:` field and the
        // offending edge's `.source()` — pinning the accessor as the
        // sole read path across the phantom-name refusal arm's arg +
        // wrap-envelope emit surface.
        let mut s = three_member_spec();
        let phantom = contract_http("phantom", "catalog", "/x");
        s.contratos.push(phantom.clone());
        let err = s.validate().unwrap_err();
        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
        };
        assert_eq!(
            caixa,
            phantom.source(),
            "ContratoMemberMissing.caixa on the phantom-:de arm must \
             byte-equal WitContract::source — the wrap envelope must \
             route through the lifted accessor rather than the raw \
             .de.clone() field-access String-carry"
        );
    }

    #[test]
    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
        // The symmetric read-path pin on the `:para` phantom-name
        // refusal arm — same shape as the sibling `:de` pin above but
        // on the callee-Servico axis. Pins the wrap envelope's
        // `caixa:` field is observed through the lifted
        // [`WitContract::destination`] accessor, not the raw
        // `.para.clone()` field-access `String`-carry.
        let mut s = three_member_spec();
        let phantom = contract_http("cart", "phantom", "/x");
        s.contratos.push(phantom.clone());
        let err = s.validate().unwrap_err();
        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
        };
        assert_eq!(
            caixa,
            phantom.destination(),
            "ContratoMemberMissing.caixa on the phantom-:para arm must \
             byte-equal WitContract::destination — the wrap envelope \
             must route through the lifted accessor rather than the raw \
             .para.clone() field-access String-carry"
        );
    }

    #[test]
    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
        // refusal arm — the `validate_contrato_caixa` arg must be
        // observed through the lifted [`WitContract::source`] accessor,
        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
        // value routes through the shared
        // [`crate::render::require_valid_dns_1123_label`] floor with the
        // accessor-projected value; the fired
        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
        // the offending edge's `.source()`, pinning that the arg + the
        // downstream `caixa: caixa.to_string()` wrap route through the
        // same accessor's read path.
        let mut s = three_member_spec();
        let malformed = contract_http("BAD_NAME", "catalog", "/x");
        s.contratos.push(malformed.clone());
        let err = s.validate().unwrap_err();
        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
        };
        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
        assert_eq!(
            caixa,
            malformed.source(),
            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
             byte-equal WitContract::source — the shape-gate arg + wrap \
             envelope must route through the lifted accessor rather \
             than the raw &c.de &String-borrow"
        );
    }

    #[test]
    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
        // Symmetric arm to the sibling `:de` malformed-shape pin above,
        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
        // route through the lifted [`WitContract::destination`]
        // accessor. `:para` runs after the `:de` shape gate in the
        // canonical edge-direction order, so the `:de` value must be
        // well-shaped for the `:para` gate to fire — the `cart` :de is
        // canonical.
        let mut s = three_member_spec();
        let malformed = contract_http("cart", "BAD_NAME", "/x");
        s.contratos.push(malformed.clone());
        let err = s.validate().unwrap_err();
        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
        };
        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
        assert_eq!(
            caixa,
            malformed.destination(),
            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
             byte-equal WitContract::destination — the shape-gate arg + \
             wrap envelope must route through the lifted accessor \
             rather than the raw &c.para &String-borrow"
        );
    }

    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────

    #[test]
    fn rejects_contrato_de_empty() {
        // `:de ""` previously fell through to `ContratoMemberMissing`
        // (with `caixa: ""`) because the validated `:membros :caixa`
        // set never contains the empty string. The narrower
        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
        // the offending slot.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert_eq!(
            err,
            AplicacaoError::ContratoCaixaEmpty {
                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
            },
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_contrato_para_empty() {
        // Symmetric arm to `:de ""` — `:para ""` previously fell
        // through to `ContratoMemberMissing { caixa: "" }`.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "", "/x"));
        let err = s.validate().unwrap_err();
        assert_eq!(
            err,
            AplicacaoError::ContratoCaixaEmpty {
                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
            },
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_contrato_de_with_uppercase() {
        // The canonical "I copied the Servico's TitleCase display
        // name from an ADR" typo. Until this gate landed `:de "Cart"`
        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
        // as "this caixa isn't in `:membros`" when the root cause is
        // "this `:de` value's shape can never legitimately match a
        // validated member (DNS-1123 labels are lowercase)". The
        // narrower diagnostic names the offending slot, the value
        // verbatim, and the parser-shaped reason.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("Cart", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        let AplicacaoError::ContratoCaixaInvalid {
            slot,
            caixa,
            reason,
        } = err
        else {
            panic!("expected ContratoCaixaInvalid, got other variant");
        };
        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
        assert_eq!(caixa, "Cart");
        assert!(
            reason.contains("uppercase"),
            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
        );
    }

    #[test]
    fn rejects_contrato_para_with_underscore() {
        // The canonical "I'm thinking of a Python module" leak —
        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
        // Pin the `:para` axis surfaces the same diagnostic shape as
        // the `:de` axis on the underscore violation.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_contrato_de_with_dot() {
        // A `:contratos :de` value is a single DNS-1123 *label*, not
        // a subdomain — mirroring the `:membros :caixa` floor. The
        // strictest floor among the use sites wins.
        let mut s = three_member_spec();
        s.contratos
            .push(contract_http("team.cart", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_contrato_para_with_unicode() {
        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
        // validity check rejects multi-byte UTF-8 by the first
        // non-`[a-z0-9-]` byte.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "café", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_contrato_de_with_leading_hyphen() {
        // DNS-1123 boundary rule: labels must start and end with an
        // alphanumeric. K8s rejects `-cart` outright; the narrower
        // shape diagnostic now names the violation at caixa-build
        // time rather than the misframed membership-lookup arm.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("-cart", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_de_empty_takes_precedence_over_invalid() {
        // Order pin: the `ContratoCaixaEmpty` arm fires before the
        // `ContratoCaixaInvalid` parse-side arm — same empty-first
        // cascade `validate_membro_caixa` / `validate_placement_cluster`
        // / `validate_entrada_host` already establish on their peer
        // name axes. The empty string is a structurally distinct
        // authoring footgun (the author left the field blank, vs.
        // typed a malformed value), so it gets its own diagnostic.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert_eq!(
            err,
            AplicacaoError::ContratoCaixaEmpty {
                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
            }
        );
    }

    #[test]
    fn contrato_de_shape_fires_before_para_shape() {
        // Per-axis order pin: within one `:contratos` entry, the `:de`
        // shape gate fires before the `:para` shape gate — same
        // edge-direction order the existing `ContratoMemberMissing` /
        // `ContratoSelfLoop` / target-dispatch checks use, so the
        // diagnostic for a contract with both `:de` and `:para`
        // malformed is stable. Authors fixing the surfaced `:de`
        // first will see `:para`'s diagnostic on re-run.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_shape_fires_before_membership_lookup() {
        // The load-bearing pin: an invalid-shape `:de` surfaces its
        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
        // an invalid-shape `:de` could never legitimately match any
        // member — the prior `ContratoMemberMissing` diagnostic was
        // a structural impossibility framed as a graph-membership
        // failure. The shape gate now routes every such input through
        // the narrower self-locating diagnostic.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("Cart", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
            ),
            "got {err:?}"
        );
        // And the symmetric case: an invalid-shape `:para` surfaces
        // its own diagnostic too, even when `:de` is well-shaped.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "Catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_shape_fires_before_self_edge_check() {
        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
        // bugs: the shape violation (uppercase) and the self-edge
        // violation. The narrower per-axis shape diagnostic surfaces
        // first because fixing the shape may reveal that the author
        // also meant to point `:para` at a different member — the
        // self-edge framing is only useful once both endpoints have
        // valid shape.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("Cart", "Cart", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_well_shaped_phantom_still_raises_member_missing() {
        // Strict-improvement pin: a well-shaped `:de` that simply
        // isn't in `:membros` (a phantom reference — author meant
        // to add the member but didn't, or renamed and missed an
        // update) still surfaces `ContratoMemberMissing`, unchanged.
        // The shape gate only intercepts inputs that could never
        // legitimately match a validated member; legitimately-shaped
        // phantom references remain on the graph-membership axis.
        let mut s = three_member_spec();
        s.contratos
            .push(contract_http("phantom-shim", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoMemberMissing { ref caixa }
                    if caixa == "phantom-shim"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
        // The diagnostic-shape pin: the error names the offending
        // slot (`:de` or `:para`) verbatim and the offending value
        // verbatim plus a non-empty parser-shaped reason, so the
        // author can grep their caixa.lisp for `:de "<name>"` /
        // `:para "<name>"` and fix it in one edit. Same diagnostic
        // shape as `MembroCaixaInvalid` (3f9d7a0) and
        // `PlacementClusterInvalid` (6c8c00b).
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
        let err = s.validate().unwrap_err();
        let AplicacaoError::ContratoCaixaInvalid {
            slot,
            caixa,
            reason,
        } = err
        else {
            panic!("expected ContratoCaixaInvalid, got {err:?}");
        };
        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
        assert_eq!(caixa, "BAD_NAME");
        assert!(
            !reason.is_empty(),
            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
        );
    }

    #[test]
    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
        // Scalar-value pin: the two author-facing kebab-case labels the
        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
        // admits on the `:contratos` per-entry endpoint-shape axis,
        // one arm per typed sub-slot. Mirrors the peer scalar-value
        // pin the sibling top-level M2 / M3 / Supervisor
        // author-facing-label consts carry
        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
        // slot itself), so every altitude of the typed-slot algebra
        // shares the same "one canonical byte-string per arm"
        // discipline. A future rebrand (`:de` → `:from` matching the
        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
        // sibling, `:para` → `:to` matching the same, or
        // `:de`/`:para` → `:source`/`:target` matching the WIT
        // world's `import`/`export` half-vocabulary) lands as an
        // edit to exactly one const, and every consumer that reaches
        // for the label picks it up at build time rather than at
        // runtime as a downstream `ContratoCaixaEmpty` /
        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
        // diagnostic mismatch far from the rename's commit.
        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
    }

    #[test]
    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
        // Production-through-const pin: the two per-axis labels the
        // per-`:contratos` entry endpoint-shape gate at
        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
        // argument to [`validate_contrato_caixa`] route through the
        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
        // future rebrand that reaches the const but not the gate (or
        // vice versa) surfaces here at build time rather than at
        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
        // `slot: <stale-kebab-case>` diagnostic far from the rename's
        // commit. Mirror of the peer
        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
        // pin (882f498) on the sibling M3 top-level slot axis.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("", "catalog", "/x"));
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::ContratoCaixaEmpty {
                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
            }
        );
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "", "/x"));
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::ContratoCaixaEmpty {
                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
            }
        );
    }

    #[test]
    fn accepts_canonical_contrato_caixa_forms() {
        // The DNS-1123 label shapes a caixa author is realistically
        // going to write on a `:contratos :de` / `:para`. Pin every
        // leg so a future tightening that bans (e.g.) digit-start
        // identifiers surfaces here, mirroring
        // `accepts_canonical_membro_caixa_forms` on the peer name
        // axis.
        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
            let mut s = three_member_spec();
            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
            s.contratos = vec![contract_http("checkout", form, "/x")];
            s.entrada = None;
            s.validate().unwrap_or_else(|e| {
                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
            });

            let mut s = three_member_spec();
            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
            s.contratos = vec![contract_http(form, "catalog", "/x")];
            s.entrada = None;
            s.validate().unwrap_or_else(|e| {
                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
            });
        }
    }

    #[test]
    fn rejects_empty_wit() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "".into(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
    }

    #[test]
    fn rejects_entrada_to_unknown_member() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "phantom".into();
        assert!(matches!(
            s.validate().unwrap_err(),
            AplicacaoError::EntradaMemberMissing { .. }
        ));
    }

    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────

    #[test]
    fn rejects_entrada_para_empty() {
        // `:para ""` previously fell through to
        // `EntradaMemberMissing { para: "" }` because the validated
        // `:membros :caixa` set never contains the empty string. The
        // narrower `EntradaParaEmpty` diagnostic now names the
        // offending slot directly — same empty-first cascade
        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
        // `ContratoCaixaEmpty` establish on the peer name axes.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = String::new();
        let err = s.validate().unwrap_err();
        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
    }

    #[test]
    fn rejects_entrada_para_with_uppercase() {
        // The canonical "I copied the Servico's TitleCase display
        // name from an ADR" typo. Until this gate landed `:para "Cart"`
        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
        // as "this caixa isn't in `:membros`" when the root cause is
        // "this `:para` value's shape can never legitimately match a
        // validated member (DNS-1123 labels are lowercase)". The
        // narrower diagnostic names the value verbatim plus the
        // parser-shaped reason.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "Cart".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
            panic!("expected EntradaParaInvalid, got other variant");
        };
        assert_eq!(para, "Cart");
        assert!(
            reason.contains("uppercase"),
            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
        );
    }

    #[test]
    fn rejects_entrada_para_with_underscore() {
        // The canonical "I'm thinking of a Python module" leak —
        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "my_cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
                    if para == "my_cart" && reason.contains('_')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_para_with_dot() {
        // An `:entrada :para` value is a single DNS-1123 *label*, not
        // a subdomain — mirroring the `:membros :caixa` floor. The
        // strictest floor among the use sites wins.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "team.cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
                    if para == "team.cart" && reason.contains('.')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_para_with_unicode() {
        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
        // (`xn--…`) before it reaches K8s.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "café".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_para_with_leading_hyphen() {
        // DNS-1123 boundary rule: labels must start and end with an
        // alphanumeric. K8s rejects `-cart` outright.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "-cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
                    if para == "-cart" && reason.contains("start and end")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_para_with_trailing_hyphen() {
        // Symmetric boundary arm.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "cart-".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
                    if para == "cart-" && reason.contains("start and end")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_para_too_long() {
        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
        // bytes per label. K8s rejects longer names at admission on
        // every `metadata.name` axis.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "a".repeat(64);
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
                    if para.len() == 64 && reason.contains("max length")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_para_empty_takes_precedence_over_invalid() {
        // Order pin: the `EntradaParaEmpty` arm fires before the
        // `EntradaParaInvalid` parse-side arm — same empty-first
        // cascade `validate_membro_caixa` / `validate_placement_cluster`
        // / `validate_contrato_caixa` already establish.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = String::new();
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
    }

    #[test]
    fn entrada_para_shape_fires_before_membership_lookup() {
        // The load-bearing pin: an invalid-shape `:para` surfaces its
        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
        // an invalid-shape `:para` could never legitimately match any
        // member — the prior `EntradaMemberMissing` diagnostic framed
        // a structural impossibility as a graph-membership failure.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "Cart".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_para_shape_fires_before_host_gate() {
        // Per-`:entrada` order pin: the `:para` shape gate fires
        // before the `:host` gate, mirroring the existing
        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
        // ordering where the member-lookup arm preceded the host gate.
        // The shape gate slots ahead of that, so a malformed `:para`
        // surfaces its own diagnostic even when `:host` is also wrong.
        let mut s = three_member_spec();
        let e = s.entrada.as_mut().unwrap();
        e.para = "Cart".into();
        e.host = "BAD HOST".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
        // Strict-improvement pin: a well-shaped `:para` that simply
        // isn't in `:membros` (a phantom reference — author meant to
        // add the member but didn't, or renamed and missed an
        // update) still surfaces `EntradaMemberMissing`, unchanged.
        // The shape gate only intercepts inputs that could never
        // legitimately match a validated member.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::EntradaMemberMissing { ref para }
                    if para == "phantom-shim"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_para_invalid_diagnostic_carries_offending_para() {
        // The diagnostic-shape pin: the error names the offending
        // `:para` value verbatim plus a non-empty parser-shaped
        // reason, so the author can grep their caixa.lisp for
        // `:para "<name>"` and fix it in one edit. Same diagnostic
        // shape as `MembroCaixaInvalid` (3f9d7a0),
        // `PlacementClusterInvalid` (6c8c00b), and
        // `ContratoCaixaInvalid` (8d5af6b).
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
            panic!("expected EntradaParaInvalid, got {err:?}");
        };
        assert_eq!(para, "BAD_NAME");
        assert!(
            !reason.is_empty(),
            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
        );
    }

    #[test]
    fn accepts_canonical_entrada_para_forms() {
        // Positive-control sweep covering the DNS-1123 label shapes a
        // caixa author is realistically going to write on `:entrada
        // :para`. Pin every leg so a future tightening that bans
        // (e.g.) digit-start identifiers surfaces here, mirroring
        // `accepts_canonical_membro_caixa_forms` and
        // `accepts_canonical_contrato_caixa_forms` on the peer name
        // axes.
        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
            let mut s = three_member_spec();
            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
            s.contratos = vec![contract_http(form, "catalog", "/x")];
            s.entrada = Some(Entrada {
                host: "checkout.quero.cloud".into(),
                para: form.into(),
                paths: vec!["/api".into()],
                port: 8080,
            });
            s.validate().unwrap_or_else(|e| {
                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
            });
        }
    }

    #[test]
    fn rejects_replicated_without_clusters() {
        let mut s = three_member_spec();
        s.placement.clusters = vec![];
        assert!(matches!(
            s.validate().unwrap_err(),
            AplicacaoError::PlacementWithoutClusters { .. }
        ));
    }

    #[test]
    fn rejects_sharded_without_key() {
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::Sharded;
        s.placement.shard_key = None;
        s.placement.clusters = vec!["rio".into()];
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
    }

    #[test]
    fn sharded_with_key_validates() {
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::Sharded;
        s.placement.shard_key = Some("$tenantId".into());
        s.validate().unwrap();
    }

    #[test]
    fn round_trip_via_json_preserves_shape() {
        let s = three_member_spec();
        let json = serde_json::to_string(&s.membros).unwrap();
        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, s.membros);

        let json = serde_json::to_string(&s.contratos).unwrap();
        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, s.contratos);

        let json = serde_json::to_string(&s.placement).unwrap();
        let back: Placement = serde_json::from_str(&json).unwrap();
        assert_eq!(back, s.placement);

        let json = serde_json::to_string(&s.entrada).unwrap();
        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, s.entrada);
    }

    #[test]
    fn rate_limit_round_trip_seconds() {
        let policy = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 100,
                window: Duration::from_secs(1),
            }),
            ..Default::default()
        };
        let json = serde_json::to_string(&policy).unwrap();
        assert!(json.contains("\"100/s\""));
        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(back.rate_limit.unwrap().rate, 100);
        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
    }

    #[test]
    fn rate_limit_round_trip_minutes() {
        let policy = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 5000,
                window: Duration::from_secs(60),
            }),
            ..Default::default()
        };
        let json = serde_json::to_string(&policy).unwrap();
        assert!(json.contains("\"5000/m\""));
    }

    #[test]
    fn circuit_breaker_round_trip() {
        let policy = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 5,
                window: Duration::from_secs(60),
            }),
            ..Default::default()
        };
        let json = serde_json::to_string(&policy).unwrap();
        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
        assert_eq!(
            back.circuit_breaker.unwrap().window,
            Duration::from_secs(60)
        );
    }

    #[test]
    fn rejects_http_contrato_without_endpoint() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(matches!(
            err,
            AplicacaoError::ContratoMissingTarget {
                expected: WitTarget::HTTP_FIELD_NAME,
                ..
            }
        ));
    }

    #[test]
    fn rejects_http_contrato_with_subject() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/x".into()),
            subject: Some("not.allowed.here".into()),
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(matches!(
            err,
            AplicacaoError::ContratoWrongTarget {
                expected: WitTarget::HTTP_FIELD_NAME,
                ..
            }
        ));
    }

    #[test]
    fn rejects_pubsub_contrato_without_subject() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(matches!(
            err,
            AplicacaoError::ContratoMissingTarget {
                expected: WitTarget::PUBSUB_FIELD_NAME,
                ..
            }
        ));
    }

    #[test]
    fn rejects_pubsub_contrato_with_endpoint() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "kafka:topic".into(),
            endpoint: Some("/wrong".into()),
            subject: Some("topic.x".into()),
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(matches!(
            err,
            AplicacaoError::ContratoWrongTarget {
                expected: WitTarget::PUBSUB_FIELD_NAME,
                ..
            }
        ));
    }

    #[test]
    fn rejects_store_contrato_without_slot() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(matches!(
            err,
            AplicacaoError::ContratoMissingTarget {
                expected: WitTarget::STORE_FIELD_NAME,
                ..
            }
        ));
    }

    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────

    #[test]
    fn rejects_http_contrato_with_empty_endpoint() {
        // `Some("")` for an HTTP endpoint passes the presence check
        // (target() previously returned WitTarget::Http { endpoint: "" })
        // but renders as a `path: ""` Cilium L7 rule that matches no
        // traffic. Same value-shape footgun closed for :entrada :paths
        // entries (eb3456d).
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some(String::new()),
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
                if de == "cart" && para == "catalog"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_with_relative_endpoint() {
        // Cilium L7 :path + Gateway API PathPrefix both require a
        // leading `/`. Same shape required of :entrada :paths
        // (eb3456d). Lifted into target() so every consumer of the
        // typed WitTarget view inherits the guarantee.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("products/:id".into()),
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
                if endpoint == "products/:id"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_with_empty_subject() {
        // NATS / Kafka publish without a subject is a no-op subscribe;
        // never the author's intent. Same empty-string rejection as
        // :membros :caixa, :placement :clusters entries, :entrada
        // :paths entries — every value carried by every typed slot is
        // value-shape-checked at validate().
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some(String::new()),
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
                if de == "cart" && para == "catalog"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_store_contrato_with_empty_slot() {
        // An empty slot template addresses the bucket root, defeating
        // the per-key isolation the slot exists for — a footgun on
        // `wasi:keyvalue/store` whose closest analog is the empty
        // shard-key rejected on :placement Sharded (c7c7799).
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some(String::new()),
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
                if de == "cart" && para == "catalog"),
            "got {err:?}"
        );
    }

    #[test]
    fn http_contrato_root_endpoint_validates() {
        // Pin the boundary case: a single-`/` endpoint is the catch-all
        // form the Gateway HTTPRoute renderer falls back to when
        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
        // must remain a valid contrato endpoint too.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "catalog", "/"));
        s.validate().unwrap();
    }

    // ── :contratos :endpoint value-shape gate ────────────────────────────
    //
    // Mirrors the `:entrada :paths` value-shape suite on the peer
    // HTTP-path axis. Until this gate landed `WitContract::target()`
    // only refused the empty string + the missing-leading-`/` form
    // (c4213a4); a structurally invalid endpoint passed validate and
    // landed verbatim as a Cilium L7 `path:` rule
    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
    // traffic or was rejected at apply time by Cilium policy admission.
    // Every authoring footgun the K8s Gateway API webhook / Cilium
    // policy validator would catch on admission now becomes a caixa-
    // build-time `ContratoEndpointInvalid` with the offending
    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
    // shape as `EntradaPathInvalid` on the sibling axis; same shared
    // predicate (`crate::render::is_gateway_api_http_path`) ensures
    // drift between the two axes' rule enforcement is a build error
    // at the predicate.

    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
        // Fresh spec per call so the would-be-duplicate edge
        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
        // `three_member_spec`'s pre-existing
        // `(cart, catalog, …, /products/:id)` entry — only the
        // endpoint payload differs.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "catalog", ep));
        s.validate().unwrap_err()
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_query() {
        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
        // rule the L7 matcher would never satisfy.
        let err = contrato_endpoint_err("/charge?token=X");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_fragment() {
        let err = contrato_endpoint_err("/charge#frag");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_whitespace() {
        let err = contrato_endpoint_err("/foo bar");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/foo bar" && reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_control_char() {
        let err = contrato_endpoint_err("/api/\x01bar");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/api/\x01bar" && reason.contains("control character")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_non_ascii() {
        let err = contrato_endpoint_err("/api/café");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/api/café" && reason.contains("non-ASCII")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
        let err = contrato_endpoint_err("/api//cart");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_dot_segment() {
        let err = contrato_endpoint_err("/api/./cart");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_parent_segment() {
        // Path-traversal in a contrato endpoint is the canonical
        // "L7 rule that the workload's HTTP server's path-resolution
        // logic interprets differently than the policy enforcer"
        // footgun. Rejected outright at validate time.
        let err = contrato_endpoint_err("/api/../etc");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_too_long() {
        // 1025-byte endpoint — one over the Gateway API
        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
        // path matcher has no inherent length limit but the policy
        // CR itself rides through the K8s apiserver, which enforces
        // ConfigMap-shaped limits; sharing the Gateway API cap is the
        // conservative floor.
        let big = format!("/api/{}", "a".repeat(1020));
        assert_eq!(big.len(), 1025);
        let err = contrato_endpoint_err(&big);
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == &big && reason.contains("max length of 1024")),
            "got {err:?}"
        );
    }

    #[test]
    fn http_contrato_endpoint_max_length_validates() {
        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
        // in the cap surfaces here and at
        // `rejects_http_contrato_endpoint_too_long` simultaneously,
        // mirroring `entrada_path_max_length_validates` on the peer
        // axis.
        let big = format!("/api/{}", "a".repeat(1019));
        assert_eq!(big.len(), 1024);
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "catalog", &big));
        s.validate().unwrap();
    }

    #[test]
    fn http_contrato_endpoint_accepts_canonical_forms() {
        // Positive-set sweep: every canonical HTTP-path shape the
        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
        // plain paths, hidden-file-style `.config` segments distinct
        // from the `.` segment, digit-bearing segments, the canonical
        // route-template `:param` form, trailing-slash form,
        // percent-encoded segments, the `/foo..bar` interior-`..`-
        // substring forms that are NOT `..` segments) must remain a
        // valid contrato endpoint too. Drift between this list and
        // the entrada path positive sweep surfaces at the shared
        // `is_gateway_api_http_path` substrate-side suite — one
        // source of truth. Uses a fresh `(payment, catalog)` edge so
        // none of the swept endpoints collide with the pre-existing
        // `(cart, catalog, /products/:id)` / `(cart, payment,
        // /charge)` entries in `three_member_spec`.
        for ep in [
            "/",
            "/charge",
            "/v1/charge",
            "/api/.config",
            "/products/:id",
            "/api/cart/",
            "/api/caf%C3%A9",
            "/foo..bar",
            "/...",
        ] {
            let mut s = three_member_spec();
            s.contratos.push(contract_http("payment", "catalog", ep));
            s.validate()
                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
        }
    }

    #[test]
    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
        // Ordering pin: `ContratoEndpointEmpty` is the more self-
        // locating diagnostic on `""` and must lead — the value-
        // shape gate is only reached after the empty-check fires.
        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
        // on the peer axis.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some(String::new()),
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
        // Ordering pin: an endpoint without a leading `/` surfaces the
        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
        // value-shape gate is only consulted on endpoints that already
        // satisfy the absolute-prefix invariant. Mirrors
        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
        let err = contrato_endpoint_err("bad path");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
                if endpoint == "bad path"),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
        // `:para` + a non-empty reason flow through verbatim so the
        // author can grep their caixa.lisp for the offending contrato
        // block and fix it in one edit. Same shape as
        // `entrada_path_diagnostic_carries_offending_path`.
        let err = contrato_endpoint_err("/api?q=1");
        match err {
            AplicacaoError::ContratoEndpointInvalid {
                de,
                para,
                endpoint,
                reason,
            } => {
                assert_eq!(de, "cart");
                assert_eq!(para, "catalog");
                assert_eq!(endpoint, "/api?q=1");
                assert!(!reason.is_empty(), "reason field must be non-empty");
            }
            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
        }
    }

    #[test]
    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
        // The compounding theorem: every &str inside a WitTarget
        // returned by target() is non-empty (and absolute, for Http).
        // Renderers downstream of typed_view() can rely on this
        // without re-checking — the type system carries the proof.
        let http = contract_http("cart", "catalog", "/x");
        match http.target().unwrap() {
            WitTarget::Http { endpoint } => {
                assert!(!endpoint.is_empty());
                assert!(endpoint.starts_with('/'));
            }
            other => panic!("expected Http, got {other:?}"),
        }
        let nats = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("topic.x".into()),
            slot: None,
        };
        match nats.target().unwrap() {
            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
            other => panic!("expected PubSub, got {other:?}"),
        }
        let kv = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("checkout/$orderId".into()),
        };
        match kv.target().unwrap() {
            WitTarget::Store { slot } => assert!(!slot.is_empty()),
            other => panic!("expected Store, got {other:?}"),
        }
    }

    #[test]
    fn target_diagnostic_names_offending_endpoint_value() {
        // When the malformed endpoint string is non-trivial, the
        // diagnostic carries the actual value back to the author —
        // not a generic "endpoint malformed" error.
        let bad = WitContract {
            de: "src".into(),
            para: "dst".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("api/v1/charge".into()),
            subject: None,
            slot: None,
        };
        match bad.target().unwrap_err() {
            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
                assert_eq!(de, "src");
                assert_eq!(para, "dst");
                assert_eq!(endpoint, "api/v1/charge");
            }
            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
        }
    }

    #[test]
    fn rejects_unknown_wit_with_target_set() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "custom:exchange".into(),
            endpoint: Some("/leaked".into()),
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(matches!(
            err,
            AplicacaoError::ContratoWrongTarget {
                expected: WitTarget::CAPABILITY_EXPECTED,
                ..
            }
        ));
    }

    #[test]
    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
        // fourth arm of the same "which payload field name goes in the
        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
        // consts cover on the peer HTTP / PubSub / Store arms
        // (`wit_target_field_name_pins_per_variant`). Until this lift
        // landed the byte-string sat twice — once inline in the
        // [`WitContract::target`] Capability-arm rejection at the
        // production dispatch, once in `rejects_unknown_wit_with_target_set`
        // pinning against the same literal — with no compile-time link
        // between them. Same "one canonical declaration, next to the
        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
        // lift established for the payload-less arm's human-readable
        // label axis; this test is the shape peer of
        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
        // pair (routes-through-const + scalar-value pin) on the
        // wrong-target diagnostic-scalar axis.
        //
        // Fail-before-pass-after was verified locally by mutating the
        // const declaration to `"capability"` — the scalar-value pin
        // below fires (`"capability" != "none"`) and the routes-through
        // assertion below still holds (production and const walk in
        // lockstep), which is the correct behavior: a rename on the
        // const drifts here first, not at a downstream consumer.
        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");

        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "custom:exchange".into(),
            endpoint: Some("/leaked".into()),
            subject: None,
            slot: None,
        });
        match s.validate().unwrap_err() {
            AplicacaoError::ContratoWrongTarget { expected, .. } => {
                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
            }
            other => panic!("expected ContratoWrongTarget, got {other:?}"),
        }
    }

    #[test]
    fn unknown_wit_capability_only_validates() {
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            // A WIT world we haven't yet shaped — accept it as a typed
            // capability edge so authors aren't blocked while the WIT
            // registry catches up. No payload field may be carried.
            wit: "custom:exchange".into(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        s.validate().unwrap();
        let added = s.contratos.last().unwrap();
        assert_eq!(added.target().unwrap(), WitTarget::Capability);
    }

    #[test]
    fn target_typed_view_round_trips_each_shape() {
        let http = contract_http("cart", "catalog", "/products/:id");
        assert_eq!(
            http.target().unwrap(),
            WitTarget::Http {
                endpoint: "/products/:id"
            }
        );
        let nats = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("topic.x".into()),
            slot: None,
        };
        assert_eq!(
            nats.target().unwrap(),
            WitTarget::PubSub { subject: "topic.x" }
        );
        let kv = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("checkout/$orderId".into()),
        };
        assert_eq!(
            kv.target().unwrap(),
            WitTarget::Store {
                slot: "checkout/$orderId"
            }
        );
    }

    #[test]
    fn wit_contract_kind_predicates() {
        let http = contract_http("a", "b", "/x");
        assert!(http.is_http());
        assert!(!http.is_pubsub());
        assert!(!http.is_store());

        let nats = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("topic.x".into()),
            slot: None,
        };
        assert!(nats.is_pubsub());
        assert!(!nats.is_http());

        let kv = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("checkout/$orderId".into()),
        };
        assert!(kv.is_store());
        assert!(!kv.is_http());
    }

    // ── :contratos :wit value-shape gate ─────────────────────────────────
    //
    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
    // dispatch-discriminator axis. Until this gate landed
    // `WitContract::target()` accepted any non-empty string and
    // silently demoted unrecognized shapes to a capability-only L4
    // edge — the canonical "I thought I had L7 HTTP routing, got
    // L4-only" footgun. Every authoring footgun the WIT registry's
    // own grammar rejects (uppercase, hyphen-for-colon typo,
    // whitespace, empty package, doubled `@`, …) now becomes a
    // caixa-build-time `ContratoWitInvalid` with the offending
    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
    // as `ContratoEndpointInvalid` on the sibling axis; same shared
    // predicate (`crate::render::is_wit_world_ref`) ensures drift
    // between any two axes' rule enforcement is a build error at the
    // predicate, not piecemeal across renderers.

    fn contrato_wit_err(wit: &str) -> AplicacaoError {
        // Fresh spec per call so the new contract doesn't collide on
        // identity with `three_member_spec`'s pre-existing entries.
        // The new edge uses `(payment, catalog)` — a pair the fixture
        // doesn't already declare — with no payload field set, so the
        // wit-shape gate fires before any payload-shape arm.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: wit.into(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        s.validate().unwrap_err()
    }

    #[test]
    fn rejects_wit_with_uppercase_namespace() {
        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
        // didn't match the lowercase `wasi:http/` prefix is_http() keys
        // off, so the dispatch fell through to the capability arm and
        // the contract silently rendered as an L4-only Cilium edge.
        // The new gate surfaces the uppercase typo at validate time
        // with the offending `:wit` named.
        let err = contrato_wit_err("WASI:http/proxy");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_hyphen_for_colon_typo() {
        // The canonical "I forgot the `:` separator" typo — pre-gate
        // this passed as Capability silently, so the renderer emitted
        // an L4-only policy where the author expected L7 HTTP rules.
        let err = contrato_wit_err("wasi-http/proxy");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_multiple_colons() {
        // Doubled `:` — the namespace/package split has nowhere to
        // anchor, so the dispatch silently demotes to Capability.
        let err = contrato_wit_err("wasi:http:proxy");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_empty_package() {
        // `wasi:` — namespace alone with no package. Pre-gate this
        // failed neither the is_http nor is_pubsub nor is_store
        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
        // a bare `wasi:`), so it silently demoted to Capability.
        let err = contrato_wit_err("wasi:");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_underscore() {
        // Underscore — WIT identifiers are kebab-case, same rule
        // DNS-1123 enforces on its peer axes. The diagnostic carries
        // the explicit "use `-` instead" remediation.
        let err = contrato_wit_err("wasi:http_proxy");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "wasi:http_proxy" && reason.contains('_')),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_whitespace() {
        // Whitespace mid-token — the prefix check matches but the
        // package-and-onward parse silently demoted to Capability.
        let err = contrato_wit_err("wasi:http proxy");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "wasi:http proxy" && reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_non_ascii() {
        // Un-percent-encoded non-ASCII byte — the canonical "I copied
        // the package name from a doc with smart quotes / accented
        // characters" footgun.
        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_consecutive_hyphens() {
        // `pub--sub` — WIT identifiers join words with single hyphens.
        let err = contrato_wit_err("nats:pub--sub");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_with_trailing_at_no_version() {
        // `wasi:http/proxy@` — the version-suffix author started to
        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
        // parser would reject this; surface it at validate time.
        let err = contrato_wit_err("wasi:http/proxy@");
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_wit_too_long() {
        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
        // The legitimate-shape arms all pass (lowercase, single `:`,
        // kebab-case identifiers); only the cap arm fires. Surfaces
        // the paste-from-binary / accidental-multi-line-blob landing
        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
        // on the peer axis.
        let big = format!("wasi:{}", "a".repeat(124));
        assert_eq!(big.len(), 129);
        let err = contrato_wit_err(&big);
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
                if wit == &big && reason.contains("max length of 128")),
            "got {err:?}"
        );
    }

    #[test]
    fn wit_max_length_validates() {
        // 128-byte WIT reference — exactly the cap. Boundary pin:
        // drift in the cap surfaces here and at `rejects_wit_too_long`
        // simultaneously, mirroring
        // `http_contrato_endpoint_max_length_validates` on the peer
        // axis.
        let big = format!("wasi:{}", "a".repeat(123));
        assert_eq!(big.len(), 128);
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: big,
            endpoint: None,
            subject: None,
            slot: None,
        });
        s.validate().unwrap();
    }

    #[test]
    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
        // Positive-set sweep through the AplicacaoSpec::validate
        // surface (rather than the substrate-side predicate directly)
        // — pins every shape the existing test fixtures + the
        // checkout-aplicacao example carry, so the gate's accept-set
        // matches the substrate's emit-set. Drift between this list
        // and `render::tests::wit_world_ref_accepts_canonical_forms`
        // surfaces at the substrate layer's positive sweep — one
        // source of truth for the rule.
        for wit in [
            "wasi:http/proxy",
            "wasi:keyvalue/store",
            "nats:pub-sub",
            "kafka:topic",
            "custom:exchange",
            "pleme:cap/audit",
            "wasi:http/proxy@0.2.0",
        ] {
            // Payload field paired to the dispatched WIT shape so the
            // shape-↔-target arm doesn't fire instead of the wit-shape
            // arm we're exercising. Routes off the same
            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
            // `wit_shape_is_store` free functions the production
            // `WitContract::is_http` / `is_pubsub` / `is_store`
            // methods delegate to (both consult the lifted
            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
            // future prefix addition to the routing accept-set
            // reaches this test's payload-dispatch arm by
            // construction — no per-test-site drift can hide a
            // shape-→-target-slot mismatch that would silently
            // demote a canonical `:wit` value to the
            // `(None, None, None)` capability-only arm and let the
            // `AplicacaoSpec::validate` positive sweep pass on a
            // shape it should exercise as HTTP / pub-sub / store.
            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
                (Some("/x".into()), None, None)
            } else if wit_shape_is_pubsub(wit) {
                (None, Some("topic.x".into()), None)
            } else if wit_shape_is_store(wit) {
                (None, None, Some("bucket/$key".into()))
            } else {
                (None, None, None)
            };
            let mut s = three_member_spec();
            s.contratos.push(WitContract {
                de: "payment".into(),
                para: "catalog".into(),
                wit: wit.into(),
                endpoint,
                subject,
                slot,
            });
            s.validate()
                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
        }
    }

    #[test]
    fn wit_shape_predicates_accept_canonical_prefix_set() {
        // Positive-set sweep pinning every prefix in
        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
        // WIT_STORE_SHAPE_PREFIXES against the three free-function
        // dispatch predicates. The six prefixes are the load-bearing
        // routing keys the substrate's WIT-shape dispatch consults
        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
        // key/value-store-slot admission); any drift between the
        // free-function accept-set and this list surfaces here
        // rather than at apply time as a silent
        // shape-→-capability-only demotion.
        assert!(wit_shape_is_http("wasi:http/proxy"));
        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
        assert!(wit_shape_is_http("http:incoming"));

        assert!(wit_shape_is_pubsub("nats:pub-sub"));
        assert!(wit_shape_is_pubsub("kafka:topic"));

        assert!(wit_shape_is_store("wasi:keyvalue/store"));
        assert!(wit_shape_is_store("kv:cache/session"));
    }

    #[test]
    fn wit_shape_predicates_reject_uncanonical_forms() {
        // Negative-set pin: the six canonical prefixes are
        // lowercase-only (mirrors the `is_wit_world_ref` substrate
        // predicate's lowercase invariant — see its docstring on the
        // "I thought I had L7 HTTP routing, got L4-only" footgun).
        // The empty string, an uppercase-prefixed form, a hyphen-
        // instead-of-colon typo, and a bare kebab identifier all miss
        // every shape arm — reachable-by-construction only via the
        // `is_wit_world_ref` gate that admission-checks the `:wit`
        // value first, but pinned here so any future
        // free-function change (e.g. a case-insensitive
        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
        // this unit level.
        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
        }
    }

    #[test]
    fn wit_shape_predicates_partition_canonical_set() {
        // Every canonical prefix routes to exactly one shape arm —
        // the three prefix sets are pairwise disjoint. Pins the
        // routing property [`WitContract::target`] relies on: an
        // `is_http()` return of `true` guarantees `is_pubsub()` and
        // `is_store()` return `false`, so the shape-→-target-slot
        // dispatch (endpoint vs subject vs slot) is unambiguous.
        // Drift (e.g. a future `"kv:"` moved into the HTTP set
        // without removal from the store set) would silently route
        // one prefix to two arms and the first-matching-arm order
        // becomes load-bearing — this pin surfaces it as a build
        // error instead.
        for prefix in WIT_HTTP_SHAPE_PREFIXES {
            let sample = format!("{prefix}x");
            assert!(wit_shape_is_http(&sample));
            assert!(!wit_shape_is_pubsub(&sample));
            assert!(!wit_shape_is_store(&sample));
        }
        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
            let sample = format!("{prefix}x");
            assert!(!wit_shape_is_http(&sample));
            assert!(wit_shape_is_pubsub(&sample));
            assert!(!wit_shape_is_store(&sample));
        }
        for prefix in WIT_STORE_SHAPE_PREFIXES {
            let sample = format!("{prefix}x");
            assert!(!wit_shape_is_http(&sample));
            assert!(!wit_shape_is_pubsub(&sample));
            assert!(wit_shape_is_store(&sample));
        }
    }

    #[test]
    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
        // Positive pin: [`wit_shape_matches`] is exactly the
        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
        // parameterized on the accept-set. Two-prefix accept-set,
        // one-prefix accept-set, and empty accept-set (which must
        // reject everything, including the empty string — an empty
        // `any()` fold returns `false`) all pinned so a future
        // reimplementation that swaps `starts_with` for `contains`,
        // `==`, or a case-folded comparator surfaces at unit-test
        // time.
        let two = &["wasi:http/", "http:"];
        assert!(wit_shape_matches("wasi:http/proxy", two));
        assert!(wit_shape_matches("http:incoming", two));
        assert!(!wit_shape_matches("wasi:keyvalue/store", two));

        let one = &["nats:"];
        assert!(wit_shape_matches("nats:pub-sub", one));
        assert!(!wit_shape_matches("kafka:topic", one));

        // Empty accept-set matches nothing — the identity element
        // for the disjunctive `any()` fold across the prefix set.
        // Reachable via a future `wit_shape_is_<name>` const paired
        // to a still-empty prefix table on a nascent shape-arm draft.
        let empty: &[&str] = &[];
        assert!(!wit_shape_matches("wasi:http/proxy", empty));
        assert!(!wit_shape_matches("", empty));

        // starts_with, not contains: a prefix embedded mid-string
        // never matches. Pins the routing invariant [`WitContract::target`]
        // relies on (an authored `:wit "custom:wasi:http/"` string
        // does not silently route through the HTTP arm just because
        // it happens to contain the canonical HTTP prefix).
        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
    }

    #[test]
    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
        // Equivalence pin: each per-shape predicate is exactly
        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
        // every canonical prefix + the empty string + one negative
        // sample against every peer so a future predicate that grew
        // its own inline `iter().any(starts_with)` (rather than
        // delegating through the lifted combinator) drifts loudly here
        // — the peer-const table's contents must agree with the
        // predicate's accept-set by construction.
        let samples = [
            String::new(),
            "wasi:http/proxy".to_string(),
            "http:incoming".to_string(),
            "nats:pub-sub".to_string(),
            "kafka:topic".to_string(),
            "wasi:keyvalue/store".to_string(),
            "kv:cache/session".to_string(),
            "custom-shape".to_string(),
            "WASI:HTTP/proxy".to_string(),
        ];
        for wit in &samples {
            assert_eq!(
                wit_shape_is_http(wit),
                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
                "wit_shape_is_http drifted from combinator on {wit:?}",
            );
            assert_eq!(
                wit_shape_is_pubsub(wit),
                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
            );
            assert_eq!(
                wit_shape_is_store(wit),
                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
                "wit_shape_is_store drifted from combinator on {wit:?}",
            );
        }
    }

    #[test]
    fn wit_contract_shape_methods_delegate_to_free_functions() {
        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
        // `is_store` are `&self` conveniences on top of the free
        // functions — for every canonical prefix the method's return
        // matches its free-function peer. Sweeps the union of the
        // three prefix sets so a future method that grew its own
        // inline prefix logic (rather than delegating) drifts loudly
        // here on the first prefix the free function accepts and the
        // method doesn't.
        for shape_set in [
            WIT_HTTP_SHAPE_PREFIXES,
            WIT_PUBSUB_SHAPE_PREFIXES,
            WIT_STORE_SHAPE_PREFIXES,
        ] {
            for prefix in shape_set {
                let c = WitContract {
                    de: "cart".into(),
                    para: "catalog".into(),
                    wit: format!("{prefix}x"),
                    endpoint: None,
                    subject: None,
                    slot: None,
                };
                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
            }
        }
    }

    #[test]
    fn empty_wit_takes_precedence_over_invalid() {
        // Ordering pin: `EmptyWit` is the more self-locating
        // diagnostic on `""` and must lead — the value-shape gate is
        // only reached after the empty-check fires. Mirrors
        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
        // the peer payload axis.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: String::new(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EmptyWit { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn wit_invalid_fires_before_payload_shape_arm() {
        // Ordering pin: a malformed `:wit` surfaces *its own*
        // diagnostic (which names the offending wit verbatim) before
        // any payload-field check — a contrato whose wit is
        // structurally invalid AND carries a wrong target field
        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
        // because the dispatch on the wit is what decides which
        // payload field is "right" in the first place. Without this
        // ordering, the author would see "wrong target field" for a
        // wit that hasn't even been parsed, which doesn't name the
        // root cause.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            // Hyphen-for-colon typo + endpoint set: pre-gate this
            // raised `ContratoWrongTarget { expected: "none" }` (the
            // Capability arm rejecting the endpoint), masking the
            // real authoring mistake (the wit isn't `wasi:http/proxy`).
            wit: "wasi-http/proxy".into(),
            endpoint: Some("/x".into()),
            subject: None,
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
                if wit == "wasi-http/proxy"),
            "got {err:?}"
        );
    }

    #[test]
    fn wit_invalid_diagnostic_carries_offending_wit() {
        // Diagnostic-shape pin — the offending `:wit` + `:de` +
        // `:para` + a non-empty reason flow through verbatim so the
        // author can grep their caixa.lisp for the offending contrato
        // block and fix it in one edit. Same shape as
        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
        let err = contrato_wit_err("WASI:HTTP/proxy");
        match err {
            AplicacaoError::ContratoWitInvalid {
                de,
                para,
                wit,
                reason,
            } => {
                assert_eq!(de, "payment");
                assert_eq!(para, "catalog");
                assert_eq!(wit, "WASI:HTTP/proxy");
                assert!(!reason.is_empty(), "reason field must be non-empty");
            }
            other => panic!("expected ContratoWitInvalid, got {other:?}"),
        }
    }

    // ── :contratos :subject value-shape gate ─────────────────────────────
    //
    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
    // suites on the peer payload axes. Until this gate landed
    // `WitContract::target()` only refused the empty string; a
    // structurally invalid subject silently passed validate and the
    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
    // Subject'` on publish / subscribe, or as a silent message drop,
    // far from the source caixa.lisp. Every authoring footgun the
    // NATS server's subject parser would catch on admission now
    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
    // offending `:subject` + `:de` + `:para` named verbatim. Same
    // diagnostic shape as `ContratoEndpointInvalid` /
    // `ContratoWitInvalid` on the peer payload axes; same shared
    // predicate (`crate::render::is_nats_subject`) ensures drift
    // between any two axes' rule enforcement is a build error at the
    // predicate, not piecemeal across renderers.

    fn contrato_subject_err(subject: &str) -> AplicacaoError {
        // Fresh spec per call so the new contract doesn't collide on
        // identity with `three_member_spec`'s pre-existing entries.
        // The new edge uses `(payment, catalog)` — a pair the fixture
        // doesn't already declare — with `:wit "nats:pub-sub"` and the
        // varying `:subject`, so the subject-shape gate fires cleanly
        // after the wit-shape gate (which `"nats:pub-sub"` passes).
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some(subject.into()),
            slot: None,
        });
        s.validate().unwrap_err()
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_whitespace() {
        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
        // landed at the NATS server as a malformed subject the parser
        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
        // source caixa.lisp.
        let err = contrato_subject_err("foo bar");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo bar" && reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_control_char() {
        let err = contrato_subject_err("foo\x01bar");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo\x01bar" && reason.contains("control character")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_non_ascii() {
        // Un-percent-encoded non-ASCII byte — the canonical "I copied
        // the subject from a doc with smart quotes / accented
        // characters" footgun.
        let err = contrato_subject_err("foo.caf\u{e9}");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_leading_dot() {
        // Empty leading token — NATS rejects.
        let err = contrato_subject_err(".foo");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == ".foo" && reason.contains("must not start with `.`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
        // Empty trailing token — NATS rejects. The remediation
        // (use `>` instead) is in the reason string.
        let err = contrato_subject_err("foo.");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo." && reason.contains("must not end with `.`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
        // The canonical "I forgot to fill in the middle segment"
        // typo — `"foo..bar"`. NATS rejects empty tokens.
        let err = contrato_subject_err("foo..bar");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo..bar" && reason.contains("consecutive `.`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
        // as the final segment. Pre-gate this passed as a typed edge
        // and surfaced at runtime as a NATS subscribe rejection.
        let err = contrato_subject_err("foo.>.bar");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
        // `foo*.bar` — NATS wildcards are standalone tokens. The
        // remediation is in the reason string.
        let err = contrato_subject_err("foo*.bar");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_with_invalid_char() {
        // `foo,bar` — comma is not a valid NATS subject character.
        // Pinned separately from the wildcard arms so the invalid-
        // character diagnostic is in force.
        let err = contrato_subject_err("foo,bar");
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == "foo,bar" && reason.contains("invalid character")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_pubsub_contrato_subject_too_long() {
        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
        // The legitimate-shape arms all pass (one all-`a` token, no
        // `.`, no wildcards); only the cap arm fires. Surfaces the
        // paste-from-binary / accidental-multi-line-blob landing
        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
        // on the peer axis.
        let big = "a".repeat(257);
        assert_eq!(big.len(), 257);
        let err = contrato_subject_err(&big);
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
                if subject == &big && reason.contains("max length of 256")),
            "got {err:?}"
        );
    }

    #[test]
    fn pubsub_contrato_subject_max_length_validates() {
        // 256-byte subject — exactly the cap. Boundary pin: drift in
        // the cap surfaces here and at
        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
        // mirroring `http_contrato_endpoint_max_length_validates` and
        // `wit_max_length_validates` on the peer axes.
        let big = "a".repeat(256);
        assert_eq!(big.len(), 256);
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some(big),
            slot: None,
        });
        s.validate().unwrap();
    }

    #[test]
    fn pubsub_contrato_subject_accepts_canonical_forms() {
        // Positive-set sweep: every canonical NATS subject shape the
        // substrate-side `is_nats_subject` predicate accepts (the
        // multi-dot `events.order.charged`, the snake_case / kebab-
        // case / mixed-case tokens, the digit-bearing tokens, the
        // single-token wildcard `*` at every segment position, and
        // the trailing `>` multi-token wildcard) must remain a valid
        // contrato subject too. Drift between this list and the
        // substrate-side `nats_subject_accepts_canonical_forms` sweep
        // surfaces at the shared predicate — one source of truth.
        // Uses a fresh `(payment, catalog)` edge so none of the swept
        // subjects collide with the pre-existing entries in
        // `three_member_spec`.
        for subject in [
            "checkout.events.charge.failed",
            "rio.events.order.charged",
            "orders",
            "orders.123",
            "snake_case.token",
            "kebab-case.token",
            "MixedCase.Token",
            "orders.*.charged",
            "*.events.*",
            "orders.>",
        ] {
            let mut s = three_member_spec();
            s.contratos.push(WitContract {
                de: "payment".into(),
                para: "catalog".into(),
                wit: "nats:pub-sub".into(),
                endpoint: None,
                subject: Some(subject.into()),
                slot: None,
            });
            s.validate()
                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
        }
    }

    #[test]
    fn contrato_subject_empty_takes_precedence_over_invalid() {
        // Ordering pin: `ContratoSubjectEmpty` is the more self-
        // locating diagnostic on `""` and must lead — the value-shape
        // gate is only reached after the empty-check fires. Mirrors
        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
        // the peer payload axis.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some(String::new()),
            slot: None,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
        // Diagnostic-shape pin — the offending `:subject` + `:de` +
        // `:para` + a non-empty reason flow through verbatim so the
        // author can grep their caixa.lisp for the offending contrato
        // block and fix it in one edit. Same shape as
        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
        // and `wit_invalid_diagnostic_carries_offending_wit`.
        let err = contrato_subject_err("foo..bar");
        match err {
            AplicacaoError::ContratoSubjectInvalid {
                de,
                para,
                subject,
                reason,
            } => {
                assert_eq!(de, "payment");
                assert_eq!(para, "catalog");
                assert_eq!(subject, "foo..bar");
                assert!(!reason.is_empty(), "reason field must be non-empty");
            }
            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
        }
    }

    #[test]
    fn target_view_pubsub_subject_passes_through_to_typed_view() {
        // The compounding theorem on the pub-sub axis: every
        // `WitTarget::PubSub { subject }` returned by `target()` carries
        // a NATS-server-accepted subject. Renderers downstream of
        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
        // NATS Stream/Consumer CR emitter, the future `feira app graph`
        // view's subject labeller) can rely on this without re-checking
        // — the type system carries the proof. Mirrors
        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
        // on the peer axes.
        let nats = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("orders.events.*.charged".into()),
            slot: None,
        };
        match nats.target().unwrap() {
            WitTarget::PubSub { subject } => {
                assert_eq!(subject, "orders.events.*.charged");
            }
            other => panic!("expected PubSub, got {other:?}"),
        }
    }

    // ── :contratos :slot value-shape gate ────────────────────────────────
    //
    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
    // (63e18a0) value-shape suites on the peer payload axes. Until this
    // gate landed `WitContract::target()` only refused the empty string
    // for the Store arm; a structurally invalid slot (raw whitespace,
    // control character, non-ASCII byte, paste-from-binary multi-line
    // blob) silently passed validate and surfaced at runtime as a
    // per-backend kv write rejection or a silent next-read corruption,
    // far from the source caixa.lisp with no field naming which
    // `:contratos` edge carried the typo. Every authoring footgun the
    // kv backend intersection-floor would catch on write now becomes a
    // caixa-build-time `ContratoSlotInvalid` with the offending
    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
    // peer payload axes; same shared predicate
    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
    // any two axes' rule enforcement is a build error at the
    // predicate, not piecemeal across renderers. Closes the typed
    // payload-axis value-shape trajectory across all three legs of the
    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).

    fn contrato_slot_err(slot: &str) -> AplicacaoError {
        // Fresh spec per call so the new contract doesn't collide on
        // identity with `three_member_spec`'s pre-existing entries
        // and doesn't close a synchronous cycle the cycle detector
        // would reject before the slot-shape gate fires. The new edge
        // uses `(payment, catalog)` — a pair the fixture doesn't
        // already declare in either direction (the fixture carries
        // `cart -> catalog` and `cart -> payment`, so `payment ->
        // catalog` doesn't form a cycle on the sync subgraph) — with
        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
        // slot-shape gate fires cleanly after the wit-shape gate
        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
        // peer `contrato_subject_err` helper uses (63e18a0).
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some(slot.into()),
        });
        s.validate().unwrap_err()
    }

    #[test]
    fn rejects_store_contrato_slot_with_whitespace() {
        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
        // silently landed at the kv backend with whitespace whose
        // runtime behavior varies unpredictably across backends (etcd
        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
        // rejects on write). Now caught at the source caixa.lisp.
        let err = contrato_slot_err("check out/$order");
        assert!(
            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
                if slot == "check out/$order" && reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_store_contrato_slot_with_tab() {
        // Tab byte arm-pinned separately from the space arm so a
        // future relaxation that admits one but not the other surfaces
        // here.
        let err = contrato_slot_err("check\tout");
        assert!(
            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
                if slot == "check\tout" && reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_store_contrato_slot_with_control_char() {
        // SOH (0x01) — distinct from the whitespace arm. Redis admits
        // and corrupts on RESP protocol framing; DynamoDB rejects on
        // write.
        let err = contrato_slot_err("checkout/\x01order");
        assert!(
            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
                if slot == "checkout/\x01order" && reason.contains("control character")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_store_contrato_slot_with_newline() {
        // Embedded newline — the canonical "the paste-from-binary slug
        // spans multiple lines" footgun. Distinct from the whitespace
        // arm because `\n` is a control character (0x0A).
        let err = contrato_slot_err("checkout\norder");
        assert!(
            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
                if slot == "checkout\norder" && reason.contains("control character")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_store_contrato_slot_with_non_ascii() {
        // Un-percent-encoded non-ASCII byte — the canonical "I copied
        // the slot from a doc with accented characters" footgun. Each
        // kv backend re-encodes non-ASCII differently (etcd preserves
        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
        // rejects), so the typed slot's value set is the intersection-
        // floor every backend admits identically (printable ASCII).
        let err = contrato_slot_err("ch\u{e9}ckout/$order");
        assert!(
            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_store_contrato_slot_too_long() {
        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
        // legitimate-shape arms all pass (a single all-`a` token, no
        // separators); only the cap arm fires. Surfaces the paste-
        // from-binary / accidental-multi-line-blob landing footgun.
        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
        // `rejects_http_contrato_endpoint_too_long` on the peer
        // payload axes.
        let big = "a".repeat(513);
        assert_eq!(big.len(), 513);
        let err = contrato_slot_err(&big);
        assert!(
            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
                if slot == &big && reason.contains("max length of 512")),
            "got {err:?}"
        );
    }

    #[test]
    fn store_contrato_slot_max_length_validates() {
        // 512-byte slot — exactly the cap. Boundary pin: drift in the
        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
        // simultaneously, mirroring
        // `pubsub_contrato_subject_max_length_validates` and
        // `http_contrato_endpoint_max_length_validates` on the peer
        // payload axes.
        let big = "a".repeat(512);
        assert_eq!(big.len(), 512);
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some(big),
        });
        s.validate().unwrap();
    }

    #[test]
    fn store_contrato_slot_accepts_canonical_forms() {
        // Positive-set sweep: every canonical kv slot template the
        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
        // (single-token identifiers, path-namespaced `$`-templates,
        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
        // snake_case / kebab-case / MixedCase tokens, digit-bearing
        // tokens, percent-encoded fragments) must remain valid
        // contrato slots too. Drift between this list and the
        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
        // surfaces at the shared predicate — one source of truth.
        // Uses a fresh `(payment, catalog)` edge so none of the swept
        // slots collide with the pre-existing entries in
        // `three_member_spec`.
        for slot in [
            "checkout",
            "checkout/$orderId",
            "users:{tenant}/{id}",
            "session.<sid>",
            "session.tokens.<sid>",
            "snake_case_key",
            "kebab-case-key",
            "MixedCase",
            "shard0",
            "v2/key",
            "users/caf%C3%A9",
        ] {
            let mut s = three_member_spec();
            s.contratos.push(WitContract {
                de: "payment".into(),
                para: "catalog".into(),
                wit: "wasi:keyvalue/store".into(),
                endpoint: None,
                subject: None,
                slot: Some(slot.into()),
            });
            s.validate()
                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
        }
    }

    #[test]
    fn contrato_slot_empty_takes_precedence_over_invalid() {
        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
        // diagnostic on `""` and must lead — the value-shape gate is
        // only reached after the empty-check fires. Mirrors
        // `contrato_subject_empty_takes_precedence_over_invalid` and
        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
        // the peer payload axes.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "catalog".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some(String::new()),
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
        // Diagnostic-shape pin — the offending `:slot` + `:de` +
        // `:para` + a non-empty reason flow through verbatim so the
        // author can grep their caixa.lisp for the offending contrato
        // block and fix it in one edit. Same shape as
        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
        // on the peer payload axes.
        let err = contrato_slot_err("check out/$order");
        match err {
            AplicacaoError::ContratoSlotInvalid {
                de,
                para,
                slot,
                reason,
            } => {
                assert_eq!(de, "payment");
                assert_eq!(para, "catalog");
                assert_eq!(slot, "check out/$order");
                assert!(!reason.is_empty(), "reason field must be non-empty");
            }
            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
        }
    }

    #[test]
    fn target_view_store_slot_passes_through_to_typed_view() {
        // The compounding theorem on the store axis: every
        // `WitTarget::Store { slot }` returned by `target()` carries a
        // kv-backend-accepted slot template. Renderers downstream of
        // `typed_view()` (the future per-Servico `:capabilities
        // wasi:keyvalue/store` axis emitter, the future `feira app
        // graph` view's slot labeller, the future kv-provider CR
        // materializer) can rely on this without re-checking — the
        // type system carries the proof. Mirrors
        // `target_view_pubsub_subject_passes_through_to_typed_view` on
        // the peer payload axis.
        let store = WitContract {
            de: "a".into(),
            para: "b".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("checkout/$orderId".into()),
        };
        match store.target().unwrap() {
            WitTarget::Store { slot } => {
                assert_eq!(slot, "checkout/$orderId");
            }
            other => panic!("expected Store, got {other:?}"),
        }
    }

    #[test]
    fn rejects_self_loop_in_synchronous_contratos() {
        // A synchronous self-edge (`cart → cart` over HTTP) is now
        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
        // "this edge is degenerate" diagnostic — rather than incidentally
        // by the cycle detector framing it as a `["cart", "cart"]`
        // multi-node deadlock.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("cart", "cart", "/loop"));
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
                assert_eq!(caixa, "cart");
                assert_eq!(wit, "wasi:http/proxy");
            }
            other => panic!("expected ContratoSelfLoop, got {other:?}"),
        }
    }

    #[test]
    fn rejects_self_loop_in_pubsub_contratos() {
        // The cycle detector excludes pub-sub edges (acyclic by
        // construction), so before the explicit gate a `nats:pub-sub`
        // self-edge silently validated and rendered a self-allow CNP.
        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "payment".into(),
            para: "payment".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("rio.events.payment".into()),
            slot: None,
        });
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
                assert_eq!(caixa, "payment");
                assert_eq!(wit, "nats:pub-sub");
            }
            other => panic!("expected ContratoSelfLoop, got {other:?}"),
        }
    }

    #[test]
    fn self_loop_fires_before_payload_shape_check() {
        // The structural "this edge can't exist" error precedes the
        // narrower payload-shape diagnostics: a self-edge carrying an
        // otherwise-malformed endpoint still reports ContratoSelfLoop,
        // not ContratoEndpointInvalid.
        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "cart".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("not-absolute".into()),
            subject: None,
            slot: None,
        });
        match s.validate().unwrap_err() {
            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
            other => panic!("expected ContratoSelfLoop, got {other:?}"),
        }
    }

    #[test]
    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
        // A self-edge naming a non-member reports the more fundamental
        // ContratoMemberMissing first (the member doesn't exist), so the
        // self-loop gate is reached only once both endpoints resolve.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
        match s.validate().unwrap_err() {
            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
            other => panic!("expected ContratoMemberMissing, got {other:?}"),
        }
    }

    #[test]
    fn rejects_two_node_synchronous_cycle() {
        let mut s = three_member_spec();
        // existing edges: cart → catalog, cart → payment
        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
        s.contratos
            .push(contract_http("catalog", "cart", "/refresh"));
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::ContratoCycle { cycle } => {
                // Cycle traversal should mention both endpoints, with
                // the back-edge target appearing as both first and last
                // element to close the loop.
                assert!(cycle.len() >= 3);
                assert_eq!(cycle.first(), cycle.last());
                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
                assert!(body.contains("cart"));
                assert!(body.contains("catalog"));
            }
            other => panic!("expected ContratoCycle, got {other:?}"),
        }
    }

    #[test]
    fn rejects_three_node_synchronous_cycle() {
        let mut s = three_member_spec();
        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
        s.contratos = vec![
            contract_http("catalog", "cart", "/x"),
            contract_http("cart", "payment", "/y"),
            contract_http("payment", "catalog", "/z"),
        ];
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::ContratoCycle { cycle } => {
                assert_eq!(cycle.first(), cycle.last());
                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
                assert_eq!(body.len(), 3);
                assert!(body.contains("cart"));
                assert!(body.contains("catalog"));
                assert!(body.contains("payment"));
            }
            other => panic!("expected ContratoCycle, got {other:?}"),
        }
    }

    #[test]
    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
        // "acyclic by construction" — so a cycle whose closing edge
        // is pub-sub should NOT raise ContratoCycle.
        let mut s = three_member_spec();
        s.contratos = vec![
            contract_http("catalog", "cart", "/x"),
            contract_http("cart", "payment", "/y"),
            // Closing edge is pub-sub — async; not a sync deadlock.
            WitContract {
                de: "payment".into(),
                para: "catalog".into(),
                wit: "nats:pub-sub".into(),
                endpoint: None,
                subject: Some("checkout.events.charge.completed".into()),
                slot: None,
            },
        ];
        s.validate().expect("pub-sub edge breaks the sync cycle");
    }

    #[test]
    fn store_edge_counts_as_synchronous_for_cycle_detection() {
        // wasi:keyvalue/store is request/response; a cycle through one
        // *is* a sync deadlock, just like HTTP.
        let mut s = three_member_spec();
        s.contratos = vec![
            contract_http("catalog", "cart", "/x"),
            WitContract {
                de: "cart".into(),
                para: "catalog".into(),
                wit: "wasi:keyvalue/store".into(),
                endpoint: None,
                subject: None,
                slot: Some("session/$id".into()),
            },
        ];
        let err = s.validate().unwrap_err();
        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
    }

    #[test]
    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
        // Capability-only edges (unknown WIT shape, no payload) default
        // to synchronous — safer; authors with truly async capability
        // semantics can model them as pub-sub explicitly.
        let mut s = three_member_spec();
        s.contratos = vec![
            contract_http("catalog", "cart", "/x"),
            WitContract {
                de: "cart".into(),
                para: "catalog".into(),
                wit: "custom:exchange".into(),
                endpoint: None,
                subject: None,
                slot: None,
            },
        ];
        let err = s.validate().unwrap_err();
        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
    }

    #[test]
    fn long_acyclic_chain_validates() {
        // A long sync chain (no back-edges) must validate even when
        // every node is reachable from the first.
        let mut s = three_member_spec();
        s.membros = vec![
            membro("a", "^0.1"),
            membro("b", "^0.1"),
            membro("c", "^0.1"),
            membro("d", "^0.1"),
            membro("e", "^0.1"),
        ];
        s.contratos = vec![
            contract_http("a", "b", "/1"),
            contract_http("b", "c", "/2"),
            contract_http("c", "d", "/3"),
            contract_http("d", "e", "/4"),
        ];
        s.entrada.as_mut().unwrap().para = "a".into();
        s.validate().unwrap();
    }

    #[test]
    fn diamond_acyclic_validates() {
        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
        let mut s = three_member_spec();
        s.membros = vec![
            membro("a", "^0.1"),
            membro("b", "^0.1"),
            membro("c", "^0.1"),
            membro("d", "^0.1"),
        ];
        s.contratos = vec![
            contract_http("a", "b", "/1"),
            contract_http("a", "c", "/2"),
            contract_http("b", "d", "/3"),
            contract_http("c", "d", "/4"),
        ];
        s.entrada.as_mut().unwrap().para = "a".into();
        s.validate().unwrap();
    }

    // ── duplicate-`:contratos` build-error gate ──────────────────────────

    #[test]
    fn rejects_duplicate_http_contrato() {
        // Fail-before-pass-after pin: the fixture's `cart → catalog`
        // HTTP edge appears once. Push an identical entry — same
        // (de, para, wit, endpoint) — and validate() must reject it.
        // Until this gate landed the typed surface accepted the
        // duplicate silently and caixa-mesh's `cilium_network_policies`
        // emitted two ``CiliumNetworkPolicy`` objects with identical
        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
        // admission rejects on `kubectl apply` far from the source.
        let mut s = three_member_spec();
        s.contratos
            .push(contract_http("cart", "catalog", "/products/:id"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_duplicate_pubsub_contrato() {
        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
        // edges with identical (de, para, subject) are degenerate;
        // pin that the typed surface refuses both at validate time.
        let mut s = three_member_spec();
        let pubsub = WitContract {
            de: "payment".into(),
            para: "cart".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("checkout.events.charge.failed".into()),
            slot: None,
        };
        s.contratos.push(pubsub.clone());
        s.contratos.push(pubsub);
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_duplicate_store_contrato() {
        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
        // edges with identical (de, para, slot) collapse to one mesh-
        // policy edge; pin the build error.
        let mut s = three_member_spec();
        let store = WitContract {
            de: "cart".into(),
            para: "payment".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("checkout/$orderId".into()),
        };
        // Drop the conflicting HTTP `cart → payment` edge from the
        // fixture so the duplicate-store pair is the only one
        // distinguishable on this pair.
        s.contratos
            .retain(|c| !(c.de == "cart" && c.para == "payment"));
        s.contratos.push(store.clone());
        s.contratos.push(store);
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_duplicate_capability_contrato() {
        // Same gate on the pure-capability axis (no payload selector).
        // Two contracts with identical (de, para, wit) and no
        // endpoint/subject/slot are duplicate edges; pin so a future
        // `target_label` change can't accidentally collapse the
        // capability arm into a None-shaped key that compares equal
        // to a populated one.
        let mut s = three_member_spec();
        let capability = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "pleme:cap/audit".into(),
            endpoint: None,
            subject: None,
            slot: None,
        };
        s.contratos.push(capability.clone());
        s.contratos.push(capability);
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::ContratoDuplicate {
                de,
                para,
                wit,
                target,
            } => {
                assert_eq!(de, "cart");
                assert_eq!(para, "catalog");
                assert_eq!(wit, "pleme:cap/audit");
                assert!(
                    target.contains("capability"),
                    "capability-edge duplicate diagnostic must surface the \
                     no-payload shape (got target = {target:?})"
                );
            }
            other => panic!("expected ContratoDuplicate, got {other:?}"),
        }
    }

    #[test]
    fn accepts_distinct_http_paths_between_same_pair() {
        // Negative pin: two HTTP contracts cart → catalog at distinct
        // endpoints (`/products/:id` and `/search`) are *not*
        // duplicates — they're distinct typed edges differing on the
        // payload axis. The duplicate-gate must not over-match here,
        // since the cart-calls-catalog-on-multiple-paths shape is the
        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
        // example: cart calls catalog at /products/:id, payment at
        // /charge — same shape extends to two paths on one para).
        let mut s = three_member_spec();
        s.contratos
            .push(contract_http("cart", "catalog", "/search"));
        s.validate()
            .expect("distinct endpoints between same (de, para) must validate");
    }

    #[test]
    fn accepts_same_endpoint_on_different_pairs() {
        // Negative pin: the same `/charge` endpoint reused on two
        // different (de, para) pairs is two distinct edges, not a
        // duplicate. Pinning this shape so the gate's identity key
        // includes both `de` and `para` (not just `(wit, endpoint)`).
        let mut s = three_member_spec();
        s.contratos
            .push(contract_http("payment", "catalog", "/charge"));
        s.validate()
            .expect("same endpoint reused on distinct (de, para) must validate");
    }

    #[test]
    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
        // Pin the diagnostic shape: the duplicate-edge error names
        // *which* target field carried the conflict, so the author
        // doesn't have to re-grep the source caixa.lisp to find it.
        // Same self-locating diagnostic discipline as
        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
        let mut s = three_member_spec();
        s.contratos
            .push(contract_http("cart", "catalog", "/products/:id"));
        let err = s.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("\"/products/:id\""),
            "duplicate-contrato diagnostic must name the offending \
             :endpoint payload (got: {msg:?})"
        );
        assert!(
            msg.contains("cart") && msg.contains("catalog"),
            "diagnostic must name both endpoints of the duplicate edge \
             (got: {msg:?})"
        );
    }

    #[test]
    fn duplicate_contrato_gate_runs_after_membership_check() {
        // Order pin: a duplicate contract whose `:de` is *also* not in
        // `:membros` surfaces the membership error first — the
        // missing-member diagnostic is more locating than the
        // duplicate-edge one (the author has to fix the membership
        // before the duplicate is meaningful). Same ordering
        // discipline as `membros_validation_runs_before_contratos_membership_check`.
        let mut s = three_member_spec();
        s.contratos.push(contract_http("phantom", "catalog", "/x"));
        s.contratos.push(contract_http("phantom", "catalog", "/x"));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
            "membership-missing must fire before duplicate-edge (got {err:?})"
        );
    }

    #[test]
    fn duplicate_contrato_gate_runs_after_target_shape_check() {
        // Order pin: a contract with a malformed target (e.g. an HTTP
        // wit world with an empty :endpoint) surfaces the target-shape
        // error first, not the duplicate one. Even when two such
        // malformed entries are identical, the per-contract `target()`
        // check fires inside the loop *before* the duplicate-key
        // insert, so the diagnostic remains the most-locating one.
        let mut s = three_member_spec();
        let malformed = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some(String::new()),
            subject: None,
            slot: None,
        };
        s.contratos.push(malformed.clone());
        s.contratos.push(malformed);
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
            "endpoint-empty must fire before duplicate-edge (got {err:?})"
        );
    }

    #[test]
    fn wit_target_label_pins_per_variant_format() {
        // Label format is the single source of truth every duplicate-
        // `:contratos` diagnostic + every future `feira app graph`
        // consumer routes through. Pin the shape per variant so a
        // future edit to `WitTarget::label` (e.g. a JSON emitter that
        // strips the leading `:`, or a rename from `endpoint` →
        // `path`) surfaces as a red-red test rather than as a silent
        // downstream diagnostic drift. Together with the exhaustive
        // `match` on `WitTarget` inside `label()`, adding a future
        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
        // peer, per-edge WIT registry variants) is a compile error at
        // the label site — not a fall-through into the `Capability`
        // "no payload" default the prior raw-field-probe helper
        // silently landed on.
        assert_eq!(
            WitTarget::Http {
                endpoint: "/charge",
            }
            .label(),
            "\
:endpoint \"/charge\""
        );
        assert_eq!(
            WitTarget::PubSub {
                subject: "events.checkout.paid",
            }
            .label(),
            "\
:subject \"events.checkout.paid\""
        );
        assert_eq!(
            WitTarget::Store {
                slot: "checkout/$order",
            }
            .label(),
            "\
:slot \"checkout/$order\""
        );
        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
        // Capability-arm label routes through the lifted
        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
        // declaration per arm, next to the variant" discipline the
        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
        // consts already carry extends to the payload-less arm; the
        // byte-string equality pin below plus this label-routes-
        // through-the-const pin make a future rebrand on either the
        // const declaration or the `label()` template a build error
        // here rather than a downstream consumer surprise.
        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
    }

    #[test]
    fn wit_target_display_routes_through_label_helper() {
        // Fail-before-pass-after pin on the fourth (and only remaining)
        // typed-shape-discriminator axis to converge onto the
        // three-path-convergence discipline the sibling M3
        // [`PlacementStrategy`] (0a2f653) and M2
        // [`crate::supervisor::RestartStrategy`] /
        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
        // through [`WitTarget::label`], so every consumer reaching for
        // `format!("{v}")` on a typed payload target lands on the same
        // stable author-facing byte-string [`WitTarget::label`] returns
        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
        // `:contratos` gate seeds via [`WitTarget::label`] at
        // aplicacao.rs:5491 already threads through.
        //
        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
        // through to the `Debug` derive's structural output
        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
        // rather than the [`WitTarget::label`] helper's stable byte-
        // string (`:endpoint "/charge"` — the author-facing `:contratos`
        // keyword form). Every future consumer that reaches for
        // `format!("{target}")` — the canonical shape every user-facing
        // pretty-print site on the sibling typed-enum axes
        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
        // [`crate::supervisor::RestartPolicy`]) already uses — would
        // silently land under a different byte-string than the
        // [`WitTarget::label`] callers that the duplicate-`:contratos`
        // diagnostic already threads through, with the mismatch
        // surfacing as a downstream diagnostic / graph / audit line
        // reading one spelling while the substrate's own gate emitted
        // another.
        //
        // Pin the routing here so a future
        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
        // that hand-rolls the per-arm formatting instead of delegating
        // to [`WitTarget::label`] fails at caixa-core build time.
        for variant in [
            WitTarget::Http {
                endpoint: "/charge",
            },
            WitTarget::PubSub {
                subject: "events.checkout.paid",
            },
            WitTarget::Store {
                slot: "checkout/$order",
            },
            WitTarget::Capability,
        ] {
            assert_eq!(
                variant.to_string(),
                variant.label(),
                "WitTarget::{variant:?} Display must route through \
                 WitTarget::label (single source of truth: the lifted \
                 payload_pair 4-arm dispatch the label helper already \
                 threads through)"
            );
        }
    }

    #[test]
    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
        // Consumer-side pin on the three-path convergence:
        // [`std::fmt::Display`] agrees byte-for-byte with the
        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
        // Pre-lift the two paths were structurally independent — the
        // substrate-side gate reached for `target_view.label()` while a
        // future downstream diagnostic / graph / audit line reaching
        // for `format!("{target}")` would silently land on the `Debug`
        // derive's structural output. Pin the two paths byte-for-byte
        // here so any future variant addition (M4 `Rest`/`Grpc` split
        // of [`WitTarget::Http`], `Queue`-shaped peer of
        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
        // match error at [`WitTarget::payload_pair`] rather than a
        // silent per-consumer dispatch miss.
        for variant in [
            WitTarget::Http {
                endpoint: "/charge",
            },
            WitTarget::PubSub {
                subject: "events.checkout.paid",
            },
            WitTarget::Store {
                slot: "checkout/$order",
            },
            WitTarget::Capability,
        ] {
            assert_eq!(
                format!("{variant}"),
                variant.label(),
                "WitTarget::{variant:?} Display byte-string must match \
                 the AplicacaoError::ContratoDuplicate `target:` carrier \
                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
                 seeds via WitTarget::label — three-path convergence: \
                 Display + label + payload_pair all resolve to the same \
                 per-arm byte-string"
            );
        }
    }

    #[test]
    fn wit_target_payload_pair_pins_per_variant() {
        // Pin the per-arm `(field-name, payload)` pair single-sourced
        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
        // and [`WitTarget::field_name`] (returns the first component)
        // route through. Until this lift landed [`WitTarget::label`]
        // dispatched on the same three arms with a per-arm
        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
        // paired [`WitTarget::HTTP_FIELD_NAME`] /
        // [`WitTarget::PUBSUB_FIELD_NAME`] /
        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
        // canonical "same shape, written N times" duplication
        // THEORY.md §I.3.5 promotes to a build-time concern. A future
        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
        // [`WitTarget::Http`], `Queue`-shaped peer of
        // [`WitTarget::Store`]) is one match-arm edit at
        // [`WitTarget::payload_pair`], visible here as a compile-time
        // exhaustiveness error on both this pin and the label-format
        // pin above.
        assert_eq!(
            WitTarget::Http {
                endpoint: "/charge"
            }
            .payload_pair(),
            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
        );
        assert_eq!(
            WitTarget::PubSub {
                subject: "events.x",
            }
            .payload_pair(),
            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
        );
        assert_eq!(
            WitTarget::Store {
                slot: "checkout/$order",
            }
            .payload_pair(),
            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
        );
        assert_eq!(WitTarget::Capability.payload_pair(), None);
    }

    #[test]
    fn wit_target_field_name_pins_per_variant() {
        // Pin the per-arm author-facing `:contratos` payload field
        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
        // + returned by [`WitTarget::field_name`]. Every downstream
        // consumer (the [`WitContract::target`] gate's `expected:`
        // scalar, the [`WitTarget::label`] template's keyword prefix,
        // the `feira app graph` verb's `endpoint=…` prefix) routes
        // through the same three peer consts, so a rename on the
        // author-surface `(defcaixa … :contratos ((:de … :para …
        // :wit … :endpoint …)))` field lands in exactly one place.
        assert_eq!(
            WitTarget::Http {
                endpoint: "/charge"
            }
            .field_name(),
            Some(WitTarget::HTTP_FIELD_NAME),
        );
        assert_eq!(
            WitTarget::PubSub {
                subject: "events.x",
            }
            .field_name(),
            Some(WitTarget::PUBSUB_FIELD_NAME),
        );
        assert_eq!(
            WitTarget::Store {
                slot: "checkout/$order",
            }
            .field_name(),
            Some(WitTarget::STORE_FIELD_NAME),
        );
        // Capability arm carries no payload field — the diagnostic
        // never reports `expected: "capability"` because the gate's
        // Capability arm accepts no payload at all (it fires the
        // "expected: none" WrongTarget error instead), so the field-
        // name method returns None here rather than a placeholder.
        assert_eq!(WitTarget::Capability.field_name(), None);

        // Peer const scalar values pinned so a rename on either side
        // (author-surface field name in the `(defcaixa …)` DSL, or
        // the diagnostic's `expected:` scalar) can't drift without
        // failing here first.
        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
    }

    #[test]
    fn wit_target_field_names_are_pairwise_distinct() {
        // Distinctness pin: if any two of the three payload-field-name
        // scalars ever collapse (e.g. an accidental `endpoint` copy-
        // paste over the `subject` const), the [`WitContract::target`]
        // gate's diagnostic would point authors at the wrong field —
        // an "expected `:endpoint`" error on a pub-sub edge would
        // silently misroute the fix. Same cross-axis-distinctness
        // discipline as the peer M3 `:placement :estrategia` variant-
        // discriminator scalar-value pins (cc8f749) applied to the
        // payload-field-name axis.
        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
    }

    #[test]
    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
        // 4-way distinctness pin extending the sibling
        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
        // (which covers only the HTTP / PubSub / Store payload arms)
        // onto the fourth scalar the shared
        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
        // (`"none"`), the payload-less Capability-arm rejection scalar.
        //
        // All four [`WitTarget::HTTP_FIELD_NAME`] /
        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
        // dispatch surface [`WitContract::target`] writes onto the
        // `ContratoWrongTarget::expected` field — the same `&'static
        // str` axis authors read as "this WIT world's shape admits
        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
        // downstream consumers rely on: an `expected: "endpoint"`
        // diagnostic on a Capability-shaped edge tells the author to
        // add a `:endpoint "…"` slot to a WIT world that admits none,
        // silently misrouting the fix. Until this pin landed the three
        // payload-arm consts were distinctness-guarded by the sibling
        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
        // author-facing vocabulary shift from `"none"` to `"endpoint"`
        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
        // into per-shape peers) would have silently landed one
        // Capability-arm rejection on a payload-arm's `expected:` byte-
        // string and desynchronized the diagnostic from the author's
        // typed shape.
        //
        // Same 4-way pairwise-distinctness pin discipline as the peer
        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
        // (cc8f749) applies on the sibling M3 closed-set typed-enum
        // scalar-value dispatch axis; extends the pin trajectory the
        // sibling `wit_target_field_names_are_pairwise_distinct`
        // 3-way pin opened to cover the last unguarded corner on the
        // `ContratoWrongTarget::expected` scalar-value axis.
        //
        // Fail-before-pass-after locally verified by mutating
        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
        // — this pin fires as expected; restoring passes.
        let all = [
            WitTarget::HTTP_FIELD_NAME,
            WitTarget::PUBSUB_FIELD_NAME,
            WitTarget::STORE_FIELD_NAME,
            WitTarget::CAPABILITY_EXPECTED,
        ];
        for (i, a) in all.iter().enumerate() {
            for (j, b) in all.iter().enumerate() {
                if i != j {
                    assert_ne!(
                        a, b,
                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
                         pairwise distinct — got duplicate {a:?} at indices \
                         {i} and {j}; all four scalars thread through the \
                         shared `AplicacaoError::ContratoWrongTarget::expected` \
                         &'static str axis, so a collapse silently misdirects \
                         the diagnostic on which typed shape the WIT world admits",
                    );
                }
            }
        }
    }

    #[test]
    fn wit_target_is_variant_predicates_partition_the_arm_set() {
        // Fail-before-pass-after pin on the
        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
        // each of the four variants exactly one of the generated
        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
        // predicates returns `true` and the other three return
        // `false`. Prior to this derive the only production
        // arm-discriminator on [`WitTarget`] — the sync-cycle
        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
        // the variant that expressed no compile-time link back to
        // the closed-set typed dispatch a future fifth
        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
        // split of [`WitTarget::PubSub`] into shape-specific peers,
        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
        // to thread through in lockstep or the DFS exclusion would
        // silently disagree with the peer diagnostic templates on
        // which arms carry sync-versus-async semantics. Peer of the
        // sibling [`crate::CaixaKind`] (f5bba80),
        // [`PlacementStrategy`] (766ec63),
        // [`crate::supervisor::RestartStrategy`],
        // [`crate::supervisor::RestartPolicy`], and
        // [`crate::upgrade::UpgradeInstruction`] (915a934)
        // `IsVariant` derives on the sibling closed-set typed-enum
        // discriminator axes — extends the same one-typed-dispatch-
        // per-variant discipline onto the last unlifted closed-set
        // typed-enum discriminator on the caixa surface (the M3
        // mesh-slot per-`:contratos` target-arm axis), closing the
        // arm-discriminator convergence trajectory across every
        // closed-set typed enum in caixa-core.
        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
            (
                WitTarget::Http { endpoint: "/x" },
                [true, false, false, false],
            ),
            (
                WitTarget::PubSub {
                    subject: "events.x",
                },
                [false, true, false, false],
            ),
            (
                WitTarget::Store { slot: "kv/x" },
                [false, false, true, false],
            ),
            (WitTarget::Capability, [false, false, false, true]),
        ];
        for (variant, expected) in rows {
            let observed = [
                variant.is_http(),
                variant.is_pubsub(),
                variant.is_store(),
                variant.is_capability(),
            ];
            assert_eq!(
                observed, expected,
                "WitTarget::{variant:?} is_* predicates must partition \
                 the arm set (http, pubsub, store, capability); got {observed:?}"
            );
        }
    }

    #[test]
    fn wit_target_is_variant_predicates_are_const_fn() {
        // The [`gen_platform::IsVariant`] derive emits `const fn`
        // predicates on the peer [`crate::CaixaKind`] +
        // [`crate::upgrade::UpgradeInstruction`] +
        // [`crate::supervisor::RestartStrategy`] +
        // [`crate::supervisor::RestartPolicy`] +
        // [`PlacementStrategy`] closed-set typed enums — pin the
        // same posture on [`WitTarget`] so a future accidental
        // downgrade to non-`const` (an added runtime helper reachable
        // only from a non-`const` context, a manual hand-rolled
        // `impl` that shadows the derive-generated method) trips at
        // caixa-core build time rather than surfacing as a downstream
        // `const`-context regression far from the derive declaration.
        //
        // Unlike the peer unit-variant enums (`CaixaKind` /
        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
        // whose `const` constructors need no arguments, the three
        // payload-carrying [`WitTarget`] arms are const-constructed
        // through `&'static str` payloads — the same `'static`
        // lifetime the closed-set typed enum's four-arm partition
        // pin above already threads through.
        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
        const IS_HTTP: bool = HTTP.is_http();
        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
        const IS_STORE: bool = STORE.is_store();
        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
        assert!(IS_HTTP);
        assert!(IS_PUBSUB);
        assert!(IS_STORE);
        assert!(IS_CAPABILITY);
    }

    #[test]
    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
        // Consumer-side pin on the sole production converge site:
        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
        // edges from the synchronous-subgraph DFS via the lifted
        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
        // predicate (rebound from the prior raw
        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
        // variant). Byte-equivalent today (`is_pubsub` is the
        // derive-generated `matches!(self, Self::PubSub { .. })` by
        // construction, the `#[is_variant(name = "pubsub")]` override
        // aliasing the auto-derived `is_pub_sub` back to the sibling
        // [`WitContract::is_pubsub`] name); pin the behavior so a
        // future accidental drift (a rebind onto a peer arm
        // predicate, a manual hand-rolled `impl` that shadows the
        // derive-generated method with different semantics, a peer
        // arm rename that shifts which variant carries sync-versus-
        // async semantics) trips at caixa-core test time rather than
        // at some downstream operator's runtime dispatch far from the
        // rebind commit.
        //
        // The fixture constructs a two-Servico Aplicacao with one
        // pub-sub edge that would close a sync-cycle if the DFS did
        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
        // edge, which is not a cycle. A regression in the converge
        // (a rebind that reads the pub-sub arm as sync) would report
        // `AplicacaoError::ContratoCycle`.
        let s = AplicacaoSpec {
            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
            contratos: vec![
                // Pub-sub edge: DFS must skip via is_pubsub().
                WitContract {
                    de: "a".into(),
                    para: "b".into(),
                    wit: "nats:pub-sub".into(),
                    endpoint: None,
                    subject: Some("events.x".into()),
                    slot: None,
                },
                // HTTP edge: DFS must include.
                WitContract {
                    de: "b".into(),
                    para: "a".into(),
                    wit: "wasi:http/proxy".into(),
                    endpoint: Some("/x".into()),
                    subject: None,
                    slot: None,
                },
            ],
            politicas: MeshPolicy::default(),
            placement: Placement {
                estrategia: PlacementStrategy::Replicated,
                clusters: vec!["rio".into()],
                affinity: None,
                shard_key: None,
            },
            entrada: None,
        };
        s.validate()
            .expect("pub-sub edge must be excluded from sync-cycle DFS");
    }

    #[test]
    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
        // Consumer-side pin: the same three peer consts thread through
        // both the [`WitTarget::label`] template (leading-`:` keyword
        // prefix in the duplicate-`:contratos` diagnostic) and the
        // [`WitContract::target`] gate's [`AplicacaoError::
        // ContratoMissingTarget`] `expected:` scalar (the field the
        // author needs to add). Pin both routes at once so a future
        // refactor can't accidentally split them onto separate string
        // literals — the "one place, everywhere reaches for it"
        // invariant the peer const set carries.
        let http_label = WitTarget::Http { endpoint: "/x" }.label();
        assert!(
            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
            "label must lead with :{} keyword (got {http_label:?})",
            WitTarget::HTTP_FIELD_NAME,
        );

        let mut s = three_member_spec();
        s.contratos.push(WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "kafka:topic".into(),
            endpoint: None,
            subject: None,
            slot: None,
        });
        match s.validate().unwrap_err() {
            AplicacaoError::ContratoMissingTarget { expected, .. } => {
                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
            }
            other => panic!("expected ContratoMissingTarget, got {other:?}"),
        }
    }

    #[test]
    fn duplicate_pubsub_diagnostic_names_offending_subject() {
        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
        // on the pub-sub target axis: the duplicate-edge diagnostic
        // must name the `:subject` payload verbatim (not just the
        // `(de, para, wit)` triple). Prior to lifting the label onto
        // [`WitTarget::label`] the diagnostic derived the label from
        // raw [`WitContract`] `Option<String>` probes — a future
        // `WitTarget` variant addition (M4 per-edge WIT registry)
        // would silently fall through to the `Capability` "no
        // payload" default without a compiler warning. Pinning the
        // pub-sub arm's format closes the second of three
        // payload-carrying `WitTarget` arms this diagnostic threads
        // through.
        let mut s = three_member_spec();
        let pubsub = WitContract {
            de: "payment".into(),
            para: "cart".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("events.checkout.paid".into()),
            slot: None,
        };
        s.contratos.push(pubsub.clone());
        s.contratos.push(pubsub);
        let err = s.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains(":subject \"events.checkout.paid\""),
            "duplicate-pubsub diagnostic must name the offending \
             :subject payload (got: {msg:?})"
        );
    }

    #[test]
    fn duplicate_store_diagnostic_names_offending_slot() {
        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
        // key-value target axis: the diagnostic must name the `:slot`
        // payload verbatim. Third of three payload-carrying
        // `WitTarget` arms this diagnostic threads through, closing
        // the per-arm label pin trilogy (`Http` — 6841,
        // `PubSub` + `Store` — this test + peer above).
        let mut s = three_member_spec();
        let store = WitContract {
            de: "cart".into(),
            para: "payment".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("checkout/$orderId".into()),
        };
        s.contratos
            .retain(|c| !(c.de == "cart" && c.para == "payment"));
        s.contratos.push(store.clone());
        s.contratos.push(store);
        let err = s.validate().unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains(":slot \"checkout/$orderId\""),
            "duplicate-store diagnostic must name the offending :slot \
             payload (got: {msg:?})"
        );
    }

    #[test]
    fn rejects_entrada_path_without_leading_slash() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_empty_entrada_path() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
    }

    #[test]
    fn rejects_duplicate_entrada_paths() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec![
            "/api/cart".into(),
            "/api/products".into(),
            "/api/cart".into(),
        ];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_zero_entrada_port() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().port = 0;
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
    }

    // ── :entrada :paths value-shape gate ─────────────────────────────
    //
    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
    // time now becomes a caixa-build-time `EntradaPathInvalid` with
    // the offending `:paths` entry named verbatim.

    #[test]
    fn rejects_entrada_path_with_query() {
        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
        // silently passed validate and the Gateway API webhook
        // rejected it at apply time with no source citation.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_fragment() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_space() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/my cart" && reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_tab() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/\tcart" && reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_control_char() {
        // 0x01 (SOH) — a non-whitespace control char surfaces the
        // distinct "control character" reason arm, separate from
        // the whitespace arm. Pinned so a future refactor that
        // collapses the two arms can't accidentally drop the more
        // self-locating diagnostic.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/\x01cart" && reason.contains("control character")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_non_ascii() {
        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
        // unreserved-set rule rejects. The Gateway API webhook
        // rejects literal non-ASCII bytes; percent-encoding is the
        // only way to author non-ASCII in a path.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/café" && reason.contains("non-ASCII")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_consecutive_slashes() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api//cart" && reason.contains("consecutive `/`")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_dot_segment() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/./cart" && reason.contains("`.` segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_trailing_dot_segment() {
        // The bare `/.` and the trailing `/foo/.` are both rejected
        // by the Gateway API webhook; pinned separately so a future
        // narrowing that catches only the inner form surfaces here.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/." && reason.contains("`.` segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_parent_segment() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_with_trailing_parent_segment() {
        // Trailing `/..` — symmetric arm of the parent-segment rule,
        // pinned separately so a future relaxation that only checks
        // the inner form (`/../`) surfaces here.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/.." && reason.contains("`..` parent-segment")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_path_too_long() {
        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
        // ASCII-alphanumeric body so only the length rule fires.
        let mut s = three_member_spec();
        let big = format!("/api/{}", "a".repeat(1020));
        assert_eq!(big.len(), 1025);
        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == &big && reason.contains("max length of 1024")),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_path_max_length_validates() {
        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
        // maxLength cap. Boundary pin: drift in the cap surfaces here
        // and at `rejects_entrada_path_too_long` simultaneously.
        let mut s = three_member_spec();
        let big = format!("/api/{}", "a".repeat(1019));
        assert_eq!(big.len(), 1024);
        s.entrada.as_mut().unwrap().paths = vec![big];
        s.validate().unwrap();
    }

    #[test]
    fn entrada_accepts_canonical_paths() {
        // Positive-control sweep — every form the Gateway API
        // apiserver accepts must round-trip through validate. Covers
        // the root catch-all, plain paths, dot-prefixed segments
        // (hidden-file-style, distinct from `.` and `..` segments
        // which are rejected), digit-bearing segments, the canonical
        // route-template `:param` form (`:` is RFC 3986 reserved-set
        // valid in paths), trailing-slash form, percent-encoded
        // segments, and an interior `..` *substring* (`/foo..bar` is
        // not the `..` segment and is allowed).
        for path in [
            "/",
            "/api/cart",
            "/healthz",
            "/api/.config",
            "/v1/products",
            "/products/:id",
            "/api/cart/",
            "/api/caf%C3%A9",
            "/foo..bar",
            "/...",
        ] {
            let mut s = three_member_spec();
            s.entrada.as_mut().unwrap().paths = vec![path.into()];
            s.validate()
                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
        }
    }

    #[test]
    fn entrada_path_empty_takes_precedence_over_invalid() {
        // Ordering pin: `EntradaPathEmpty` is the more self-locating
        // diagnostic on `""` and must lead — `validate_entrada_path`
        // is only reached after the empty-check fires at the call
        // site. (The predicate itself defends against direct
        // invocation by returning the same error on `""`.)
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["".into()];
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
    }

    #[test]
    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
        // Ordering pin: a path without a leading `/` surfaces the
        // narrower `EntradaPathNotAbsolute` diagnostic first; the
        // value-shape gate is only consulted on paths that already
        // satisfy the absolute-prefix invariant.
        let mut s = three_member_spec();
        // `bad path` would fire the whitespace rule under the
        // value-shape gate, but missing-leading-`/` is the more
        // self-locating diagnostic.
        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_path_invalid_fires_before_duplicate_check() {
        // Ordering pin: a malformed path on the *first* entry of a
        // would-be duplicate pair fires the value-shape gate before
        // the duplicate gate, mirroring the
        // `placement_cluster_invalid_fires_before_duplicate_check`
        // (6cbb900) pattern on the peer axis.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_path_diagnostic_carries_offending_path() {
        // Diagnostic-shape pin — the offending path + a non-empty
        // reason flow through verbatim so the author can grep their
        // caixa.lisp for `:paths` and fix it in one edit. Same shape
        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::EntradaPathInvalid { path, reason } => {
                assert_eq!(path, "/api?q=1");
                assert!(!reason.is_empty(), "reason field must be non-empty");
            }
            other => panic!("expected EntradaPathInvalid, got {other:?}"),
        }
    }

    #[test]
    fn rejects_entrada_path_with_curly_brace_template_form() {
        // Per-axis pin on the shared `is_gateway_api_http_path`
        // reserved-byte arm: the canonical "I wrote an OpenAPI
        // path-template `{id}` instead of the Gateway API `:id` form"
        // footgun the K8s apiserver would otherwise catch at admission
        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
        // landing site, far from the caixa.lisp. Surfaces as
        // `EntradaPathInvalid` carrying the offending path verbatim
        // plus the canonical `%7B`/`%7D` percent-encoding remediation
        // — the substrate-side `gateway_api_http_path_rejects_every_
        // reserved_printable_ascii_byte` predicate-level sweep pins the
        // full eleven-byte set; this per-axis pin confirms the
        // diagnostic flows through to the `EntradaPathInvalid` variant.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
                if path == "/api/cart/{id}"
                    && reason.contains("reserved character")
                    && reason.contains("'{'")
                    && reason.contains("%7B")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
        // template_form` on the sibling `:contratos :endpoint` axis.
        // Same shared `is_gateway_api_http_path` reserved-byte arm
        // fires through `ContratoEndpointInvalid`, with the offending
        // endpoint + `:de` + `:para` + reason flowing through verbatim.
        // Pins that the lifted predicate's tightening lands on both
        // caller axes simultaneously — one source of truth for the
        // Gateway API HTTPPathMatch.value accepted set.
        let err = contrato_endpoint_err("/api/cart/{id}");
        assert!(
            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
                if endpoint == "/api/cart/{id}"
                    && reason.contains("reserved character")
                    && reason.contains("'{'")
                    && reason.contains("%7B")),
            "got {err:?}"
        );
    }

    // ── :entrada :host value-shape gate ──────────────────────────────
    //
    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
    // the sibling `:host` axis. Every authoring footgun the K8s
    // Gateway API v1 apiserver would catch at admission time becomes
    // a caixa-build-time `EntradaHostInvalid` with the offending
    // `:host` named verbatim. Same diagnostic shape as
    // `MembroVersaoInvalid` (9888b13).

    #[test]
    fn rejects_entrada_host_with_scheme() {
        // Fail-before-pass-after pin — pre-gate codebases silently
        // accepted `https://…` and the apiserver rejected it at apply
        // time with no source citation.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
                if host == "https://checkout.quero.cloud"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_port() {
        // The `:8080` port suffix is the canonical "I forgot the port
        // belongs in `:entrada :port`" footgun. The top-level `:` arm
        // (introduced after the per-label loop-only impl silently
        // surfaced a deep "label \"cloud:8080\" contains invalid
        // character ':'" leak) names the canonical fix verbatim — the
        // `:entrada :port` slot.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
                if host == "checkout.quero.cloud:8080"
                && reason.contains(":entrada :port")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_trailing_colon() {
        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
        // edit) — the per-label loop would land it as a deep
        // "label \"com:\" must start and end with an alphanumeric"
        // / "contains invalid character ':'" leak. The top-level
        // `:` arm pre-empts with the canonical `:port` slot
        // diagnostic.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
                if host == "checkout.quero.cloud:"
                && reason.contains(":entrada :port")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_unbracketed_ipv6_literal() {
        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
        // literals across the board (peer with `rejects_entrada_host_
        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
        // Before this top-level `:` arm landed the per-label loop
        // surfaced a single-label byte-class diagnostic that named the
        // `:` byte but not the IP-literal prohibition. The top-level
        // `:` arm names both the `:port` slot and the IP-literal
        // prohibition verbatim, so an author whose `:host "2001:..."`
        // value lands here gets a self-locating fix either way.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
                if host == "2001:db8::1"
                && reason.contains("IPv6")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_wildcard_with_port() {
        // Wildcard host with port suffix — the `*.` strip and the
        // per-label loop on `["foo", "quero", "cloud:8080"]` would
        // surface the deep byte-class leak. The top-level `:` arm sits
        // upstream of the `*.` strip, so it names the canonical `:port`
        // fix verbatim regardless of whether the host is wildcard-led.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
                if host == "*.quero.cloud:8080"
                && reason.contains(":entrada :port")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_path() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
                if host == "checkout.quero.cloud/api"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_uppercase() {
        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
        // rejected, not silently lower-cased.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("uppercase")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_underscore() {
        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains('_')),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_ipv4_literal() {
        // Gateway API v1 explicitly forbids IP literals as Hostnames.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("IPv4")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_trailing_dot() {
        // The Gateway API regex anchors at end-of-string with no
        // trailing `.` allowance — the FQDN root-dot form is rejected.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
                if host == "checkout.quero.cloud."),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_leading_dot() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("empty label")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_consecutive_dots() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("empty label")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_leading_hyphen_label() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("alphanumeric")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_trailing_hyphen_label() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("alphanumeric")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_inner_wildcard() {
        // Gateway API allows `*` only as the first label (`*.foo`);
        // any inner or trailing `*` is rejected.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("wildcard")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_bare_wildcard() {
        // `*.` with no domain is meaningless; Gateway API rejects it.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "*.".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("wildcard")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_with_whitespace() {
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("whitespace")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_space_names_offending_byte() {
        // Embedded space in the `:entrada :host` axis surfaces the
        // byte-naming diagnostic through the lifted
        // `find_ascii_whitespace_byte` predicate. Peer with the
        // sibling `parse_rejects_leading_whitespace` pins on
        // `supervisor::duration_codec` (a7ae622) — same "the
        // diagnostic carries the offending byte's `0x{b:02x}` shape"
        // discipline extended from the shared duration codec to the
        // Gateway API v1 Hostname axis.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
            panic!("expected EntradaHostInvalid, got {err:?}");
        };
        assert!(
            reason.contains("ASCII whitespace byte"),
            "expected byte-naming diagnostic, got {reason:?}"
        );
        assert!(
            reason.contains("0x20"),
            "expected offending space byte 0x20, got {reason:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_tab_names_offending_byte() {
        // Embedded tab byte in the `:entrada :host` axis — the
        // canonical paste-from-YAML-block-scalar / paste-from-
        // indented-doc footgun. Pins that the lifted predicate covers
        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
        // not just the leading-space case the pre-lift `.bytes().any`
        // arm's opaque "must not contain whitespace" reason already
        // covered. Peer with `parse_rejects_tab_byte` on
        // `supervisor::duration_codec` (a7ae622).
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
            panic!("expected EntradaHostInvalid, got {err:?}");
        };
        assert!(
            reason.contains("ASCII whitespace byte"),
            "expected byte-naming diagnostic, got {reason:?}"
        );
        assert!(
            reason.contains("0x09"),
            "expected offending tab byte 0x09, got {reason:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_lf_names_offending_byte() {
        // Embedded LF byte in the `:entrada :host` axis — the
        // canonical paste-from-shell-heredoc / paste-from-multiline-
        // doc footgun the caixa-mesh YAML emitter would silently
        // reinterpret at the Gateway API v1 HTTPRoute admission
        // layer (an embedded LF byte in a YAML plain scalar either
        // truncates the value at the emitter or crashes the parser
        // on the k8s-apiserver side). Pins the third representative
        // of the full ASCII-whitespace set through the shared
        // predicate.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
            panic!("expected EntradaHostInvalid, got {err:?}");
        };
        assert!(
            reason.contains("ASCII whitespace byte"),
            "expected byte-naming diagnostic, got {reason:?}"
        );
        assert!(
            reason.contains("0x0a"),
            "expected offending LF byte 0x0a, got {reason:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
        // axis — the canonical paste-from-typography /
        // paste-from-word-processor footgun. Before the non-ASCII
        // Unicode `White_Space` scan lifted through the shared
        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
        // with the far-from-source `label "…" must start and end
        // with an alphanumeric` diagnostic — burying the
        // paste-from-typography origin under a label-shape leak.
        // Peer with the sibling non-ASCII-whitespace pins at
        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
        // — 1b75b38), `limits::parse_duration`,
        // `limits::parse_millicores`, and the shared duration codec
        // — same "the diagnostic carries the offending Unicode
        // codepoint's `U+XXXX` shape" discipline extended from every
        // typed-magnitude codec to the Gateway API v1 Hostname axis.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
            panic!("expected EntradaHostInvalid, got {err:?}");
        };
        assert!(
            reason.contains("non-ASCII Unicode whitespace character"),
            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
        );
        assert!(
            reason.contains("U+00A0"),
            "expected offending NBSP codepoint U+00A0, got {reason:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
        // `:entrada :host` axis — the canonical paste-from-web-doc /
        // paste-from-published-HTML footgun. `char::is_whitespace`
        // returns true for `U+2028` per the Unicode `White_Space`
        // property, so `str::trim` at any downstream site would
        // silently strip it — same drift class as NBSP but on a
        // different codepoint region. Pins the second representative
        // (non-Latin-1 `char::is_whitespace` member) through the
        // shared predicate. Peer with
        // `parse_byte_size_rejects_internal_line_separator` on
        // `limits::parse_byte_size` (1b75b38).
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
            panic!("expected EntradaHostInvalid, got {err:?}");
        };
        assert!(
            reason.contains("non-ASCII Unicode whitespace character"),
            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
        );
        assert!(
            reason.contains("U+2028"),
            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
        // labels in the `:entrada :host` axis — the canonical
        // paste-from-CJK-typography footgun (CJK IMEs default to
        // full-width whitespace when the space bar is pressed in
        // Japanese / Chinese input modes). Pins the third
        // representative of the non-ASCII Unicode `White_Space` set
        // through the shared predicate: the CJK block, distinct from
        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
        // SEPARATOR `U+2028` — covering the same axis breadth the
        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
        // (1b75b38) pins on `limits::parse_byte_size`.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
        let err = s.validate().unwrap_err();
        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
            panic!("expected EntradaHostInvalid, got {err:?}");
        };
        assert!(
            reason.contains("non-ASCII Unicode whitespace character"),
            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
        );
        assert!(
            reason.contains("U+3000"),
            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_too_long() {
        // Total length cap = 253; build a 254-byte host out of two
        // 63-byte labels + one 62-byte label + dots.
        let mut s = three_member_spec();
        let big = format!(
            "{}.{}.{}.{}",
            "a".repeat(63),
            "b".repeat(63),
            "c".repeat(63),
            "d".repeat(254 - 63 * 3 - 3)
        );
        assert_eq!(big.len(), 254);
        s.entrada.as_mut().unwrap().host = big;
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("max length of 253")),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_entrada_host_label_too_long() {
        let mut s = three_member_spec();
        // 64-byte label — one over the per-label cap.
        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
                if reason.contains("label max length of 63")),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_host_diagnostic_carries_offending_host() {
        // Diagnostic-shape pin — the offending host + a non-empty
        // reason flow through verbatim so the author can grep their
        // caixa.lisp for `:host "<host>"` and fix it in one edit.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::EntradaHostInvalid { host, reason } => {
                assert_eq!(host, "checkout.quero.cloud:8080");
                assert!(!reason.is_empty(), "reason field must be non-empty");
            }
            other => panic!("expected EntradaHostInvalid, got {other:?}"),
        }
    }

    #[test]
    fn entrada_host_empty_takes_precedence_over_invalid() {
        // Ordering pin: `EmptyEntradaHost` is the more self-locating
        // diagnostic on `""` and must lead — `validate_entrada_host`
        // is only reached after the empty-check fires at the call
        // site. (The predicate itself defends against direct
        // invocation by returning the same error on `""`.)
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().host = String::new();
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
    }

    #[test]
    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
        // Ordering pin: a missing :para member is the more
        // self-locating diagnostic and fires before the host gate.
        let mut s = three_member_spec();
        let e = s.entrada.as_mut().unwrap();
        e.para = "ghost".into();
        e.host = "BAD HOST".into();
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_host_invalid_fires_before_port_zero() {
        // Ordering pin: the host gate fires before the port gate so
        // a malformed host is named even when the port is also wrong.
        let mut s = three_member_spec();
        let e = s.entrada.as_mut().unwrap();
        e.host = "Checkout.quero.cloud".into();
        e.port = 0;
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
                if host == "Checkout.quero.cloud"),
            "got {err:?}"
        );
    }

    #[test]
    fn entrada_accepts_canonical_hosts() {
        // Positive-control sweep — every form the Gateway API
        // apiserver accepts must round-trip through validate. Covers
        // a plain DNS subdomain, a leading wildcard, a single-label
        // host (cluster-internal), a max-length-edge label, a
        // hyphen-bearing label, and a Punycode IDN label.
        for host in [
            "checkout.quero.cloud",
            "*.quero.cloud",
            "checkout",
            // 63-byte label — exactly the per-label cap.
            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
            "foo-bar.quero.cloud",
            // Punycode IDN — valid because the author pre-encoded.
            "xn--bcher-kva.example.com",
        ] {
            let mut s = three_member_spec();
            s.entrada.as_mut().unwrap().host = host.into();
            s.validate()
                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
        }
    }

    #[test]
    fn entrada_host_max_length_validates() {
        // 253-byte host is the cap exactly — must validate. Build a
        // 253-byte host out of three 63-byte labels + one 61-byte
        // label + 3 dots = 252 bytes, then pad one byte to 253.
        let mut s = three_member_spec();
        let host = format!(
            "{}.{}.{}.{}",
            "a".repeat(63),
            "b".repeat(63),
            "c".repeat(63),
            "d".repeat(253 - 63 * 3 - 3)
        );
        assert_eq!(host.len(), 253);
        s.entrada.as_mut().unwrap().host = host;
        s.validate().unwrap();
    }

    #[test]
    fn entrada_host_total_length_cap_threads_lifted_render_const() {
        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
        // total-length gate now reads the K8s Gateway API v1 Hostname
        // `maxLength: 253` cap from the lifted
        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
        // of truth — the same constant every future Gateway-API-Hostname
        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
        // materializer's per-host validator, the future per-`Certificate`
        // SAN emitter for cert-manager, the multi-`:entrada`
        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
        // from. Before the lift, the aplicacao-side reader consumed a
        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
        // 253-byte value as the peer render-side canonical bounds
        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
        // module boundary — a future 253-byte drift on either side would
        // silently split into two axes' worth of admission-schema mismatch
        // without a build-time signal. Pin the cap through a fresh 254-
        // byte host that hits the total-length arm, then read the reason
        // for the exact byte count the shared constant carries: any future
        // regression on the lift (a private alias reintroduced, a hard-
        // coded literal at the arm, a mismatch between the aplicacao-side
        // and render-side canonicals) surfaces as this pin's diagnostic
        // failing to match, not as a per-cluster admission rejection far
        // from the caixa.lisp source line.
        let mut s = three_member_spec();
        let over_cap = format!(
            "{}.{}.{}.{}",
            "a".repeat(63),
            "b".repeat(63),
            "c".repeat(63),
            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
        );
        assert_eq!(
            over_cap.len(),
            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
        );
        s.entrada.as_mut().unwrap().host = over_cap;
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::EntradaHostInvalid { reason, .. } => {
                let needle = format!(
                    "max length of {} bytes",
                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
                );
                assert!(
                    reason.contains(&needle),
                    "diagnostic must name the lifted \
                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
                );
            }
            other => panic!("expected EntradaHostInvalid, got {other:?}"),
        }
    }

    #[test]
    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
        // on the per-label-cap axis. Before the lift, the aplicacao-side
        // per-label arm consumed a private const alias
        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
        // split from it at the module boundary — every `.`-separated
        // label in a Gateway API v1 Hostname is a DNS-1123 label under
        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
        // so the private alias's 63 and the canonical const's 63 were
        // pinning the same underlying rule twice. Pin the cap through a
        // 64-byte label that hits the per-label arm, then read the reason
        // for the exact byte count the shared constant carries: any
        // future drift on either side (a private alias reintroduced, a
        // hard-coded literal at the arm, a mismatch between the two
        // 63-byte pins) surfaces at this pin's diagnostic rather than at
        // a per-cluster admission rejection whose "field is invalid"
        // opacity misframes the root cause.
        let mut s = three_member_spec();
        let over_cap_label = format!(
            "{}.quero.cloud",
            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
        );
        s.entrada.as_mut().unwrap().host = over_cap_label;
        let err = s.validate().unwrap_err();
        match err {
            AplicacaoError::EntradaHostInvalid { reason, .. } => {
                let needle = format!(
                    "label max length of {} bytes",
                    crate::render::DNS_1123_LABEL_MAX_LEN,
                );
                assert!(
                    reason.contains(&needle),
                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
                     cap verbatim on the per-label arm, got: {reason:?}",
                );
            }
            other => panic!("expected EntradaHostInvalid, got {other:?}"),
        }
    }

    #[test]
    fn entrada_with_empty_paths_validates() {
        // Empty `:paths` is the documented "match every path" form;
        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec![];
        s.validate().unwrap();
    }

    #[test]
    fn entrada_root_path_validates() {
        // The author-supplied bare-root `:entrada :paths` entry is the
        // same byte-shape the peer emit-side catch-all constant
        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
        // the author's `:paths` list is empty — sweeping the test-side
        // probe literal onto the lifted const closes the two-axis pin
        // (author-side admit + emit-side canonical fallback) around
        // one `&'static str`, so a future rebrand of the catch-all
        // reaches both consumers by construction. Peer to
        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
        // on the canonical-literal pin surface.
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
        s.validate().unwrap();
    }

    #[test]
    fn placement_strategy_variants_round_trip() {
        for s in [
            PlacementStrategy::SingleNode,
            PlacementStrategy::Replicated,
            PlacementStrategy::Sharded,
        ] {
            let p = Placement {
                estrategia: s,
                clusters: vec!["rio".into()],
                affinity: None,
                shard_key: if s.is_sharded() {
                    Some("$key".into())
                } else {
                    None
                },
            };
            let json = serde_json::to_string(&p).unwrap();
            let back: Placement = serde_json::from_str(&json).unwrap();
            assert_eq!(back, p);
        }
    }

    #[test]
    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
        // The fail-before-pass-after pin: pre-lift there was no
        // single-source binding between the [`PlacementStrategy`]
        // variant name the `Serialize` derive emits and the byte-
        // string every downstream cluster-side dispatcher (the
        // `lareira-fleet-programs` aggregator's per-entry strategy
        // branch, the future `app-operator` reconciler, the M3
        // Adaptive compression pass's per-strategy weighting) probes
        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
        // future `#[serde(rename_all = "kebab-case")]` attribute on
        // the enum — or a variant rename in the source — would
        // silently rebrand the emitted scalar under one spelling
        // while every downstream dispatcher still probed the other,
        // with the failure surfacing at the aggregator's dispatch
        // step or the operator's reconcile posture (workloads coming
        // up under the `default()` `Replicated` arm rather than the
        // typed slot's declared strategy) far from the source
        // rebrand commit and with no field naming the drift. Pinning
        // the two paths (the `Serialize` derive's serialized string
        // AND the [`PlacementStrategy::as_str`] helper) to the same
        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
        // makes any future drift on either endpoint fail here at
        // caixa-core build time.
        for (variant, expected) in [
            (
                PlacementStrategy::SingleNode,
                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
            ),
            (
                PlacementStrategy::Replicated,
                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
            ),
            (
                PlacementStrategy::Sharded,
                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
            ),
        ] {
            let json = serde_json::to_string(&variant).unwrap();
            assert_eq!(
                json,
                format!("\"{expected}\""),
                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
            );
            assert_eq!(
                variant.as_str(),
                expected,
                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
                 M3_PLACEMENT_ESTRATEGIA_* constant"
            );
        }
    }

    #[test]
    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
        // Cross-arm drift-detection pin on the M3
        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
        // scalar-value pentad: a future collapse of two canonical
        // variant byte-strings onto the same value (an accidental
        // copy-paste flip of
        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
        // read `"SingleNode"`, a per-arm rebrand that lands one const
        // without touching its paired peer) would silently reroute
        // every downstream operator's per-strategy dispatch onto the
        // sibling arm's reconcile branch and pass every
        // propagation-probe test that expected only the stale arm's
        // value — a `Replicated`-declared Aplicacao would come up
        // under the `SingleNode` primary-and-standby reconcile
        // posture, so every-cluster active-active workload would
        // silently collapse onto one-cluster-runs-at-a-time takeover
        // semantics against its declared strategy, with no field
        // naming the strategy-value drift root cause. Peer of the
        // sibling
        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
        // (09ffb2d) /
        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
        // (ccdf955) /
        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
        // (d739850) distinctness pins on the sibling OTP-shape /
        // caixa-kind closed-set typed-enum discriminator axes — the
        // fourth (and structurally the M3 mesh-primitive-defining)
        // closed-set typed-enum axis to converge on the same
        // "pairwise-distinct-by-construction" discipline.
        //
        // Fail-before-pass-after locally verified by mutating
        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
        // also read `"SingleNode"` — this pin fires as expected;
        // restoring passes.
        let all = [
            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
        ];
        for (i, a) in all.iter().enumerate() {
            for (j, b) in all.iter().enumerate() {
                if i != j {
                    assert_ne!(
                        a, b,
                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
                         distinct — got duplicate {a:?} at indices {i} and {j}",
                    );
                }
            }
        }
    }

    #[test]
    fn placement_strategy_display_routes_through_as_str_helper() {
        // The fail-before-pass-after pin: pre-lift the sibling
        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
        // / [`crate::supervisor::RestartPolicy`] both carried a stable
        // [`std::fmt::Display`] surface via their
        // `#[discriminant(also_display)]` gen-platform derive, but
        // [`PlacementStrategy`] did not — every consumer reaching for
        // a strategy byte-string past the wire format had to pick
        // between three paths ([`PlacementStrategy::as_str`], the
        // `Serialize` derive's serialized string, or `format!("{v:?}")`
        // on the `Debug` derive), any two of which a future variant
        // rename or `#[serde(rename_all = "kebab-case")]` attribute
        // would silently desynchronize. Wiring [`std::fmt::Display`]
        // through [`PlacementStrategy::as_str`] closes the third path:
        // every `format!("{v}")` call reaches the same lifted
        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
        // and the [`PlacementStrategy::as_str`] helper already route
        // through, so a future variant rename lands at exactly one
        // place. Pin the routing here so a future
        // `impl std::fmt::Display for PlacementStrategy` reimplementation
        // that hand-rolls the arms instead of delegating to
        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
        for variant in [
            PlacementStrategy::SingleNode,
            PlacementStrategy::Replicated,
            PlacementStrategy::Sharded,
        ] {
            assert_eq!(
                variant.to_string(),
                variant.as_str(),
                "PlacementStrategy::{variant:?} Display must route through \
                 PlacementStrategy::as_str (single source of truth: the lifted \
                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
            );
        }
    }

    #[test]
    fn placement_strategy_display_matches_serialized_wire_byte_string() {
        // The fail-before-pass-after pin on the second half of the
        // three-path convergence: `Display` (user-facing text) agrees
        // byte-for-byte with the `Serialize` derive's wire format
        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
        // scalar) on every variant. Pre-lift the two paths were
        // structurally independent — a future
        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
        // would silently rebrand the emitted wire scalar
        // (`single-node`, `replicated`, `sharded`) while every consumer
        // that pretty-prints the strategy (the M3 diagnostic templates,
        // the future `feira app graph` per-Aplicacao strategy line,
        // the future M4 CR materializer's admission-webhook rejection
        // body) would still emit the TitleCase form the `as_str` /
        // `Display` route returns, with the mismatch surfacing at
        // consumer parse time / operator dispatch time far from the
        // source rebrand commit. Pin the two paths byte-for-byte here
        // so any future serde-attribute or variant-rename drift is a
        // caixa-core-build-time test failure at this call, not a
        // silent per-consumer dispatch miss.
        for variant in [
            PlacementStrategy::SingleNode,
            PlacementStrategy::Replicated,
            PlacementStrategy::Sharded,
        ] {
            let wire = serde_json::to_string(&variant).unwrap();
            // Strip the outer `"…"` the JSON string form carries — the
            // wire scalar the K8s / YAML apiserver consumes is the
            // enclosed byte-string, not the quote wrapper.
            let unquoted = wire
                .strip_prefix('"')
                .and_then(|s| s.strip_suffix('"'))
                .expect("serialized PlacementStrategy is a JSON string");
            assert_eq!(
                variant.to_string(),
                unquoted,
                "PlacementStrategy::{variant:?} Display byte-string must match the \
                 Serialize derive's wire byte-string (three-path convergence: \
                 Display + as_str + Serialize all resolve to the same \
                 M3_PLACEMENT_ESTRATEGIA_* const)"
            );
        }
    }

    #[test]
    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
        // derive on [`PlacementStrategy`]: for each of the three variants
        // exactly one of the generated `is_single_node` / `is_replicated`
        // / `is_sharded` predicates returns `true` and the other two
        // return `false`. Prior to this derive the three per-arm
        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
        // (the `placement_strategy_variants_round_trip` fixture, the
        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
        // fixture, and the
        // `validate_placement_reads_through_lifted_estrategia_accessor`
        // fixture) each open-coded a per-arm PartialEq compare against
        // the enum variant — three sites that expressed no compile-time
        // link back to the closed-set typed dispatch a future fourth
        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
        // would have to thread through in lockstep or one fixture would
        // silently disagree with the others on which arms consume the
        // `:shard-key` axis. Peer of the sibling
        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
        // / [`crate::supervisor::RestartPolicy`] /
        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
        // the sibling closed-set typed-enum discriminator axes — extends
        // the same one-typed-dispatch-per-variant discipline onto the
        // fifth (and only remaining) closed-set typed-enum discriminator
        // on the caixa surface, closing the axis on the M3 mesh-slot
        // family.
        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
            (PlacementStrategy::SingleNode, [true, false, false]),
            (PlacementStrategy::Replicated, [false, true, false]),
            (PlacementStrategy::Sharded, [false, false, true]),
        ];
        for (variant, expected) in rows {
            let observed = [
                variant.is_single_node(),
                variant.is_replicated(),
                variant.is_sharded(),
            ];
            assert_eq!(
                observed, expected,
                "PlacementStrategy::{variant:?} is_* predicates must partition \
                 the arm set (single_node, replicated, sharded); got {observed:?}"
            );
        }
    }

    #[test]
    fn placement_strategy_is_variant_predicates_are_const_fn() {
        // The [`gen_platform::IsVariant`] derive emits `const fn`
        // predicates on the peer [`crate::CaixaKind`] +
        // [`crate::upgrade::UpgradeInstruction`] +
        // [`crate::supervisor::RestartStrategy`] +
        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
        // pin the same posture on [`PlacementStrategy`] so a future
        // accidental downgrade to non-`const` (an added runtime helper
        // reachable only from a non-`const` context, a manual hand-rolled
        // `impl` that shadows the derive-generated method) trips at
        // caixa-core build time rather than surfacing as a downstream
        // `const`-context regression far from the derive declaration.
        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
        assert!(IS_SINGLE_NODE);
        assert!(IS_REPLICATED);
        assert!(IS_SHARDED);
    }

    #[test]
    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
        // Pin the M3 diagnostic template routes through the typed
        // [`PlacementStrategy`] Display byte-string (rebound from the
        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
        // routes emitted identical bytes (the `Debug` derive on a
        // unit variant emits the variant name verbatim, exactly what
        // `as_str` returns), but the two paths were structurally
        // independent — a future `#[serde(rename_all = "…")]`
        // attribute or variant rename would coordinate the wire /
        // `Display` / `as_str` triple through the lifted const but
        // leave the `Debug` route on the compiler-derived variant name,
        // silently desynchronizing the diagnostic byte-string from the
        // wire byte-string. Rebinding the template onto `Display`
        // ties the diagnostic to the same lifted
        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
        // emits — drift becomes structurally impossible. Pin the
        // byte-string here so a future edit that reverts the template
        // to `{estrategia:?}` is caught at caixa-core test time, not
        // at consumer dispatch time.
        for (variant, expected_scalar) in [
            (
                PlacementStrategy::SingleNode,
                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
            ),
            (
                PlacementStrategy::Replicated,
                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
            ),
            (
                PlacementStrategy::Sharded,
                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
            ),
        ] {
            let err = AplicacaoError::PlacementWithoutClusters {
                estrategia: variant,
            };
            let msg = err.to_string();
            assert!(
                msg.starts_with(&format!(":placement {expected_scalar} requires")),
                "PlacementWithoutClusters diagnostic for {variant:?} must open \
                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
            );
        }
    }

    #[test]
    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
        // Peer of
        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
        // on the second M3 diagnostic that carries the typed
        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
        // diagnostics now route the strategy scalar through the same
        // [`std::fmt::Display`] surface, tying the diagnostic
        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
        // const set the wire format also emits. The two non-Sharded
        // arms are exercised here (the diagnostic exists to flag a
        // `:shard-key` slot the current strategy will never consume);
        // the peer `Sharded` arm never reaches this diagnostic (the
        // `Sharded` strategy consumes `:shard-key` — the
        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
        // slot instead).
        for (variant, expected_scalar) in [
            (
                PlacementStrategy::SingleNode,
                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
            ),
            (
                PlacementStrategy::Replicated,
                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
            ),
        ] {
            let err = AplicacaoError::ShardKeyOnNonSharded {
                estrategia: variant,
                shard_key: "$tenantId".into(),
            };
            let msg = err.to_string();
            assert!(
                msg.starts_with(&format!(":placement {expected_scalar} carries")),
                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
            );
        }
    }

    #[test]
    fn rejects_zero_policy_timeout() {
        let mut s = three_member_spec();
        s.politicas.timeout = Some(Duration::ZERO);
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
    }

    #[test]
    fn rejects_zero_policy_retries() {
        let mut s = three_member_spec();
        s.politicas.retries = Some(0);
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
    }

    #[test]
    fn rejects_policy_retries_above_cap() {
        // The fail-before-pass-after pin: `Some(11)` is structurally
        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
        // passed validate on every pre-gate codebase because the
        // typed slot's only check was the zero-floor arm. The
        // thundering-herd amplification vector only surfaced at the
        // runtime substrate (Envoy / Cilium L7 retry overlay)
        // far from the source caixa.lisp with no field naming the
        // offending policy.
        let mut s = three_member_spec();
        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRetriesExceedsCap {
                retries: POLICY_RETRIES_MAX + 1
            }
        );
    }

    #[test]
    fn rejects_policy_retries_far_above_cap() {
        // The `u32::MAX` worst case — the four-billion-retry policy
        // a typo (`(:retries 4294967295)`) or struct-literal
        // copy-paste lands in the slot. Pin the cap arm's coverage
        // explicitly across the full `u32` overflow so a future
        // relaxation that drops the upper bound surfaces here.
        let mut s = three_member_spec();
        s.politicas.retries = Some(u32::MAX);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
        );
    }

    #[test]
    fn accepts_policy_retries_at_cap() {
        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
        // must validate. The cap is inclusive on the top edge,
        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
        // discipline on the sibling [`crate::LimitsSpec::memory`]
        // axis. Pin the boundary explicitly so a future off-by-one
        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
        // surfaces here as a test failure rather than a silent
        // contract narrowing.
        let mut s = three_member_spec();
        s.politicas.retries = Some(POLICY_RETRIES_MAX);
        s.validate()
            .expect("retries == POLICY_RETRIES_MAX must validate");
    }

    #[test]
    fn accepts_policy_retries_typical_values() {
        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
        // every value in the validated set must pass. The
        // Envoy / Istio production-playbook recommendation band
        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
        // (`maxRetries ≤ 10`) both lie within this set.
        for r in 1..=POLICY_RETRIES_MAX {
            let mut s = three_member_spec();
            s.politicas.retries = Some(r);
            s.validate()
                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
        }
    }

    #[test]
    fn policy_retries_zero_takes_precedence_over_cap() {
        // The cross-arm ordering pin: `Some(0)` is structurally
        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
        // (cap), but the zero-floor diagnostic is the more
        // self-locating one (it directly names the omit-axis
        // remediation), so the validate gate must fire on zero
        // first. Pin the order so a future refactor that reorders
        // the arms surfaces here as a test failure rather than a
        // silent diagnostic regression. Same shape every other
        // zero-then-shape ordering on this surface uses
        // ([`AplicacaoError::PolicyTimeoutZero`] then
        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
        let mut s = three_member_spec();
        s.politicas.retries = Some(0);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRetriesZero,
            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
        );
    }

    #[test]
    fn policy_retries_cap_diagnostic_carries_offending_value() {
        // The diagnostic-shape pin: the offending `u32` is carried
        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
        // variant so the surfaced error message names the value the
        // author wrote (`":politicas :retries (47) exceeds the
        // mesh-policy ceiling …"`), not just the cap. Same
        // self-locating diagnostic shape every other typed-cap arm
        // on this surface carries
        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
        // offending byte count verbatim).
        let mut s = three_member_spec();
        s.politicas.retries = Some(47);
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
            "got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("47"),
            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
        );
    }

    #[test]
    fn policy_retries_cap_is_aws_app_mesh_aligned() {
        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
        // schema cap — the only upstream mesh-policy schema that
        // documents an explicit hard cap. Pinning the literal value
        // here surfaces a future drift (a relaxation to 20, a
        // tightening to 5) as a deliberate test edit, not a silent
        // contract narrowing.
        assert_eq!(POLICY_RETRIES_MAX, 10);
    }

    #[test]
    fn rejects_circuit_breaker_zero_max_failures() {
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 0,
            window: Duration::from_secs(60),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerZeroFailures
        );
    }

    #[test]
    fn rejects_circuit_breaker_max_failures_above_cap() {
        // The fail-before-pass-after pin: `1001` is structurally one
        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
        // silently passed validate on every pre-gate codebase
        // because the typed slot's only check was the zero-floor
        // arm. The breaker-no-op vector only surfaced at the runtime
        // substrate (Envoy / Cilium L7 outlier-detection overlay)
        // far from the source caixa.lisp with no field naming the
        // offending policy.
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
            window: Duration::from_secs(60),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
            }
        );
    }

    #[test]
    fn rejects_circuit_breaker_max_failures_far_above_cap() {
        // The `u32::MAX` worst case — the four-billion-failure
        // threshold a typo (`(:max-failures 4294967295)`) or a
        // struct-literal copy-paste lands in the slot. Pin the cap
        // arm's coverage explicitly across the full `u32` overflow
        // so a future relaxation that drops the upper bound surfaces
        // here.
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: u32::MAX,
            window: Duration::from_secs(60),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
                max_failures: u32::MAX,
            }
        );
    }

    #[test]
    fn accepts_circuit_breaker_max_failures_at_cap() {
        // The boundary value — exactly
        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
        // cap is inclusive on the top edge, matching the
        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
        // discipline on the sibling capped axes. Pin the boundary
        // explicitly so a future off-by-one tightening
        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
        // surfaces here as a test failure rather than a silent
        // contract narrowing.
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
            window: Duration::from_secs(60),
        });
        s.validate()
            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
    }

    #[test]
    fn accepts_circuit_breaker_max_failures_typical_values() {
        // The documented production-playbook band positive-control
        // sweep — every value Hystrix / Istio / Envoy / Polly /
        // Resilience4j recommend (5..=50) must pass, plus a sweep
        // through the hyperscale band (100, 500, 1000) the cap
        // accepts. Pin the inclusive validated set explicitly so a
        // future tightening of the ceiling surfaces here.
        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
            let mut s = three_member_spec();
            s.politicas.circuit_breaker = Some(CircuitBreaker {
                max_failures: n,
                window: Duration::from_secs(60),
            });
            s.validate()
                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
        }
    }

    #[test]
    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
        // The cross-arm ordering pin: `0` is structurally outside
        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
        // (cap), but the zero-floor diagnostic is the more
        // self-locating one (it directly names the omit-axis
        // remediation), so the validate gate must fire on zero
        // first. Same shape every other zero-then-shape ordering on
        // this surface uses
        // ([`AplicacaoError::PolicyRetriesZero`] then
        // [`AplicacaoError::PolicyRetriesExceedsCap`];
        // [`AplicacaoError::PolicyTimeoutZero`] then
        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 0,
            window: Duration::from_secs(60),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerZeroFailures,
            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
        );
    }

    #[test]
    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
        // The cross-arm ordering pin between the cap and the
        // sibling `:window` gates (zero-window, canonical-window).
        // A breaker carrying both an over-cap `max_failures` AND a
        // structurally invalid window (zero, sub-ms) must surface
        // the cap diagnostic first — the cap arm is wired
        // immediately after the zero-failure arm and strictly
        // before the window arms, so the offending value the
        // diagnostic names matches the order the author would
        // discover the gates by reading top-to-bottom through
        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
        // future refactor that reorders the arms surfaces here as a
        // test failure rather than a silent diagnostic regression.
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
            window: Duration::ZERO,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
            },
            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
        );
    }

    #[test]
    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
        // The diagnostic-shape pin: the offending `u32` is carried
        // verbatim into the
        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
        // variant so the surfaced error message names the value the
        // author wrote (`":politicas :circuit-breaker :max-failures
        // (50000) exceeds the mesh-policy ceiling …"`), not just
        // the cap. Same self-locating diagnostic shape every other
        // typed-cap arm on this surface carries
        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
        // offending retry count verbatim,
        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
        // offending byte count verbatim).
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 50_000,
            window: Duration::from_secs(60),
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
                    max_failures: 50_000
                }
            ),
            "got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("50000"),
            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
        );
    }

    #[test]
    fn policy_breaker_max_failures_cap_pins_canonical_value() {
        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
        // value at 1000 — an order of magnitude above every
        // documented production-playbook recommendation band
        // (Hystrix `requestVolumeThreshold` default 20, Istio
        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
        // `outlier_detection.consecutive_5xx` default 5, Polly /
        // Resilience4j typical 5..=50) and below the
        // clearly-pathological "effectively no protection" floor
        // (10_000, 100_000, u32::MAX). Pinning the literal value
        // here surfaces a future drift (a relaxation to 10_000, a
        // tightening to 100) as a deliberate test edit, not a
        // silent contract narrowing.
        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
    }

    #[test]
    fn rejects_circuit_breaker_zero_window() {
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window: Duration::ZERO,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerZeroWindow
        );
    }

    #[test]
    fn rejects_zero_rate_limit() {
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: 0,
            window: Duration::from_secs(1),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitZero
        );
    }

    #[test]
    fn rejects_rate_limit_zero_window() {
        // `RateLimit { rate: 100, window: Duration::ZERO }` is
        // constructible programmatically (the typed `Duration` field
        // imposes no nonzero invariant) but renders through
        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
        // codec's `parse` rejects as `unknown rate-limit window unit
        // "0s"`. Until this validate-time gate landed the typed slot
        // accepted the value silently and the round-trip break only
        // surfaced at deserialize time (potentially in a downstream
        // consumer that never re-validates). Pin the rejection at
        // `AplicacaoSpec::validate` so the typed slot's valid set
        // matches the codec's round-trippable set structurally.
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: 100,
            window: Duration::ZERO,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitWindowNotCanonical {
                window: Duration::ZERO
            }
        );
    }

    #[test]
    fn rejects_rate_limit_arbitrary_seconds_window() {
        // 45 seconds is a valid `Duration` but not one of the three
        // canonical rate-limit windows the codec round-trips
        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
        // refuses on round-trip — same round-trip-break shape the
        // zero-window arm above pins, with a non-zero magnitude to
        // guard against a future "reject only zero" half-measure.
        let mut s = three_member_spec();
        let window = Duration::from_secs(45);
        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
        );
    }

    #[test]
    fn rejects_rate_limit_two_minute_window() {
        // 120 seconds = 2 minutes is a "looks-canonical" but
        // not-canonical window: it's a clean integer multiple of the
        // minute unit, but the codec only round-trips the
        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
        // A `Duration::from_secs(120)` window renders as `"100/120s"`
        // which the parser rejects. Pinning this case rules out a
        // future "accept any clean multiple of s/m/h" relaxation
        // that would silently break the codec contract.
        let mut s = three_member_spec();
        let window = Duration::from_secs(120);
        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
        );
    }

    #[test]
    fn rejects_rate_limit_subsecond_window() {
        // A sub-second window (e.g. 500ms) is a valid `Duration` but
        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
        // Pin the rejection so a future relaxation can't silently
        // admit fractional-second windows that the codec can't
        // round-trip.
        let mut s = three_member_spec();
        let window = Duration::from_millis(500);
        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
        );
    }

    #[test]
    fn rejects_policy_rate_limit_above_cap() {
        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
        // is structurally one past the cap and silently passed
        // validate on every pre-gate codebase because the typed slot's
        // only `rate` check was the zero-floor arm. The no-op-limiter
        // shape only surfaced at the runtime substrate (Envoy's
        // `local_rate_limit.token_bucket.max_tokens`, the future
        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
        // with no field naming the offending policy.
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: POLICY_RATE_LIMIT_MAX + 1,
            window: Duration::from_secs(1),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitExceedsCap {
                rate: POLICY_RATE_LIMIT_MAX + 1
            }
        );
    }

    #[test]
    fn rejects_policy_rate_limit_far_above_cap() {
        // The `u32::MAX` worst case — the four-billion-token rate-limit
        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
        // copy-paste lands in the slot. Pin the cap arm's coverage
        // explicitly across the full `u32` overflow so a future
        // relaxation that drops the upper bound surfaces here. Peer to
        // `rejects_policy_retries_far_above_cap` on the sibling
        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
        // on the sibling `:max-failures` axis.
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: u32::MAX,
            window: Duration::from_secs(1),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
        );
    }

    #[test]
    fn accepts_policy_rate_limit_at_cap() {
        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
        // must validate. The cap is inclusive on the top edge, matching
        // every other typed upper bound in this crate
        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
        // across all three canonical windows so a future off-by-one
        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
        // window-conditional cap surfaces here as a test failure rather
        // than a silent contract narrowing.
        for secs in [1u64, 60, 3600] {
            let mut s = three_member_spec();
            s.politicas.rate_limit = Some(RateLimit {
                rate: POLICY_RATE_LIMIT_MAX,
                window: Duration::from_secs(secs),
            });
            s.validate().unwrap_or_else(|e| {
                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
            });
        }
    }

    #[test]
    fn accepts_policy_rate_limit_typical_values() {
        // The documented production-playbook recommendation band —
        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
        // Enterprise ~1M per-hour. Every value in the validated set
        // must pass; pin the band explicitly so a future tightening
        // surfaces here.
        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
            for secs in [1u64, 60, 3600] {
                let mut s = three_member_spec();
                s.politicas.rate_limit = Some(RateLimit {
                    rate,
                    window: Duration::from_secs(secs),
                });
                s.validate().unwrap_or_else(|e| {
                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
                });
            }
        }
    }

    #[test]
    fn policy_rate_limit_zero_takes_precedence_over_cap() {
        // The cross-arm ordering pin: `rate == 0` is structurally
        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
        // (cap), but the zero-floor diagnostic is the more
        // self-locating one (it directly names the omit-axis
        // remediation). Pin the order so a future refactor that
        // reorders the arms surfaces here as a test failure rather
        // than a silent diagnostic regression. Same shape every other
        // zero-then-cap ordering on this surface uses
        // ([`AplicacaoError::PolicyRetriesZero`] then
        // [`AplicacaoError::PolicyRetriesExceedsCap`];
        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: 0,
            window: Duration::from_secs(1),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitZero,
            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
        );
    }

    #[test]
    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
        // Two-axis-bad pin: rate above cap *and* window non-canonical.
        // The validate gate must fire on the rate cap first — the
        // amplification-shape (no-op limiter) diagnostic is the more
        // fundamental one; the window-canonical diagnostic is the
        // narrower codec-round-trip shape. Pin the ordering so a future
        // refactor that reorders the rate-then-window check arms
        // surfaces here as a test failure rather than a silent
        // diagnostic regression.
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: POLICY_RATE_LIMIT_MAX + 1,
            window: Duration::from_secs(45),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitExceedsCap {
                rate: POLICY_RATE_LIMIT_MAX + 1
            },
            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
        );
    }

    #[test]
    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
        // The diagnostic-shape pin: the offending `u32` is carried
        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
        // variant so the surfaced error message names the value the
        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
        // the mesh-policy ceiling …"`), not just the cap. Same
        // self-locating diagnostic shape every other typed-cap arm on
        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
        // carries the offending retries count verbatim,
        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
        // the offending failure count verbatim).
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: 5_000_000,
            window: Duration::from_secs(1),
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
            ),
            "got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("5000000"),
            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
        );
    }

    #[test]
    fn policy_rate_limit_cap_pins_canonical_value() {
        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
        // 1_000_000 — two-to-three orders of magnitude above every
        // documented production-playbook recommendation band (Envoy /
        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
        // Gateway 10_000..=100_000 per-minute) and below the
        // clearly-pathological "paste-from-binary blob" floor
        // (100_000_000, u32::MAX). Pinning the literal value here
        // surfaces a future drift (a relaxation to 10_000_000, a
        // tightening to 100_000) as a deliberate test edit, not a
        // silent contract narrowing.
        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
    }

    #[test]
    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
        // Both axes are invalid here: rate == 0 *and* window is
        // non-canonical. The validate gate must fire on rate first
        // (matching the existing `rejects_zero_rate_limit` ordering),
        // so the existing diagnostic continues to lead with the
        // simpler "zero rate" framing. Pinning the order of checks
        // so a future refactor that reorders the arms surfaces here
        // as a test failure rather than a silent diagnostic
        // regression.
        let mut s = three_member_spec();
        s.politicas.rate_limit = Some(RateLimit {
            rate: 0,
            window: Duration::from_secs(45),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyRateLimitZero
        );
    }

    #[test]
    fn rate_limit_canonical_windows_validate() {
        // The three canonical windows the codec round-trips
        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
        // unchanged. Pin the full canonical set as a positive case
        // (the existing `rate_limit_round_trip_seconds` /
        // `rate_limit_round_trip_minutes` tests pin the
        // serialize-then-deserialize property at the codec layer; this
        // test pins the validate-side complement so a future tightening
        // of the canonical set — e.g. dropping `:hour` — surfaces here
        // as a test failure rather than a silent contract narrowing).
        for secs in [1u64, 60, 3600] {
            let mut s = three_member_spec();
            s.politicas.rate_limit = Some(RateLimit {
                rate: 100,
                window: Duration::from_secs(secs),
            });
            s.validate().expect("canonical window must validate");
        }
    }

    #[test]
    fn rate_limit_validated_value_round_trips_through_codec() {
        // The structural property the validate gate enforces:
        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
        // losslessly through the `rate_limit_codec` (serialize → string
        // → deserialize → equal value). Pin this end-to-end so a future
        // change to either side (the validate gate's accepted window
        // set, the codec's parse/render unit set) that breaks the
        // alignment surfaces here. The previous-state shape (typed
        // slot accepts arbitrary `Duration`, codec only round-trips
        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
        // window — the validate gate now forecloses that.
        for secs in [1u64, 60, 3600] {
            let mut s = three_member_spec();
            s.politicas.rate_limit = Some(RateLimit {
                rate: 250,
                window: Duration::from_secs(secs),
            });
            s.validate().unwrap();
            let json = serde_json::to_string(&s.politicas).unwrap();
            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
            assert_eq!(
                back.rate_limit, s.politicas.rate_limit,
                "every validated :rate-limit must round-trip losslessly through the codec"
            );
        }
    }

    #[test]
    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
        // The hour-window canonical form (`"<n>/h"`) was missing from
        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
        // pair. Now that the validate gate pins 3600s as part of the
        // canonical set, pin its serialize-side render shape too so
        // the third leg of the s/m/h tripod is explicitly tested.
        let policy = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 10000,
                window: Duration::from_secs(3600),
            }),
            ..Default::default()
        };
        let json = serde_json::to_string(&policy).unwrap();
        assert!(
            json.contains("\"10000/h\""),
            "hour-window canonical form must render with `h` suffix (got: {json})"
        );
        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
    }

    #[test]
    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
        // typed accessor's accepted-window set against the codec's
        // accepted set explicitly. A future addition to the codec
        // (e.g. accepting `:day`/`:week` as authoring units) must be
        // accompanied by a parallel addition here, and a regression
        // that drops one of the three canonical units from either
        // side surfaces as a test failure. The accessor is the
        // single source of truth for the canonical-window set —
        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
        // gate and [`rate_limit_codec::render`]'s canonical arm both
        // read through it — this test enshrines that its
        // `Duration → Option<RateLimitUnit>` projection matches the
        // codec's parse / render arms' accepted-window set exactly.
        //
        // Predecessor: this pin previously read the module-private
        // free helper `is_canonical_rate_limit_window` — a delegate
        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
        // — but the helper had no production consumers left after the
        // validate-gate migration onto [`RateLimit::canonical_unit`]
        // and was deleted; the closed-set arm-window bijection now
        // lives on exactly one typed dispatch on the substrate
        // primitive.
        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
            RateLimit { rate: 1, window }.canonical_unit()
        };
        assert!(canonical_unit(Duration::from_secs(1)).is_some());
        assert!(canonical_unit(Duration::from_secs(60)).is_some());
        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
        // Non-canonical windows the accessor rejects.
        assert!(canonical_unit(Duration::ZERO).is_none());
        assert!(canonical_unit(Duration::from_secs(2)).is_none());
        assert!(canonical_unit(Duration::from_secs(30)).is_none());
        assert!(canonical_unit(Duration::from_secs(120)).is_none());
        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
        // Sub-second windows: even `Duration::from_millis(1000)` is
        // exactly 1s and accepted; `Duration::from_millis(500)` is
        // sub-second and rejected.
        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
        assert!(canonical_unit(Duration::from_millis(500)).is_none());
        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
    }

    #[test]
    fn rate_limit_unit_table_projections_are_mutual_inverses() {
        // Bidirection pin against the closed-set typed enum
        // [`RateLimitUnit`] arm-table (the canonical
        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
        // of the rate-limit unit surface reads from). The two
        // projection directions [`RateLimitUnit::from_suffix`] /
        // [`RateLimitUnit::window`] (str → Duration, exposed as one
        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
        // (Duration → str, exposed as one typed dispatch through
        // [`RateLimit::canonical_unit`] composed with
        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
        // codec's parse arm ([`rate_limit_codec::parse`] via
        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
        // via [`RateLimit::canonical_unit`]) all key off. A future
        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
        // sub-second window) is one variant + one arm per method on the
        // closed-set enum; the compiler-enforced exhaustiveness on
        // every consumer's `match self` arms picks it up by
        // construction. This pin enshrines that both projection
        // directions agree on every canonical arm row and neither
        // leaks a spurious entry the other doesn't recognize.
        //
        // Predecessor: this test previously read the two vestigial
        // module-private free helpers `rate_limit_window_unit` and
        // `rate_limit_window_from_unit` on the `Duration → &str` and
        // `&str → Duration` axes; the former was deleted after its
        // sole production consumer ([`rate_limit_codec::render`])
        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
        // the latter is folded here into the substrate primitive
        // [`RateLimitUnit::window_from_suffix`] so both projection
        // directions live on the closed-set enum's arm-table.
        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
            let window = super::RateLimitUnit::window_from_suffix(unit)
                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
            assert_eq!(
                window,
                Duration::from_secs(secs),
                "unit {unit:?} must resolve to {secs}s"
            );
            let projected_suffix = RateLimit { rate: 1, window }
                .canonical_unit()
                .map(super::RateLimitUnit::as_suffix);
            assert_eq!(
                projected_suffix,
                Some(unit),
                "Duration({secs}s) must render as {unit:?} \
                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
            );
        }
        // Non-table units yield None on the `unit → Duration`
        // projection — a future `"d"` addition to the table would
        // flip this arm; today it pins the current three-row table's
        // rejection semantics.
        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
        // Non-table Durations yield None on the `Duration → unit`
        // projection — pins that the two projections agree on the
        // "not in the table" semantic too, so a drift where the
        // parse-side accepts a value the render-side can't emit is
        // a build error at the two-arm pair, not a silent codec
        // round-trip break.
        let projected_suffix = |window: Duration| -> Option<&'static str> {
            RateLimit { rate: 1, window }
                .canonical_unit()
                .map(super::RateLimitUnit::as_suffix)
        };
        assert!(projected_suffix(Duration::from_secs(2)).is_none());
        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
    }

    #[test]
    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
        // substrate-primitive `&str → Duration` associated method the
        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
        // to the same [`Duration`] the two-step composition
        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
        // `"MIN"`) must project to [`None`] on both paths. A future
        // implementation of `window_from_suffix` that took a shortcut
        // through a per-suffix `match` table (bypassing the arm-table's
        // `Self::from_suffix` scan and the arm-table's `Self::window`
        // dispatch) would silently split the accept-set — the parse
        // arm would accept a suffix the enum's arm-table doesn't know,
        // or reject a suffix the enum's arm-table does; this pin
        // surfaces that drift at caixa-core build time rather than at a
        // downstream serde round-trip audit on a live `MeshPolicy`.
        //
        // Same byte-parity discipline the sibling
        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
        // pin carries on the peer `Duration → RateLimitUnit` axis via
        // [`RateLimit::canonical_unit`], and the peer
        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
        // carries on the bidirectional arm-table axis — extended here
        // onto the fifth (and last unlifted) projection axis on the
        // closed-set enum's arm-table.
        let composition = |suffix: &str| -> Option<Duration> {
            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
        };
        for suffix in ["s", "m", "h"] {
            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
            let via_composition = composition(suffix);
            assert_eq!(
                via_method, via_composition,
                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
                 method must delegate to the arm-table's two typed dispatches, \
                 not shortcut through a per-suffix match table"
            );
            assert!(
                via_method.is_some(),
                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
                 RateLimitUnit::window_from_suffix"
            );
        }
        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
            let via_composition = composition(suffix);
            assert_eq!(
                via_method, via_composition,
                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
                 axis too"
            );
            assert!(
                via_method.is_none(),
                "non-arm suffix {suffix:?} must project to None via \
                 RateLimitUnit::window_from_suffix — a future extension that \
                 accepted this suffix without a corresponding arm on the enum \
                 would split the codec's parse-accepted set from the enum's \
                 arm-table"
            );
        }
        // And the codec's parse arm now reads through this method: a
        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
        // the same `Duration` the method returns for its unit, closing
        // the two-consumer drift surface (the codec's parse arm and the
        // enum's arm-table) with one typed dispatch on the substrate
        // primitive.
        for suffix in ["s", "m", "h"] {
            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
            let mp: MeshPolicy = serde_json::from_str(&wire)
                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
            let parsed = mp.rate_limit().expect("rate_limit payload present");
            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
            assert_eq!(
                parsed.window(),
                via_method,
                "codec parse arm on {wire:?} must resolve the window through \
                 RateLimitUnit::window_from_suffix, not a divergent path"
            );
        }
    }

    #[test]
    fn rate_limit_unit_all_enumerates_every_arm_once() {
        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
        // enumerate every arm of the closed-set enum exactly once, in
        // the canonical shortest-to-longest window order (Second before
        // Minute before Hour) — the same order the sibling
        // [`crate::supervisor::RestartStrategy`] /
        // [`crate::supervisor::RestartPolicy`] /
        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
        // typed enums carry (the arm declared first is the arm listed
        // first). A future variant addition that extends the enum
        // without appending to [`RateLimitUnit::ALL`] leaves the
        // exhaustive iteration surface silently short one arm — the
        // codec's parse arm would then reject the new suffix even
        // though the enum knows it. This pin closes the drift.
        assert_eq!(
            super::RateLimitUnit::ALL,
            &[
                super::RateLimitUnit::Second,
                super::RateLimitUnit::Minute,
                super::RateLimitUnit::Hour,
            ],
            "RateLimitUnit::ALL must enumerate every arm exactly once, \
             in canonical shortest-to-longest window order"
        );
    }

    #[test]
    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
        // every arm's [`RateLimitUnit::as_suffix`] output must parse
        // back through [`RateLimitUnit::from_suffix`] to the same
        // variant. A future arm addition that lands `as_suffix` but
        // forgets `from_suffix` (`from_suffix` iterates
        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
        // is the load-bearing carrier of the round-trip; the sibling
        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
        // the `ALL` half) trips here at caixa-core build time rather
        // than surfacing as a codec round-trip miss (a `render` emit
        // that lands a suffix the paired `parse` cannot decode).
        for unit in super::RateLimitUnit::ALL {
            let suffix = unit.as_suffix();
            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
                panic!(
                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
                     RateLimitUnit::as_suffix output — got None for {unit:?}"
                )
            });
            assert_eq!(
                parsed, *unit,
                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
                 must return RateLimitUnit::{unit:?}"
            );
        }
    }

    #[test]
    fn rate_limit_unit_from_window_and_window_round_trip() {
        // Total round-trip pin on the `(from_window, window)` pair:
        // every arm's [`RateLimitUnit::window`] output must parse back
        // through [`RateLimitUnit::from_window`] to the same variant.
        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
        // on the peer `Duration` axis — the two round-trip pins
        // together enshrine that both projections of the typed
        // canonical-unit bijection are total on the arm-set.
        for unit in super::RateLimitUnit::ALL {
            let window = unit.window();
            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
                panic!(
                    "RateLimitUnit::from_window({window:?}) must accept every \
                     RateLimitUnit::window output — got None for {unit:?}"
                )
            });
            assert_eq!(
                parsed, *unit,
                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
                 must return RateLimitUnit::{unit:?}"
            );
        }
    }

    #[test]
    fn rate_limit_unit_projections_are_pairwise_distinct() {
        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
        // [`RateLimitUnit::window`] outputs must be pairwise distinct
        // across every arm — an accidental copy-paste flip that
        // reroutes one arm's suffix or window to also match another
        // silently collapses two arms onto one, so
        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
        // (both using `find` on `Self::ALL`) would return whichever
        // arm the linear scan lands on first — a match-arm-ordering-
        // dependent outcome the closed-set typed-enum shape is meant
        // to rule out structurally. Peer of the sibling
        // `caixa_kind_wire_consts_are_pairwise_distinct` /
        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
        // other closed-set typed-enum discriminator axes.
        let all = super::RateLimitUnit::ALL;
        for (i, a) in all.iter().enumerate() {
            for (j, b) in all.iter().enumerate() {
                if i != j {
                    assert_ne!(
                        a.as_suffix(),
                        b.as_suffix(),
                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
                         must be distinct — a collision silently collapses two \
                         arms onto one under from_suffix's linear scan"
                    );
                    assert_ne!(
                        a.window(),
                        b.window(),
                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
                         must be distinct — a collision silently collapses two \
                         arms onto one under from_window's linear scan"
                    );
                }
            }
        }
    }

    #[test]
    fn rate_limit_unit_display_routes_through_as_suffix() {
        // Route pin: [`std::fmt::Display`] must byte-equal
        // [`RateLimitUnit::as_suffix`] on every arm — the single
        // source of truth for the canonical suffix. A future
        // reimplementation that hand-rolls the arms instead of
        // delegating to [`RateLimitUnit::as_suffix`] would silently
        // desynchronize `format!("{u}")` from the codec's parse arm
        // (which uses `as_suffix` to compare suffixes). Peer of the
        // sibling `caixa_kind_display_routes_through_as_str_helper` /
        // `placement_strategy_display_routes_through_as_str_helper`
        // pins on the peer closed-set typed-enum Display axes.
        for unit in super::RateLimitUnit::ALL {
            assert_eq!(
                unit.to_string(),
                unit.as_suffix(),
                "RateLimitUnit::{unit:?} Display must route through \
                 as_suffix (single source of truth: the canonical suffix \
                 the codec parses and renders)"
            );
        }
    }

    #[test]
    fn rate_limit_unit_from_window_rejects_non_canonical() {
        // Rejection pin on the parser's accept-set: any Duration
        // outside the three-arm [`RateLimitUnit::window`] output set
        // (sub-second residue, or a second-magnitude outside `{1, 60,
        // 3600}`) must return `None`. A future accidental widening of
        // the accept-set (rounding down sub-second residue to the
        // nearest arm, admitting `Duration::from_secs(30)` as a
        // half-minute unit) would silently drift the parser's accept-
        // set from the emitter's — a validated slot with a
        // non-canonical window would then round-trip through the
        // codec to a canonical form the author never wrote.
        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
    }

    #[test]
    fn rate_limit_unit_from_suffix_rejects_unknown() {
        // Rejection pin on the suffix parser's accept-set: any string
        // outside the three-arm [`RateLimitUnit::as_suffix`] output
        // set must return `None`. Peer of the sibling
        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
        // the [`crate::CaixaKind`] `from_wire` accept-set.
        for bad in [
            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
            " s",
        ] {
            assert!(
                super::RateLimitUnit::from_suffix(bad).is_none(),
                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
                 outputs"
            );
        }
    }

    #[test]
    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
        // every canonical `:window` magnitude the validate gate
        // accepts must map to the paired [`RateLimitUnit`] arm through
        // this accessor. A future validate-gate rebrand that widened
        // the accepted-window set without extending [`RateLimitUnit`]
        // would silently split the accessor's `Some`-return set from
        // the validate gate's accept-set — a slot that satisfies
        // validate would land at the accessor with `None`, so a
        // consumer past validate that pattern-matches on the returned
        // `Some` would silently miss the newly-accepted magnitude.
        for (window_secs, expected) in [
            (1u64, super::RateLimitUnit::Second),
            (60, super::RateLimitUnit::Minute),
            (3600, super::RateLimitUnit::Hour),
        ] {
            let rl = RateLimit {
                rate: 100,
                window: Duration::from_secs(window_secs),
            };
            assert_eq!(
                rl.canonical_unit(),
                Some(expected),
                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
                 must return Some({expected:?})"
            );
        }
        // Non-canonical windows the validate gate rejects also return
        // None here — the accessor is the typed-enum projection of
        // the sibling `is_canonical_rate_limit_window` predicate.
        let bad = RateLimit {
            rate: 100,
            window: Duration::from_secs(30),
        };
        assert!(
            bad.canonical_unit().is_none(),
            "RateLimit with a non-canonical window must return None from \
             canonical_unit — the validate gate rejects the same set"
        );
    }

    #[test]
    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
        // Fail-before-pass-after byte-parity pin: for every canonical
        // window the [`rate_limit_codec::render`] arm's emitted string
        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
        // the vestigial free helper [`rate_limit_window_unit`] (a
        // `find_map`-walked `Duration → &'static str` delegate) onto the
        // substrate primitive [`RateLimit::canonical_unit`] typed method
        // (a closed-set `match self.window` arm on
        // [`RateLimitUnit::from_window`], projected through
        // [`RateLimitUnit::as_suffix`] via the enum's
        // [`std::fmt::Display`] impl). A future re-routing of the render
        // arm through a differently-computed unit projection would break
        // this pin at build time rather than as a silent per-consumer
        // codec round-trip drift far from the substrate primitive edit.
        //
        // Sibling to the peer
        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
        // on the free-helper axis: that pin locks the two projections
        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
        // on the closed-set arm table; this pin locks the codec's render
        // arm reads through the typed accessor rather than the free
        // helper. Two production consumers of the canonical-unit axis
        // now key off one typed dispatch on the substrate primitive.
        for (window_secs, unit) in [
            (1u64, super::RateLimitUnit::Second),
            (60, super::RateLimitUnit::Minute),
            (3600, super::RateLimitUnit::Hour),
        ] {
            let rl = RateLimit {
                rate: 42,
                window: Duration::from_secs(window_secs),
            };
            let policy = MeshPolicy {
                rate_limit: Some(rl),
                ..Default::default()
            };
            let json = serde_json::to_string(&policy).unwrap();
            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
            assert!(
                json.contains(&expected),
                "rate_limit_codec::render must emit {expected} (via \
                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
            );
            // And the accessor route resolves to the same typed unit
            // the render arm's Display formatting is asked to produce —
            // so a future edit that split the two paths (one through
            // the accessor, one through a re-introduced free helper)
            // trips this pin.
            assert_eq!(
                rl.canonical_unit(),
                Some(unit),
                "RateLimit::canonical_unit must return Some({unit:?}) for a \
                 {window_secs}s window; the codec render arm reads the same \
                 typed unit through this accessor"
            );
        }
    }

    #[test]
    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
        // Fail-before-pass-after byte-parity pin on the validate gate's
        // canonical-window shape probe: every non-canonical `:window`
        // the free-helper predicate [`is_canonical_rate_limit_window`]
        // rejects is also rejected by the substrate primitive
        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
        // gate now reads through, and vice versa on the accepted set
        // (the three canonical windows). Locks the migration from the
        // free helper onto the substrate primitive: a future re-routing
        // of one of the two paths through a differently-computed unit
        // projection would silently split the codec's accepted set from
        // the validate gate's accepted set — a two-consumer drift the
        // codec-round-trip pin
        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
        // above closes on the render arm and this pin closes on the
        // validate arm.
        for canonical_window_secs in [1u64, 60, 3600] {
            let mut s = three_member_spec();
            let rl = RateLimit {
                rate: 100,
                window: Duration::from_secs(canonical_window_secs),
            };
            s.politicas.rate_limit = Some(rl);
            assert!(
                s.validate().is_ok(),
                "canonical {canonical_window_secs}s window must pass \
                 validate_politicas — the validate gate now reads \
                 RateLimit::canonical_unit().is_none() and the accessor \
                 returns Some on every canonical arm"
            );
            assert!(
                rl.canonical_unit().is_some(),
                "canonical {canonical_window_secs}s window must resolve to \
                 Some on RateLimit::canonical_unit — the validate gate reads \
                 this accessor directly"
            );
        }
        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
            let mut s = three_member_spec();
            let rl = RateLimit {
                rate: 100,
                window: Duration::from_secs(non_canonical_window_secs),
            };
            s.politicas.rate_limit = Some(rl);
            assert_eq!(
                s.validate().unwrap_err(),
                AplicacaoError::PolicyRateLimitWindowNotCanonical {
                    window: rl.window(),
                },
                "non-canonical {non_canonical_window_secs}s window must be \
                 rejected by validate_politicas — the validate gate now \
                 keys off RateLimit::canonical_unit().is_none()"
            );
            assert!(
                rl.canonical_unit().is_none(),
                "non-canonical {non_canonical_window_secs}s window must \
                 resolve to None on RateLimit::canonical_unit — the two \
                 paths (the free helper the validate gate previously read \
                 and the substrate primitive the validate gate now reads) \
                 must agree on the same rejected set"
            );
        }
        // And the substrate-primitive [`RateLimit::canonical_unit`]
        // accessor's accepted-window set matches the codec's parse arm's
        // accepted-suffix set on every canonical / non-canonical shape,
        // so a future silent drift between the codec's accepted set and
        // the validate gate's accepted set is a build error at test time
        // (both consumers key off the same closed-set enum's `match self`
        // arms). The predecessor free helper `is_canonical_rate_limit_window`
        // — a delegate that composed [`RateLimitUnit::from_window`] with
        // `.is_some()` — was deleted after this migration; the
        // canonical-window set now lives on exactly one typed dispatch
        // on the substrate primitive.
        for (secs, expected) in [
            (1u64, true),
            (60, true),
            (3600, true),
            (2, false),
            (30, false),
            (86_400, false),
        ] {
            let window = Duration::from_secs(secs);
            let rl = RateLimit { rate: 1, window };
            assert_eq!(
                rl.canonical_unit().is_some(),
                expected,
                "RateLimit::canonical_unit().is_some() must agree with the \
                 codec-accepted canonical-window set on {secs}s"
            );
            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
                1 => "s",
                60 => "m",
                3600 => "h",
                _ => return,
            })
            .is_some_and(|d| d == window);
            if expected {
                assert!(
                    suffix_from_axis,
                    "the codec's `&str → Duration` axis \
                     ({secs}s) must round-trip to the same Duration the \
                     substrate primitive's accessor returns Some on"
                );
            }
        }
    }

    #[test]
    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
        // derive: for each of the three variants, exactly one of the
        // generated `is_second` / `is_minute` / `is_hour` predicates
        // returns `true` and the other two return `false`. Peer of
        // the sibling
        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
        // sibling `IsVariant`-derived closed-set typed-enum pins.
        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
            (super::RateLimitUnit::Second, [true, false, false]),
            (super::RateLimitUnit::Minute, [false, true, false]),
            (super::RateLimitUnit::Hour, [false, false, true]),
        ];
        for (variant, expected) in rows {
            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
            assert_eq!(
                observed, expected,
                "RateLimitUnit::{variant:?} is_* predicates must partition \
                 the arm set (second, minute, hour); got {observed:?}"
            );
        }
    }

    #[test]
    fn rejects_policy_timeout_sub_millisecond() {
        // A purely sub-millisecond `Duration` (`from_micros(500)` =
        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
        // arm passes — but `as_millis() == 0`, so the shared codec's
        // `render` arm returns the literal `"0s"`, which the
        // codec's `parse` arm then deserializes as `Duration::ZERO`
        // and the `PolicyTimeoutZero` zero-floor gate would reject
        // on re-validate. Pin the rejection at the typed slot's
        // canonical-floor gate so the round-trip break surfaces at
        // validate time, naming the offending `Duration`, rather
        // than at the next serialize → deserialize round-trip far
        // from the source `caixa.lisp`.
        let mut s = three_member_spec();
        let timeout = Duration::from_micros(500);
        s.politicas.timeout = Some(timeout);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
        );
    }

    #[test]
    fn rejects_policy_timeout_non_integer_millisecond() {
        // A `Duration` with non-integer-millisecond residue
        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
        // through the shared codec's `render` arm as `"1ms"` (the
        // `as_millis()` floor truncates), which the codec's `parse`
        // arm then deserializes as `Duration::from_millis(1)` =
        // 1_000_000 ns — silently *different* from the original.
        // Pin the rejection so this round-trip break surfaces at
        // validate time, where the offending `Duration` is named,
        // rather than as a silent value-laundered round-trip on the
        // next codec round-trip.
        let mut s = three_member_spec();
        let timeout = Duration::from_micros(1500);
        s.politicas.timeout = Some(timeout);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
        );
    }

    #[test]
    fn accepts_policy_timeout_integer_millisecond_forms() {
        // The codec's accepted set — integer multiples of 1ms — is
        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
        // `1h` all pass the canonical gate. Pin the canonical-forms
        // sweep so a future tightening of the codec's grammar (e.g.
        // dropping `:ms`) surfaces here as a test failure rather
        // than a silent contract narrowing on the typed slot.
        for timeout in [
            Duration::from_millis(1),
            Duration::from_millis(500),
            Duration::from_millis(1500),
            Duration::from_secs(30),
            Duration::from_secs(120),
            Duration::from_secs(3600),
        ] {
            let mut s = three_member_spec();
            s.politicas.timeout = Some(timeout);
            s.validate()
                .expect("integer-millisecond :timeout must validate");
        }
    }

    #[test]
    fn policy_timeout_zero_takes_precedence_over_canonical() {
        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
        // pass the canonical-millisecond gate; the more self-locating
        // `PolicyTimeoutZero` arm (which names the omit-axis
        // remediation directly) must fire first. Pin the ordering so
        // a future refactor that reorders the arms surfaces here as a
        // test failure rather than a silent diagnostic regression.
        let mut s = three_member_spec();
        s.politicas.timeout = Some(Duration::ZERO);
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
    }

    #[test]
    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
        // The diagnostic envelope carries the offending `Duration`
        // verbatim so the author can grep their `caixa.lisp` for
        // `:timeout "<value>"` and fix it in one edit. Same
        // diagnostic shape every other typed-slot canonical-form
        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
        // peer `:rate-limit :window` axis.
        let mut s = three_member_spec();
        let timeout = Duration::from_nanos(1_000_001);
        s.politicas.timeout = Some(timeout);
        match s.validate().unwrap_err() {
            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
            }
            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
        }
    }

    #[test]
    fn rejects_policy_timeout_above_cap() {
        // The fail-before-pass-after pin: 3601s = 1h + 1s is
        // structurally one canonical-tick past the
        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
        // integer-millisecond magnitude the canonical-form arm above
        // accepts cleanly, that the codec round-trips losslessly as
        // `"3601s"`, and that silently passed validate on every
        // pre-gate codebase because the typed slot's only checks were
        // the zero-floor and canonical-form arms. The mesh-level
        // deadline degenerates only at the runtime substrate (Envoy
        // / Cilium L7 timeout overlay) far from the source
        // `caixa.lisp` with no field naming the offending policy.
        let mut s = three_member_spec();
        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
        s.politicas.timeout = Some(timeout);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
        );
    }

    #[test]
    fn rejects_policy_timeout_one_millisecond_above_cap() {
        // Boundary case: exactly 1ms past the cap (the granularity
        // the canonical-form gate enforces). Catches a future
        // "strictly less than" half-measure and pins the diagnostic
        // to name the offending `Duration` verbatim. Peer of
        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
        // boundary pin on the sibling `:limits :memory` top edge.
        let mut s = three_member_spec();
        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
        s.politicas.timeout = Some(timeout);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
        );
    }

    #[test]
    fn rejects_policy_timeout_far_above_cap() {
        // The "obvious authoring footgun" case: a `(:timeout "24h")`
        // or `(:timeout "86400s")` — values the canonical-form arm
        // accepts as integer-millisecond magnitudes, the codec
        // round-trips losslessly through serde, but the mesh-level
        // policy cannot honor (a 24-hour synchronous-`:contratos`
        // deadline is operationally indistinguishable from
        // omit-the-axis). Until this gate landed validate accepted
        // it. Pin both common above-cap values (24h, 7d) so a future
        // relaxation that drops the upper bound surfaces here.
        for timeout in [
            Duration::from_secs(86_400),    // 24h
            Duration::from_secs(604_800),   // 7d
            Duration::from_secs(1_000_000), // ~11.5 days
        ] {
            let mut s = three_member_spec();
            s.politicas.timeout = Some(timeout);
            assert_eq!(
                s.validate().unwrap_err(),
                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
            );
        }
    }

    #[test]
    fn accepts_policy_timeout_at_cap() {
        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
        // must validate. The cap is inclusive on the top edge,
        // matching the [`POLICY_RETRIES_MAX`] /
        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
        // sibling capped axes. Pin the boundary explicitly so a
        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
        // instead of `>`) surfaces here as a test failure rather
        // than a silent contract narrowing.
        let mut s = three_member_spec();
        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
        s.validate()
            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
    }

    #[test]
    fn accepts_policy_timeout_typical_values() {
        // The documented production-playbook band positive-control
        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
        // plus a sweep through the long-running-workflow band
        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
        // validated set explicitly so a future tightening of the
        // ceiling surfaces here as a deliberate test edit, not a
        // silent contract narrowing.
        for timeout in [
            Duration::from_millis(1),
            Duration::from_millis(500),
            Duration::from_secs(1),
            Duration::from_secs(10),
            Duration::from_secs(15), // Envoy default
            Duration::from_secs(30),
            Duration::from_secs(60), // AWS App Mesh typical
            Duration::from_secs(300),
            Duration::from_secs(900),
            Duration::from_secs(1800),
            Duration::from_secs(3600), // exactly 1h, the cap
        ] {
            let mut s = three_member_spec();
            s.politicas.timeout = Some(timeout);
            s.validate()
                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
        }
    }

    #[test]
    fn policy_timeout_zero_takes_precedence_over_cap() {
        // The cross-arm ordering pin: `Duration::ZERO` is
        // structurally outside both `>= 1ms` (zero-floor) and
        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
        // diagnostic is the more self-locating one (it directly
        // names the omit-axis remediation), so the validate gate
        // must fire on zero first. Same shape every other
        // zero-then-shape ordering on this surface uses
        // ([`AplicacaoError::PolicyRetriesZero`] then
        // [`AplicacaoError::PolicyRetriesExceedsCap`];
        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
        let mut s = three_member_spec();
        s.politicas.timeout = Some(Duration::ZERO);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutZero,
            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
        );
    }

    #[test]
    fn policy_timeout_canonical_takes_precedence_over_cap() {
        // The cross-arm ordering pin: a `Duration` that is *both*
        // sub-millisecond (non-canonical-form) and structurally
        // above the cap surfaces the canonical-form diagnostic
        // first, because the round-trip-shape break is the more
        // fundamental issue (the value can't even round-trip
        // through the codec, so the cap diagnostic naming
        // `1ms..=1h` would be misleading — there's no integer-ms
        // form of the offending value). Pin the order so a future
        // refactor that reorders the arms surfaces here as a test
        // failure rather than a silent diagnostic regression.
        let mut s = three_member_spec();
        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
        // *and* total magnitude above the 1h cap.
        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
        s.politicas.timeout = Some(timeout);
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
        );
    }

    #[test]
    fn policy_timeout_cap_diagnostic_carries_offending_value() {
        // The diagnostic-shape pin: the offending `Duration` is
        // carried verbatim into the
        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
        // surfaced error message names the value the author wrote
        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
        // exceeds the mesh-policy ceiling …"`), not just the cap.
        // Same self-locating diagnostic shape every other typed-cap
        // arm on this surface carries
        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
        // offending retry count verbatim).
        let mut s = three_member_spec();
        let timeout = Duration::from_secs(7200); // 2h
        s.politicas.timeout = Some(timeout);
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
            "got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("7200"),
            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
        );
    }

    #[test]
    fn policy_timeout_cap_pins_canonical_value() {
        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
        // the shared duration codec emits as a clean canonical
        // string (`"<n>h"`). Pinning the literal value here surfaces
        // a future drift (a relaxation to 24h, a tightening to 5m)
        // as a deliberate test edit, not a silent contract
        // narrowing. Same shape every other typed-cap value pin on
        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
    }

    #[test]
    fn policy_timeout_cap_value_round_trips_through_codec() {
        // The codec round-trip property the cap arm preserves: the
        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
        // the shared duration codec — every value at the cap renders
        // to a clean canonical string (`"1h"`) and parses back to
        // the same `Duration`. Pin this so a future drift between
        // the cap constant and the codec's largest emitted unit
        // surfaces here. Same shape every other typed boundary pin
        // on this surface uses
        // (`wasm32_memory_cap_matches_parsed_4_gib`).
        let policy = MeshPolicy {
            timeout: Some(POLICY_TIMEOUT_MAX),
            ..Default::default()
        };
        let json = serde_json::to_string(&policy).unwrap();
        // The codec emits `"1h"` for the canonical 1-hour magnitude.
        assert!(
            json.contains("\"1h\""),
            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
        );
        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
    }

    #[test]
    fn rejects_circuit_breaker_window_sub_millisecond() {
        // Peer of the `:timeout` sub-millisecond arm on the second
        // typed-`Duration` `:politicas` axis: a purely sub-ms
        // `Duration` (`from_micros(500)`) renders through the shared
        // codec as `"0s"`, which the codec parses back to
        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
        // zero-floor gate then rejects on re-validate.
        let mut s = three_member_spec();
        let window = Duration::from_micros(500);
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
        );
    }

    #[test]
    fn rejects_circuit_breaker_window_non_integer_millisecond() {
        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
        // with non-integer-millisecond residue renders through the
        // shared codec as the truncated `"<n>ms"` form, parsing back
        // to a *different* `Duration` on the next round-trip.
        let mut s = three_member_spec();
        let window = Duration::from_micros(1500);
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
        );
    }

    #[test]
    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
        // The canonical-forms sweep on the breaker axis: every
        // integer-ms multiple the codec round-trips losslessly
        // passes the canonical gate.
        for window in [
            Duration::from_millis(1),
            Duration::from_millis(500),
            Duration::from_millis(1500),
            Duration::from_secs(30),
            Duration::from_secs(60),
            Duration::from_secs(3600),
        ] {
            let mut s = three_member_spec();
            s.politicas.circuit_breaker = Some(CircuitBreaker {
                max_failures: 5,
                window,
            });
            s.validate()
                .expect("integer-millisecond :circuit-breaker :window must validate");
        }
    }

    #[test]
    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
        // `Duration::ZERO` would pass the canonical-ms gate (the
        // sub-ns residue is zero) but must surface the narrower
        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
        // remediation.
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window: Duration::ZERO,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerZeroWindow
        );
    }

    #[test]
    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
        // Both axes invalid: max_failures == 0 *and* window is
        // sub-ms. The validate gate must fire on max_failures first
        // (matching the existing ordering pin
        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
        // the existing diagnostic continues to lead with the simpler
        // "zero threshold" framing.
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 0,
            window: Duration::from_micros(500),
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerZeroFailures
        );
    }

    #[test]
    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
        let mut s = three_member_spec();
        let window = Duration::from_nanos(60_000_000_001);
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window,
        });
        match s.validate().unwrap_err() {
            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
                assert_eq!(w, window, "diagnostic must carry the offending Duration");
            }
            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
        }
    }

    #[test]
    fn rejects_circuit_breaker_window_above_cap() {
        // The fail-before-pass-after pin: 3601s = 1h + 1s is
        // structurally one canonical-tick past the
        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
        // integer-millisecond magnitude the canonical-form arm above
        // accepts cleanly, that the codec round-trips losslessly as
        // `"3601s"`, and that silently passed validate on every
        // pre-gate codebase because the typed slot's only checks were
        // the zero-floor and canonical-form arms. The
        // rolling-window-to-lifetime-counter degeneration surfaces
        // only at the runtime substrate (Envoy's outlier_detection
        // interval, the future CiliumClusterwideEnvoyConfig overlay)
        // far from the source `caixa.lisp` with no field naming the
        // offending policy.
        let mut s = three_member_spec();
        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
        );
    }

    #[test]
    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
        // Boundary case: exactly 1ms past the cap (the granularity the
        // canonical-form gate enforces). Catches a future "strictly
        // less than" half-measure and pins the diagnostic to name the
        // offending `Duration` verbatim. Peer of
        // `rejects_policy_timeout_one_millisecond_above_cap` on the
        // sibling duration-typed `:politicas :timeout` top edge.
        let mut s = three_member_spec();
        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
        );
    }

    #[test]
    fn rejects_circuit_breaker_window_far_above_cap() {
        // The "obvious authoring footgun" case: a `(:window "24h")` or
        // `(:window "86400s")` — values the canonical-form arm
        // accepts as integer-millisecond magnitudes, the codec
        // round-trips losslessly through serde, but the
        // rolling-window breaker contract cannot honor (a 24-hour
        // rolling failure window is operationally a lifetime counter).
        // Until this gate landed validate accepted it. Pin both common
        // above-cap values (24h, 7d) so a future relaxation that
        // drops the upper bound surfaces here.
        for window in [
            Duration::from_secs(86_400),    // 24h
            Duration::from_secs(604_800),   // 7d
            Duration::from_secs(1_000_000), // ~11.5 days
        ] {
            let mut s = three_member_spec();
            s.politicas.circuit_breaker = Some(CircuitBreaker {
                max_failures: 5,
                window,
            });
            assert_eq!(
                s.validate().unwrap_err(),
                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
            );
        }
    }

    #[test]
    fn accepts_circuit_breaker_window_at_cap() {
        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
        // (1h) — must validate. The cap is inclusive on the top edge,
        // matching the [`POLICY_TIMEOUT_MAX`] /
        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
        // sibling capped axes. Pin the boundary explicitly so a
        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
        // instead of `>`) surfaces here as a test failure rather than
        // a silent contract narrowing.
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window: POLICY_BREAKER_WINDOW_MAX,
        });
        s.validate()
            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
    }

    #[test]
    fn accepts_circuit_breaker_window_typical_values() {
        // The documented production-playbook band positive-control
        // sweep — every value Hystrix / resilience4j / Istio / Envoy
        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
        // through the long-tail failure-detection band (15m, 30m, 1h)
        // the cap accepts. Pin the inclusive validated set explicitly
        // so a future tightening of the ceiling surfaces here as a
        // deliberate test edit, not a silent contract narrowing.
        for window in [
            Duration::from_millis(1),
            Duration::from_millis(500),
            Duration::from_secs(1),
            Duration::from_secs(10), // Hystrix / Istio / Envoy default
            Duration::from_secs(30),
            Duration::from_secs(60),  // resilience4j typical
            Duration::from_secs(300), // AWS App Mesh typical
            Duration::from_secs(900),
            Duration::from_secs(1800),
            Duration::from_secs(3600), // exactly 1h, the cap
        ] {
            let mut s = three_member_spec();
            s.politicas.circuit_breaker = Some(CircuitBreaker {
                max_failures: 5,
                window,
            });
            s.validate()
                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
        }
    }

    #[test]
    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
        // The cross-arm ordering pin: `Duration::ZERO` is structurally
        // outside both `>= 1ms` (zero-floor) and
        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
        // diagnostic is the more self-locating one (it directly names
        // the omit-axis remediation), so the validate gate must fire
        // on zero first. Same shape every other zero-then-cap
        // ordering on this surface uses
        // ([`AplicacaoError::PolicyTimeoutZero`] then
        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
        let mut s = three_member_spec();
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window: Duration::ZERO,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerZeroWindow,
            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
        );
    }

    #[test]
    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
        // The cross-arm ordering pin: a `Duration` that is *both*
        // sub-millisecond (non-canonical-form) and structurally above
        // the cap surfaces the canonical-form diagnostic first,
        // because the round-trip-shape break is the more fundamental
        // issue (the value can't even round-trip through the codec, so
        // the cap diagnostic naming `1ms..=1h` would be misleading —
        // there's no integer-ms form of the offending value). Pin the
        // order so a future refactor that reorders the arms surfaces
        // here as a test failure rather than a silent diagnostic
        // regression. Peer of
        // `policy_timeout_canonical_takes_precedence_over_cap` on the
        // sibling duration-typed `:politicas :timeout` axis.
        let mut s = three_member_spec();
        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
        );
    }

    #[test]
    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
        // The cross-arm ordering pin between the two breaker axes: a
        // `CircuitBreaker` whose *both* `max_failures` is above its
        // cap *and* `window` is above its cap surfaces the
        // max-failures cap diagnostic first, because the validate
        // gate visits the failures arm before the window arm. Pin the
        // order so a future refactor that reorders the breaker arms
        // surfaces here.
        let mut s = three_member_spec();
        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
            window,
        });
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
            },
            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
        );
    }

    #[test]
    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
        // The diagnostic-shape pin: the offending `Duration` is
        // carried verbatim into the
        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
        // the surfaced error message names the value the author wrote
        // (`":politicas :circuit-breaker :window (Duration { secs:
        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
        // just the cap. Same self-locating diagnostic shape every
        // other typed-cap arm on this surface carries
        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
        // offending `Duration` verbatim).
        let mut s = three_member_spec();
        let window = Duration::from_secs(7200); // 2h
        s.politicas.circuit_breaker = Some(CircuitBreaker {
            max_failures: 5,
            window,
        });
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
            "got {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("7200"),
            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
        );
    }

    #[test]
    fn circuit_breaker_window_cap_pins_canonical_value() {
        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
        // shared duration codec emits as a clean canonical string
        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
        // the sibling duration-typed `:politicas :timeout` axis (the
        // two duration-typed `:politicas` axes share a uniform top
        // edge). Pinning the literal value here surfaces a future
        // drift (a relaxation to 24h, a tightening to 5m) as a
        // deliberate test edit, not a silent contract narrowing. Same
        // shape every other typed-cap value pin on this surface uses
        // (`policy_timeout_cap_pins_canonical_value`).
        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
        assert_eq!(
            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
            "the two duration-typed `:politicas` caps share the same top edge"
        );
    }

    #[test]
    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
        // The codec round-trip property the cap arm preserves: the
        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
        // through the shared duration codec — every value at the cap
        // renders to a clean canonical string (`"1h"`) and parses back
        // to the same `Duration`. Pin this so a future drift between
        // the cap constant and the codec's largest emitted unit
        // surfaces here. Same shape every other typed boundary pin on
        // this surface uses
        // (`policy_timeout_cap_value_round_trips_through_codec`).
        let policy = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 5,
                window: POLICY_BREAKER_WINDOW_MAX,
            }),
            ..Default::default()
        };
        let json = serde_json::to_string(&policy).unwrap();
        // The codec emits `"1h"` for the canonical 1-hour magnitude.
        assert!(
            json.contains("\"1h\""),
            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
        );
        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(
            back.circuit_breaker.unwrap().window,
            POLICY_BREAKER_WINDOW_MAX
        );
    }

    #[test]
    fn is_integer_millisecond_duration_predicate_tracks_codec() {
        // Pin the predicate's accepted set against the codec's
        // accepted set explicitly. The codec parses
        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
        // accepted value is an integer-millisecond multiple — so the
        // predicate must accept exactly that set. Same shape every
        // other predicate-on-the-typed-slot helper carries
        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
        // Read directly from the codec-owned predicate — the crate's
        // single source of truth every typed-`Duration` axis now routes
        // through via
        // [`crate::render::require_positive_canonical_bounded_duration`].
        use super::supervisor::duration_codec::is_integer_millisecond_duration;
        assert!(is_integer_millisecond_duration(Duration::ZERO));
        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
        // Non-integer-millisecond residue: rejected.
        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
        assert!(!is_integer_millisecond_duration(Duration::from_micros(
            1500
        )));
        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
            999_999
        )));
        // The 1-ns-past-1ms boundary: rejected (no longer a clean
        // integer-millisecond multiple).
        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
            1_000_001
        )));
    }

    #[test]
    fn policy_timeout_validated_value_round_trips_through_codec() {
        // The structural property the canonical-ms gate enforces:
        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
        // round-trips losslessly through the shared `duration_codec`
        // (serialize → string → deserialize → equal value). Pin this
        // end-to-end so a future change to either side (the validate
        // gate's accepted granularity, the codec's parse/render unit
        // set) that breaks the alignment surfaces here. The
        // previous-state shape (typed slot accepts arbitrary
        // `Duration`, codec only round-trips integer-ms) would fail
        // this test for any `Duration::from_micros(1500)` timeout —
        // the validate gate now forecloses that.
        for timeout in [
            Duration::from_millis(1),
            Duration::from_millis(1500),
            Duration::from_secs(30),
            Duration::from_secs(3600),
        ] {
            let mut s = three_member_spec();
            s.politicas.timeout = Some(timeout);
            s.validate().unwrap();
            let json = serde_json::to_string(&s.politicas).unwrap();
            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
            assert_eq!(
                back.timeout, s.politicas.timeout,
                "every validated :timeout must round-trip losslessly through the codec"
            );
        }
    }

    #[test]
    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
        // Peer of the `:timeout` round-trip property on the breaker
        // axis.
        for window in [
            Duration::from_millis(1),
            Duration::from_millis(1500),
            Duration::from_secs(30),
            Duration::from_secs(3600),
        ] {
            let mut s = three_member_spec();
            s.politicas.circuit_breaker = Some(CircuitBreaker {
                max_failures: 5,
                window,
            });
            s.validate().unwrap();
            let json = serde_json::to_string(&s.politicas).unwrap();
            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
            assert_eq!(
                back.circuit_breaker.unwrap().window,
                window,
                "every validated :circuit-breaker :window must round-trip losslessly"
            );
        }
    }

    #[test]
    fn empty_politicas_validates() {
        // Omitting every policy axis is fine — defaults express "no
        // policy on this axis", not "policy = 0". The fixture's typical
        // values continue to validate; this test pins that
        // MeshPolicy::default() is a clean pass through validate().
        let mut s = three_member_spec();
        s.politicas = MeshPolicy::default();
        s.validate().unwrap();
    }

    #[test]
    fn typical_politicas_validates_with_every_axis_set() {
        // The full §III.1 example block (timeout + retries + breaker +
        // mtls + rate-limit) — every axis nonzero — must remain a
        // clean pass.
        let mut s = three_member_spec();
        s.politicas = MeshPolicy {
            timeout: Some(Duration::from_secs(30)),
            retries: Some(3),
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 5,
                window: Duration::from_secs(60),
            }),
            mtls_required: Some(true),
            rate_limit: Some(RateLimit {
                rate: 100,
                window: Duration::from_secs(1),
            }),
        };
        s.validate().unwrap();
    }

    #[test]
    fn rejects_empty_cluster_name() {
        let mut s = three_member_spec();
        s.placement.clusters = vec!["rio".into(), "".into()];
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PlacementClusterEmpty
        );
    }

    #[test]
    fn rejects_duplicate_cluster_names() {
        let mut s = three_member_spec();
        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_cluster_with_uppercase() {
        // The canonical "I copied the cluster's display name verbatim"
        // typo — K8s context names are lowercase per DNS-1123 label
        // rule, but org docs often round-trip a TitleCase identifier
        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
        // on the peer name axis.
        let mut s = three_member_spec();
        s.placement.clusters = vec!["Rio".into(), "mar".into()];
        let err = s.validate().unwrap_err();
        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
            panic!("expected PlacementClusterInvalid, got other variant");
        };
        assert_eq!(cluster, "Rio");
        assert!(
            reason.contains("uppercase"),
            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
        );
        assert!(
            reason.contains("\"rio\""),
            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
        );
    }

    #[test]
    fn rejects_placement_cluster_with_underscore() {
        // The canonical "I'm thinking of an env var / hostname slug"
        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
        // schema. K8s context filtering on `my_cluster` silently misses
        // the cluster the author intended; the gate moves it to caixa-
        // build time. Same shape as `rejects_membro_caixa_with_underscore`
        // (3f9d7a0).
        let mut s = three_member_spec();
        s.placement.clusters = vec!["my_cluster".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
                    if cluster == "my_cluster" && reason.contains('_')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_cluster_with_dot() {
        // A `:placement :clusters` entry is a single DNS-1123 *label*,
        // not a subdomain — even though K8s context names sometimes
        // carry a dotted form via kubeconfig conventions, the strictest
        // floor among the use sites (DNS-1035 cluster.x-k8s.io
        // `metadata.name`, Cilium identity label values) wins. The "I
        // want to namespace my cluster names with `.`" intent is
        // expressed via `-` (`mar-east`).
        let mut s = three_member_spec();
        s.placement.clusters = vec!["team.rio".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
                    if cluster == "team.rio" && reason.contains('.')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_cluster_with_leading_hyphen() {
        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
        // with an alphanumeric. The K8s apiserver rejects `-rio`
        // outright; the rendered fan-out would emit a `metadata.name:
        // "-rio"` that fails admission far from the source caixa.lisp.
        let mut s = three_member_spec();
        s.placement.clusters = vec!["-rio".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
                    if cluster == "-rio" && reason.contains("start and end")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_cluster_with_trailing_hyphen() {
        // The symmetric arm of the boundary rule. Pin separately so
        // both ends are covered against a future relaxation that only
        // checks one boundary (parallel to
        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
        let mut s = three_member_spec();
        s.placement.clusters = vec!["rio-".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
                    if cluster == "rio-"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_cluster_with_unicode() {
        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
        // before it reaches K8s. The byte-by-byte ASCII validity check
        // rejects multi-byte UTF-8 sequences by the first byte that
        // fails `[a-z0-9-]`.
        let mut s = three_member_spec();
        s.placement.clusters = vec!["rió".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
                    if cluster == "rió"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_cluster_with_whitespace() {
        // Whitespace is the canonical "I pasted from a sketch / doc"
        // footgun. The apiserver rejects every cluster `metadata.name`
        // value carrying whitespace.
        let mut s = three_member_spec();
        s.placement.clusters = vec!["rio cluster".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
                    if cluster == "rio cluster"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_cluster_too_long() {
        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
        // pin. The diagnostic names both the cap (63) and the actual
        // length so the author can shorten in one edit. Mirrors
        // `rejects_membro_caixa_too_long` (3f9d7a0).
        let mut s = three_member_spec();
        let too_long = "a".repeat(64);
        s.placement.clusters = vec![too_long.clone()];
        let err = s.validate().unwrap_err();
        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
            panic!("expected PlacementClusterInvalid");
        };
        assert_eq!(cluster, too_long);
        assert!(
            reason.contains("63") && reason.contains("64"),
            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
        );
    }

    #[test]
    fn placement_cluster_max_length_validates() {
        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
        // future tightening (e.g. dropping to 62) surfaces here as a
        // regression, mirroring `membro_caixa_max_length_validates`
        // (3f9d7a0).
        let mut s = three_member_spec();
        s.placement.clusters = vec!["a".repeat(63)];
        s.validate().unwrap();
    }

    #[test]
    fn accepts_canonical_placement_cluster_forms() {
        // The DNS-1123 label shapes a caixa author is realistically
        // going to write for cluster names: single-word lowercase
        // (`rio`), regional hyphen-joined (`mar-east`), single
        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
        // Pin every leg so a future tightening that bans (e.g.) digit-
        // start identifiers surfaces here.
        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
            let mut s = three_member_spec();
            s.placement.clusters = vec![form.into()];
            s.validate().unwrap_or_else(|e| {
                panic!("canonical cluster form {form:?} must validate, got {e:?}")
            });
        }
    }

    #[test]
    fn placement_cluster_empty_takes_precedence_over_invalid() {
        // Order pin: the existing `PlacementClusterEmpty` diagnostic
        // (which doesn't try to parse) fires before the new
        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
        // `:clusters` entry keeps its narrower error message — the new
        // gate would also reject `""`, but the empty-string arm is the
        // more self-locating diagnostic. Mirrors the
        // `membro_caixa_empty_takes_precedence_over_invalid` pin
        // (3f9d7a0).
        let mut s = three_member_spec();
        s.placement.clusters = vec!["rio".into(), "".into()];
        let err = s.validate().unwrap_err();
        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
    }

    #[test]
    fn placement_cluster_invalid_fires_before_duplicate_check() {
        // Order pin: a malformed-shape `:clusters` entry surfaces *its
        // own* diagnostic, even when a later entry would otherwise
        // collapse onto a duplicate name. The per-entry shape gate runs
        // inline before the duplicate-key insert, parallel to
        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
        let mut s = three_member_spec();
        s.placement.clusters = vec!["Rio".into(), "rio".into()];
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
        // The diagnostic-shape pin: the error names the offending
        // `:clusters` value verbatim so the author can grep their
        // caixa.lisp without re-running the build, and carries a
        // non-empty `reason` naming the specific violation. Same shape
        // every typed-shape gate enshrines
        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
        let mut s = three_member_spec();
        s.placement.clusters = vec!["BAD_CLUSTER".into()];
        let err = s.validate().unwrap_err();
        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
            panic!("expected PlacementClusterInvalid");
        };
        assert_eq!(cluster, "BAD_CLUSTER");
        assert!(
            !reason.is_empty(),
            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
        );
    }

    #[test]
    fn rejects_sharded_with_empty_clusters() {
        // §III.1: Sharded uses :clusters as the shard pool. An empty
        // pool means "shard across no clusters" — meaningless, same as
        // Replicated with no hosts.
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::Sharded;
        s.placement.shard_key = Some("$tenantId".into());
        s.placement.clusters = vec![];
        assert!(matches!(
            s.validate().unwrap_err(),
            AplicacaoError::PlacementWithoutClusters {
                estrategia: PlacementStrategy::Sharded
            }
        ));
    }

    #[test]
    fn rejects_sharded_with_empty_shard_key() {
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::Sharded;
        s.placement.shard_key = Some("".into());
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
    }

    #[test]
    fn rejects_shard_key_under_replicated_strategy() {
        // The fail-before-pass-after pin: a `:placement (:estrategia
        // Replicated :shard-key "tenantId")` manifest carries the
        // hash-keyed-distribution slot on a strategy that never consumes
        // it. Before the gate the typed slot's value silently vanished
        // at the renderer layer (caixa-mesh emits `placement.shardKey`
        // verbatim regardless of strategy; the Akka-style cluster-
        // sharding reconciler keys off `estrategia == Sharded` and
        // ignores the slot otherwise), with no diagnostic. Lifting the
        // rejection to a build-time gate makes the
        // `shard_key.is_some() == matches!(estrategia, Sharded)`
        // partition a structural property of every validated
        // [`Placement`].
        let mut s = three_member_spec();
        // The fixture already uses Replicated; just add a shard-key.
        s.placement.shard_key = Some("$tenantId".into());
        let err = s.validate().unwrap_err();
        let AplicacaoError::ShardKeyOnNonSharded {
            estrategia,
            shard_key,
        } = err
        else {
            panic!("expected ShardKeyOnNonSharded, got {err:?}");
        };
        assert_eq!(estrategia, PlacementStrategy::Replicated);
        assert_eq!(shard_key, "$tenantId");
    }

    #[test]
    fn rejects_shard_key_under_singlenode_strategy() {
        // Peer of the Replicated case above on the SingleNode arm: OTP
        // distributed-app takeover (one cluster runs at a time) has no
        // hash-keyed routing axis to consume `:shard-key` either, so
        // the rejection fires on both non-Sharded arms uniformly.
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::SingleNode;
        s.placement.shard_key = Some("$tenantId".into());
        let err = s.validate().unwrap_err();
        let AplicacaoError::ShardKeyOnNonSharded {
            estrategia,
            shard_key,
        } = err
        else {
            panic!("expected ShardKeyOnNonSharded, got {err:?}");
        };
        assert_eq!(estrategia, PlacementStrategy::SingleNode);
        assert_eq!(shard_key, "$tenantId");
    }

    #[test]
    fn rejects_empty_shard_key_under_replicated_strategy() {
        // The `Some("")` case under non-Sharded is rejected by
        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
        // fires before the empty-value gate), not
        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
        // the `Sharded` arm). Pin the partition so a future reorder of
        // the validate_placement match arms doesn't silently swap which
        // diagnostic the author sees — both are author errors, but
        // ShardKeyOnNonSharded names which strategy is the actual fix
        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
        // only says "pick a non-empty key".
        let mut s = three_member_spec();
        s.placement.shard_key = Some(String::new());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyOnNonSharded {
                    estrategia: PlacementStrategy::Replicated,
                    ref shard_key,
                } if shard_key.is_empty()
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn replicated_without_shard_key_validates() {
        // The complement of the rejection: `:placement :estrategia
        // Replicated` with `:shard-key None` is the canonical happy
        // path on every existing fixture. Pin the no-shard-key case so
        // the new gate doesn't accidentally fire on `None`.
        let mut s = three_member_spec();
        assert!(matches!(
            s.placement.estrategia,
            PlacementStrategy::Replicated
        ));
        s.placement.shard_key = None;
        s.validate().unwrap();
    }

    #[test]
    fn singlenode_without_shard_key_validates() {
        // Peer of the Replicated no-shard-key case on the SingleNode
        // arm — both non-Sharded strategies must validate cleanly when
        // the slot is omitted.
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::SingleNode;
        s.placement.shard_key = None;
        s.validate().unwrap();
    }

    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
        // Fixture builder for the `:placement :shard-key` shape gate
        // tests: a three-member Aplicacao on the `Sharded` strategy
        // with the supplied `:shard-key` slot. Co-locates the
        // arm-construction so every test below carries one line of
        // setup (the offending `:shard-key` value) and the assertion.
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::Sharded;
        s.placement.shard_key = Some(key.into());
        s
    }

    #[test]
    fn rejects_shard_key_with_embedded_space() {
        // The canonical paste-from-aligned-doc footgun:
        // `:shard-key "$tenant Id"` — the Akka-style entity-id
        // extractor reads the slot as a single-token reference, and an
        // embedded space breaks the token boundary at the runtime
        // hash-extractor pass with no diagnostic naming the offending
        // entry.
        let s = sharded_spec_with_key("$tenant Id");
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
                    if shard_key == "$tenant Id" && reason.contains("space")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_shard_key_with_leading_space() {
        // Leading-space arm of the embedded-whitespace footgun — the
        // paste-from-aligned-doc / paste-from-CSV-cell variant where
        // the leading column-padding leaked into the slot.
        let s = sharded_spec_with_key(" $tenantId");
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
                    if shard_key == " $tenantId"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_shard_key_with_trailing_newline() {
        // The canonical paste-from-shell-heredoc footgun — every
        // `<<EOF` heredoc terminator paste leaves a trailing newline
        // the YAML emitter then folds away inconsistently across
        // emitter implementations.
        let s = sharded_spec_with_key("$tenantId\n");
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_shard_key_with_embedded_tab() {
        // The paste-from-aligned-doc tab-stop variant — tabs land
        // alongside spaces in copy-paste from formatted columns.
        let s = sharded_spec_with_key("$tenant\tId");
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
                    if shard_key == "$tenant\tId" && reason.contains("tab")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_shard_key_with_control_character() {
        // The paste-from-binary / paste-from-screen-cleared-terminal
        // footgun — an embedded `\x01` (SOH) byte that some YAML
        // emitters silently strip and others escape as ``,
        // breaking round-trip across emitter implementations.
        let s = sharded_spec_with_key("$tenant\u{0001}Id");
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_shard_key_with_non_ascii() {
        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
        // footgun — non-ASCII bytes normalize differently between the
        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
        // YAML parser, the same entity ID can silently map to two
        // distinct shards on a re-render.
        let s = sharded_spec_with_key("$tenàntId");
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_shard_key_too_long() {
        // Length cap pin: 64 bytes — one byte over the
        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
        // here is a paste-from-doc multi-line blob landing in
        // `:shard-key` instead of a single-token extractor expression.
        let too_long = "a".repeat(64);
        let s = sharded_spec_with_key(&too_long);
        let err = s.validate().unwrap_err();
        let AplicacaoError::ShardKeyInvalid {
            ref shard_key,
            ref reason,
        } = err
        else {
            panic!("expected ShardKeyInvalid, got {err:?}");
        };
        assert_eq!(shard_key, &too_long);
        assert!(
            reason.contains("63") && reason.contains("64"),
            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
        );
    }

    #[test]
    fn shard_key_max_length_validates() {
        // Boundary pin: 63 bytes exactly — the
        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
        // dropping to 62) surfaces here as a regression, mirroring
        // `placement_cluster_max_length_validates` /
        // `placement_affinity_max_length_validates` on the peer
        // identifier-shaped slots.
        let s = sharded_spec_with_key(&"a".repeat(63));
        s.validate().unwrap();
    }

    #[test]
    fn accepts_canonical_shard_key_forms() {
        // The Akka-style entity-id extractor shapes a caixa author is
        // realistically going to write — pin every leg so a future
        // tightening that bans (e.g.) the `${...}` interpolation
        // variant or the `metadata.<field>` JSONPath form surfaces
        // here as a regression. The canonical forms span:
        //
        //   - bare property name (`tenantId`, `customerId`)
        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
        //   - JSONPath-style nested reference (`metadata.tenantId`,
        //     `$.user.id`)
        //   - interpolation-style template (`${tenant}`)
        //   - snake_case property name (`customer_id`)
        //   - kebab-case property name (`customer-id` — accepted
        //     because the slot is a printable-ASCII single-token
        //     reference, not a DNS-1123 label like
        //     `:placement :affinity` / `:clusters`)
        //   - single character (`a`, `$` — boundary)
        for form in [
            "tenantId",
            "customerId",
            "$tenantId",
            "metadata.tenantId",
            "$.user.id",
            "${tenant}",
            "customer_id",
            "customer-id",
            "a",
            "$",
        ] {
            let s = sharded_spec_with_key(form);
            s.validate().unwrap_or_else(|e| {
                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
            });
        }
    }

    #[test]
    fn shard_key_empty_takes_precedence_over_invalid() {
        // Order pin: the existing `ShardedKeyEmpty` diagnostic
        // (reserved for the `Sharded` `Some("")` arm) fires before the
        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
        // `:shard-key` keeps its narrower error message — the new gate
        // would also reject `""` defensively, but the empty-string arm
        // is the more self-locating diagnostic. Mirrors the
        // `placement_cluster_empty_takes_precedence_over_invalid` pin
        // on the peer identifier-shaped slot.
        let s = sharded_spec_with_key("");
        let err = s.validate().unwrap_err();
        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
    }

    #[test]
    fn shard_key_invalid_diagnostic_carries_offending_value() {
        // The diagnostic-shape pin: the error names the offending
        // `:shard-key` value verbatim so the author can grep their
        // caixa.lisp without re-running the build, and carries a
        // parser-shaped `reason:` naming the specific violation —
        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
        // on the peer identifier-shaped slot.
        let s = sharded_spec_with_key("$tenant Id");
        let err = s.validate().unwrap_err();
        let AplicacaoError::ShardKeyInvalid {
            ref shard_key,
            ref reason,
        } = err
        else {
            panic!("expected ShardKeyInvalid, got {err:?}");
        };
        assert_eq!(shard_key, "$tenant Id");
        assert!(
            !reason.is_empty(),
            "reason must name the specific violation, got empty string"
        );
    }

    #[test]
    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
        // `:shard-key` carried on non-Sharded strategies) fires before
        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
        // a `Replicated` strategy surfaces the more self-locating
        // strategy-mismatch diagnostic (naming the actual fix — drop
        // the slot, or switch to Sharded) rather than the shape
        // diagnostic. The strategy-mismatch arm is the more actionable
        // diagnostic: a malformed shard-key on Replicated is "you
        // shouldn't have a :shard-key here at all", not "your
        // :shard-key value is malformed".
        let mut s = three_member_spec();
        // Replicated is the default fixture strategy.
        s.placement.shard_key = Some("$tenant Id".into());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ShardKeyOnNonSharded {
                    estrategia: PlacementStrategy::Replicated,
                    ..
                }
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_empty_affinity_hint() {
        let mut s = three_member_spec();
        s.placement.affinity = Some("".into());
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::PlacementAffinityEmpty
        );
    }

    #[test]
    fn placement_without_affinity_validates() {
        // Omitting :affinity is fine — the placement engine falls back
        // to the default heuristic. Pin the no-hint case so the
        // affinity-empty rejection doesn't accidentally fire on `None`.
        let mut s = three_member_spec();
        s.placement.affinity = None;
        s.validate().unwrap();
    }

    #[test]
    fn rejects_placement_affinity_with_uppercase() {
        // The canonical "I copied the ADR's display name verbatim" typo
        // — placement hints land verbatim in K8s label-selector
        // territory, where the apiserver enforces the DNS-1123 label
        // rule (lowercase-only) on every identity-keyed admission axis.
        // Mirrors `rejects_placement_cluster_with_uppercase` on the
        // sibling slot.
        let mut s = three_member_spec();
        s.placement.affinity = Some("DataLocality".into());
        let err = s.validate().unwrap_err();
        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
            panic!("expected PlacementAffinityInvalid, got other variant");
        };
        assert_eq!(affinity, "DataLocality");
        assert!(
            reason.contains("uppercase"),
            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
        );
        assert!(
            reason.contains("\"datalocality\""),
            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
        );
    }

    #[test]
    fn rejects_placement_affinity_with_underscore() {
        // The canonical "I'm thinking of an env var / Python identifier"
        // leak — `_` is forbidden by every DNS-1123 label schema. Same
        // shape as `rejects_placement_cluster_with_underscore` on the
        // sibling slot.
        let mut s = three_member_spec();
        s.placement.affinity = Some("data_locality".into());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
                    if affinity == "data_locality" && reason.contains('_')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_affinity_with_dot() {
        // A `:placement :affinity` value is a single DNS-1123 *label*
        // (it lands as a K8s label value selector key), not a subdomain.
        // The "I want to namespace my hint with `.`" intent is expressed
        // via `-` (`data-locality-east`).
        let mut s = three_member_spec();
        s.placement.affinity = Some("data.locality".into());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
                    if affinity == "data.locality" && reason.contains('.')
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_affinity_with_unicode() {
        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
        // before it reaches K8s. The byte-by-byte ASCII validity check
        // rejects multi-byte UTF-8 sequences by the first byte that
        // fails `[a-z0-9-]`.
        let mut s = three_member_spec();
        s.placement.affinity = Some("data-localité".into());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
                    if affinity == "data-localité"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_affinity_with_leading_hyphen() {
        // DNS-1123 boundary rule: labels must start with an
        // alphanumeric. Pin separately from the trailing-hyphen arm so
        // a future relaxation that only checks one boundary surfaces
        // here as a regression (parallel to
        // `rejects_placement_cluster_with_leading_hyphen`).
        let mut s = three_member_spec();
        s.placement.affinity = Some("-data-locality".into());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
                    if affinity == "-data-locality" && reason.contains("start and end")
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_affinity_with_trailing_hyphen() {
        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
        // ends are covered against a future relaxation.
        let mut s = three_member_spec();
        s.placement.affinity = Some("data-locality-".into());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
                    if affinity == "data-locality-"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_affinity_with_whitespace() {
        // Whitespace is the canonical "I pasted from a sketch / doc"
        // footgun. The apiserver rejects every label-selector value
        // carrying whitespace.
        let mut s = three_member_spec();
        s.placement.affinity = Some("data locality".into());
        let err = s.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
                    if affinity == "data locality"
            ),
            "got {err:?}"
        );
    }

    #[test]
    fn rejects_placement_affinity_too_long() {
        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
        // pin. The diagnostic names both the cap (63) and the actual
        // length so the author can shorten in one edit. Mirrors
        // `rejects_placement_cluster_too_long`.
        let mut s = three_member_spec();
        let too_long = "a".repeat(64);
        s.placement.affinity = Some(too_long.clone());
        let err = s.validate().unwrap_err();
        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
            panic!("expected PlacementAffinityInvalid");
        };
        assert_eq!(affinity, too_long);
        assert!(
            reason.contains("63") && reason.contains("64"),
            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
        );
    }

    #[test]
    fn placement_affinity_max_length_validates() {
        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
        // future tightening (e.g. dropping to 62) surfaces here as a
        // regression, mirroring `placement_cluster_max_length_validates`.
        let mut s = three_member_spec();
        s.placement.affinity = Some("a".repeat(63));
        s.validate().unwrap();
    }

    #[test]
    fn accepts_canonical_placement_affinity_forms() {
        // The DNS-1123 label shapes a caixa author is realistically
        // going to write for placement hints: the M3 canonical examples
        // (`data-locality`, `low-latency`, `anti-affinity`), the
        // single-token form (`affinity`), the single-character boundary
        // (`a`), the digit-start (DNS-1123 allows this, unlike
        // DNS-1035), and a regional-suffixed form. Pin every leg so a
        // future tightening that bans (e.g.) digit-start identifiers
        // surfaces here.
        for form in [
            "data-locality",
            "low-latency",
            "anti-affinity",
            "affinity",
            "a",
            "3-tier",
            "locality-east",
        ] {
            let mut s = three_member_spec();
            s.placement.affinity = Some(form.into());
            s.validate().unwrap_or_else(|e| {
                panic!("canonical affinity form {form:?} must validate, got {e:?}")
            });
        }
    }

    #[test]
    fn placement_affinity_empty_takes_precedence_over_invalid() {
        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
        // (which doesn't try to parse) fires before the new
        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
        // `:affinity` keeps its narrower error message — the new gate
        // would also reject `""`, but the empty-string arm is the more
        // self-locating diagnostic. Mirrors the
        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
        let mut s = three_member_spec();
        s.placement.affinity = Some(String::new());
        let err = s.validate().unwrap_err();
        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
    }

    #[test]
    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
        // The diagnostic shape pin: every rejection carries the offending
        // `affinity:` verbatim plus a parser-shaped `reason:` so the
        // author can grep their caixa.lisp for `:affinity "<hint>"` and
        // fix it in one edit. Mirrors the
        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
        // pin on the sibling slot.
        let mut s = three_member_spec();
        s.placement.affinity = Some("Data_Locality".into());
        let err = s.validate().unwrap_err();
        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
            panic!("expected PlacementAffinityInvalid");
        };
        assert_eq!(affinity, "Data_Locality");
        assert!(
            !reason.is_empty(),
            "diagnostic reason must not be empty (got: {reason:?})"
        );
    }

    #[test]
    fn singlenode_with_takeover_candidates_validates() {
        // OTP distributed-application convention (MESH-COMPOSITION
        // §II.1): SingleNode runs on one cluster at a time but the
        // :clusters list enumerates the takeover candidates. Multiple
        // entries are not a contradiction — they are the failover pool.
        let mut s = three_member_spec();
        s.placement.estrategia = PlacementStrategy::SingleNode;
        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
        s.validate().unwrap();
    }

    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────

    #[test]
    fn mesh_policy_default_is_empty() {
        // The Default impl carries None on every axis — the typed
        // analog of an unset `:politicas (())` slot. Renderers that
        // overlay the policy onto a cluster artifact key off this
        // predicate to skip the slot entirely; pinning so a future
        // axis added to MeshPolicy can't silently break the contract
        // (a new field whose Default is non-None would flip is_empty
        // to false on every existing caixa, surfacing here).
        assert!(MeshPolicy::default().is_empty());
    }

    #[test]
    fn mesh_policy_with_only_timeout_is_not_empty() {
        let p = MeshPolicy {
            timeout: Some(Duration::from_secs(30)),
            ..Default::default()
        };
        assert!(!p.is_empty());
    }

    #[test]
    fn mesh_policy_with_only_retries_is_not_empty() {
        let p = MeshPolicy {
            retries: Some(3),
            ..Default::default()
        };
        assert!(!p.is_empty());
    }

    #[test]
    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
        let p = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 5,
                window: Duration::from_secs(60),
            }),
            ..Default::default()
        };
        assert!(!p.is_empty());
    }

    #[test]
    fn mesh_policy_with_only_mtls_required_is_not_empty() {
        // Even `mtls_required: Some(false)` (an explicit opt-out) is
        // not empty — the author *named* the axis, the renderer needs
        // to honor that vs. fall back to the cluster default.
        let p = MeshPolicy {
            mtls_required: Some(false),
            ..Default::default()
        };
        assert!(!p.is_empty());
    }

    #[test]
    fn mesh_policy_with_only_rate_limit_is_not_empty() {
        let p = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 100,
                window: Duration::from_secs(1),
            }),
            ..Default::default()
        };
        assert!(!p.is_empty());
    }

    #[test]
    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
        // The three-member happy-path fixture sets timeout + retries +
        // mtls_required — every populated axis must read non-empty.
        // Pin the round-trip so the M3.x per-:politicas emitter (the
        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
        // on is_empty() to decide whether to emit at all without
        // re-deriving the contract from inline field probes.
        assert!(!three_member_spec().politicas.is_empty());
    }

    // ── shared duration codec: cross-slot integer-magnitude gate ──
    //
    // The integer-magnitude discipline applied to
    // `supervisor::duration_codec::parse` lifts onto every typed slot
    // that routes through the shared codec — `MeshPolicy::timeout`
    // (`:politicas :timeout`) and `CircuitBreaker::window`
    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
    // These cross-slot tests pin that the gate fires at the serde
    // layer for both typed slots, not just for the supervisor side.

    #[test]
    fn policy_timeout_serde_rejects_fractional_seconds() {
        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
        // so the shared codec's integer-magnitude gate applies on
        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
        // deserialize with the canonical-form diagnostic naming the
        // offending `"1.5"` and the remediation `"1500ms"`.
        let payload = r#"{"timeout":"1.5s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a non-negative integer"),
            "expected integer-magnitude diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
        assert!(
            msg.contains("\"1500ms\""),
            "missing canonical-form remediation in {msg:?}"
        );
    }

    #[test]
    fn policy_timeout_serde_rejects_leading_plus_sign() {
        // Pin the leading-`+` arm cross-slot — the prior f64 parser
        // accepted `"+30s"` silently and round-tripped to `"30s"`.
        let payload = r#"{"timeout":"+30s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
    }

    #[test]
    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
        // `CircuitBreaker::window` uses `with =
        // "supervisor::duration_codec_required"` (the required-Duration
        // variant that delegates to the same shared parser). `"0.5m"`
        // parsed to 30s and round-tripped to `"30s"` on next emit —
        // DRIFT closed.
        let payload = format!(
            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
        );
        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a non-negative integer"),
            "expected integer-magnitude diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
        assert!(
            msg.contains("\"30s\""),
            "missing canonical-form remediation in {msg:?}"
        );
    }

    #[test]
    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
        // Pin the happy-path on the cross-slot side: every canonical
        // author shape `render` ever emits parses cleanly through the
        // shared codec on the `CircuitBreaker` slot. The
        // codec's accepted set (post-gate) is exactly its emitted set
        // for the integer-magnitude class.
        for window_lit in ["30s", "500ms", "2m", "1h"] {
            let payload = format!(
                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
            );
            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
            });
            assert_eq!(cb.max_failures, 5);
        }
    }

    // ── rate_limit_codec: integer-magnitude gate ──
    //
    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
    // / 737a676 / d53c922 trajectory landed on every typed-duration /
    // typed-byte-size codec in caixa-core lifts onto the fifth typed
    // codec — `rate_limit_codec` — through the digit-only magnitude
    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
    // These tests pin the gate at the serde layer for `:politicas
    // :rate-limit` (the only typed slot the codec backs), and at the
    // codec-internal `parse` layer for the canonical positive cases.

    #[test]
    fn rate_limit_serde_rejects_fractional_rate() {
        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
        // wording, which didn't name the canonical-form remediation or
        // the round-trip drift the next emit would produce. Now refused
        // at deserialize with the canonical-form diagnostic naming the
        // offending `"1.5"` magnitude and the round-trip drift wording.
        let payload = r#"{"rateLimit":"1.5/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a non-negative integer"),
            "expected integer-magnitude diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
        assert!(
            msg.contains("THEORY.md"),
            "missing render-determinism contract citation in {msg:?}"
        );
    }

    #[test]
    fn rate_limit_serde_rejects_leading_plus_sign() {
        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
        // permissive-`+` parse), so `"+100/s"` silently parsed to
        // `RateLimit { 100, 1s }` and round-tripped through `render` to
        // `"100/s"` — a *different* canonical string on the next emit,
        // breaking the THEORY.md Part V render-determinism contract
        // exactly the way the peer duration codecs' `"+30s"` case did.
        // This is the load-bearing class the digit-only gate closes
        // beyond what `u32::from_str`'s strictness covers on its own.
        let payload = r#"{"rateLimit":"+100/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a non-negative integer"),
            "expected integer-magnitude diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_rejects_leading_minus_sign() {
        // The signed-negative arm: `"-1/s"` lands on the
        // non-canonical-but-numeric branch via the `i64` fallback (the
        // `f64` parse also succeeds), surfacing the canonical-form
        // diagnostic. Replaces the prior value-laundered "not a u32"
        // wording with the unified diagnostic across signs.
        let payload = r#"{"rateLimit":"-1/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a non-negative integer"),
            "expected integer-magnitude diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_rejects_decimal_shaped_integer() {
        // `"100.0/s"` is integer-valued numerically but not in the
        // codec's accepted set — `render` emits `"100/s"`, so the
        // round-trip would drift. Lifted to the canonical-form
        // diagnostic peer with the duration codec's `"1.0s"` case
        // (1c55a2a).
        let payload = r#"{"rateLimit":"100.0/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a non-negative integer"),
            "expected integer-magnitude diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
        // Non-numeric, non-digit-only input lands on the existing
        // narrower `"not a u32"` arm (preserved for diagnostic-shape
        // stability on the parser-shape footgun case). Pin this so a
        // future relaxation of the numeric-fallback predicate doesn't
        // silently collapse garbage onto the canonical-form arm — same
        // partition the peer duration codecs draw between
        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
        let payload = r#"{"rateLimit":"abc/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not a u32"),
            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
        );
        assert!(
            !msg.contains("not a non-negative integer"),
            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
        );
    }

    #[test]
    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
        // u32's range. The digit-only gate passes; `u32::from_str`
        // fails on overflow. Surface that with the overflow-shaped
        // diagnostic naming the offending magnitude verbatim, peer
        // with `supervisor::duration_codec`'s overflow arm. Pinning
        // the wording so a future refactor doesn't silently collapse
        // overflow onto the canonical-form arm.
        let payload = r#"{"rateLimit":"4294967296/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("overflows u32"),
            "expected overflow diagnostic in {msg:?}"
        );
        assert!(
            msg.contains("\"4294967296\""),
            "missing offending magnitude in {msg:?}"
        );
    }

    #[test]
    fn rate_limit_serde_rejects_leading_zero_magnitude() {
        // `"0100/s"` is digit-only, so the existing
        // non-digit-only / sign / fractional arm doesn't catch it —
        // `u32::from_str("0100")` returns `Ok(100)`, so before this
        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
        // round-tripped through `render` to `"100/s"` — a *different*
        // canonical string on the next emit, breaking the THEORY.md
        // Part V render-determinism contract exactly the way the
        // peer `"+100/s"` case did before the leading-`+` arm landed.
        // This is the load-bearing class the leading-zero gate closes
        // beyond what the existing digit-only / sign / fractional
        // gates cover, and the peer arm to the leading-`+` test
        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
        // canonical-form-drift axis.
        let payload = r#"{"rateLimit":"0100/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("non-canonical leading zero"),
            "expected leading-zero diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
        assert!(
            msg.contains("THEORY.md"),
            "missing render-determinism contract citation in {msg:?}"
        );
    }

    #[test]
    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
        // `"00/s"` is the degenerate leading-zero case — every byte
        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
        // a *different* canonical string, same render-determinism
        // violation. The single-byte `"0/s"` itself is in the
        // accepted set (round-trips losslessly through `render`,
        // refused downstream by `PolicyRateLimitZero`); the
        // multi-byte `"00/s"` is not. Pins the boundary between the
        // accepted single-`0` and the rejected leading-zero class.
        let payload = r#"{"rateLimit":"00/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("non-canonical leading zero"),
            "expected leading-zero diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
        // Cross-window pin — the gate is window-agnostic; the
        // leading-zero class is a property of the magnitude, not the
        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
        // single-window coverage extended across the three canonical
        // windows the codec accepts.
        let payload = r#"{"rateLimit":"007/h"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("non-canonical leading zero"),
            "expected leading-zero diagnostic in {msg:?}"
        );
        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_rejects_leading_whitespace() {
        // `" 100/s"` — the canonical paste-from-aligned-doc /
        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
        // the top-level `s.trim()` silently ate the leading space and
        // parsed the value to `RateLimit { 100, 1s }`, which then
        // round-tripped through `render` to `"100/s"` (a *different*
        // canonical string on the next emit) — the exact
        // canonical-form-drift class the leading-`+` / leading-zero
        // arms already close, extended to the whitespace byte class.
        let payload = r#"{"rateLimit":" 100/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("contains whitespace byte"),
            "expected whitespace diagnostic in {msg:?}"
        );
        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
        assert!(
            msg.contains("THEORY.md"),
            "missing render-determinism contract citation in {msg:?}"
        );
    }

    #[test]
    fn rate_limit_serde_rejects_trailing_whitespace() {
        // `"100/s "` — the canonical shell-history / trailing-space
        // paste footgun. Before this gate the top-level `s.trim()`
        // silently ate the trailing space and parsed to
        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
        // next emit — same canonical-form drift as the leading-space
        // sibling, closed on the same whitespace-byte arm.
        let payload = r#"{"rateLimit":"100/s "}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("contains whitespace byte"),
            "expected whitespace diagnostic in {msg:?}"
        );
        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
        // `"100 / s"` — the canonical typographically-spaced author
        // shape (the same idiom every prose reference to a rate limit
        // renders as, mistakenly retained when the value is pasted
        // into a codec-shaped slot). Before this gate the per-part
        // `rate_str.trim()` / `unit.trim()` calls silently ate both
        // spaces on either side of `/` and parsed to
        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
        // codec's *internal* whitespace-tolerance vector, orthogonal
        // to the leading / trailing surface but the same canonical-
        // form-drift class. Pins the arm as strictly stronger than the
        // pre-existing top-level `s.trim()` behavior: it fires on
        // whitespace anywhere in the value, not just at the string
        // boundary.
        let payload = r#"{"rateLimit":"100 / s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("contains whitespace byte"),
            "expected whitespace diagnostic in {msg:?}"
        );
        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_rejects_tab_byte() {
        // `"\t100/s"` — the canonical paste-from-indented-doc /
        // paste-from-YAML-block-scalar footgun where a tab byte leads
        // the magnitude. Pins that the gate covers tab (`0x09`) as
        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
        // members and both would be silently swallowed by `s.trim()`
        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
        // space alone to the full ASCII-whitespace set (space `0x20`,
        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
        // the tab arm as a representative of the non-space members.
        let payload = r#"{"rateLimit":"\t100/s"}"#;
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("contains whitespace byte"),
            "expected whitespace diagnostic in {msg:?}"
        );
        assert!(
            msg.contains("0x09"),
            "missing offending tab byte in {msg:?}"
        );
    }

    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
    //
    // Successor to the ASCII-whitespace arm (1ad7755) on
    // `rate_limit_codec` — closes the strictly-complementary class the
    // byte-scan cannot see, through the lifted
    // [`crate::render::find_non_ascii_whitespace_char`] predicate.

    #[test]
    fn rate_limit_serde_rejects_leading_nbsp() {
        // NBSP prefix — paste-from-typography footgun. Byte-scan
        // misses, `str::trim` silently strips it, value drifts to
        // `"100/s"` on next serialize.
        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("non-ASCII Unicode whitespace character"),
            "expected non-ASCII whitespace diagnostic in {msg:?}"
        );
        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_rejects_internal_em_space() {
        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
        // paste-from-typography footgun on the `<integer>/<unit>`
        // shape.
        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("non-ASCII Unicode whitespace character"),
            "expected non-ASCII whitespace diagnostic in {msg:?}"
        );
        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
    }

    #[test]
    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
        // Positive-control pin: every ASCII-only canonical form the
        // renderer emits stays accepted through the new arm.
        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
            let p: MeshPolicy = serde_json::from_str(&payload)
                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
            assert!(p.rate_limit.is_some());
        }
    }

    #[test]
    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
        // The boundary case — `"0/s"` is the canonical form
        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
        // it at the parse layer; the downstream
        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
        // `rate == 0` at the typed-validate layer above. Pins the
        // partition: the leading-zero gate at the codec layer does
        // not poach the rate-zero semantic-validation arm at the
        // typed-validate layer above (a future stricter codec must
        // not reject `"0/s"` here, or it'd collapse the diagnostic
        // partitioning that lets `PolicyRateLimitZero` name the
        // offending typed slot).
        let payload = r#"{"rateLimit":"0/s"}"#;
        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
        });
        let rl = policy.rate_limit.expect("rate_limit must be Some");
        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
        assert_eq!(
            rl.window,
            Duration::from_secs(1),
            "single-`0` magnitude with `s` unit must parse to window=1s"
        );
    }

    #[test]
    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
        // The complementary boundary pin — every magnitude
        // `render` emits starts with `[1-9]` (or is the single byte
        // `"0"`), so the canonical-form predicate is `(len == 1) ||
        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
        // '1'` case explicitly so a future tightening of the gate
        // (e.g. an over-eager "no leading digit < 5" rule, or a
        // mistakenly anchored start-of-magnitude byte check) lands
        // here before the canonical-forms-iterating test would catch
        // it.
        let payload = r#"{"rateLimit":"100/s"}"#;
        let policy: MeshPolicy = serde_json::from_str(payload)
            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
        let rl = policy.rate_limit.expect("rate_limit must be Some");
        assert_eq!(
            rl.rate, 100,
            "canonical-100 magnitude must parse to rate=100"
        );
    }

    #[test]
    fn rate_limit_serde_accepts_integer_canonical_forms() {
        // Pin the happy-path: every canonical author shape `render`
        // ever emits parses cleanly through the codec post-gate. The
        // codec's accepted set (post-gate) is exactly its emitted set
        // for the integer-magnitude class — same property
        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
        // gates guarantee on the peer codecs. Iterating across rate
        // magnitudes (including `"0"`, which the codec accepts even
        // though `validate_politicas` rejects `rate == 0` at the typed
        // layer above) closes the codec contract at the parse layer
        // independently of the validate layer.
        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
            for unit_lit in ["s", "m", "h"] {
                let lit = format!("{rate_lit}/{unit_lit}");
                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
                });
                let rl = policy.rate_limit.expect("rate_limit must be Some");
                assert_eq!(
                    rl.rate,
                    rate_lit.parse::<u32>().unwrap(),
                    "rate mismatch for {lit:?}"
                );
            }
        }
    }

    #[test]
    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
        // The structural property the gate enforces: serialize ∘
        // deserialize is the identity on every canonical author shape.
        // Peer of `parse_byte_size`'s and `parse_duration`'s
        // `_round_trips_through_render_for_every_canonical_form` tests
        // on the rate-limit axis. Before the gate, `"+100/s"` violated
        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
        for rate in [1u32, 100, 5000, 1_000_000] {
            for (window, unit) in [
                (Duration::from_secs(1), "s"),
                (Duration::from_secs(60), "m"),
                (Duration::from_secs(3600), "h"),
            ] {
                let policy = MeshPolicy {
                    rate_limit: Some(RateLimit { rate, window }),
                    ..Default::default()
                };
                let json = serde_json::to_string(&policy).unwrap();
                let expected = format!("\"{rate}/{unit}\"");
                assert!(
                    json.contains(&expected),
                    "expected {expected:?} in {json:?}"
                );
                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
                assert_eq!(
                    back.rate_limit, policy.rate_limit,
                    "round-trip for {json:?}"
                );
            }
        }
    }

    // ── self-membership cross-slot gate ──────────────────────────────

    #[test]
    fn validate_no_self_membership_rejects_self_named_membro() {
        // An Aplicacao whose `:membros` lists its own `:nome` is a
        // one-node lacre-closure recursion — rejected, naming the parent.
        let membros = vec![
            membro("catalog", "^0.1"),
            membro("checkout", "^0.1"),
            membro("cart", "^0.1"),
        ];
        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
        assert!(
            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
            "got {err:?}"
        );
    }

    #[test]
    fn validate_no_self_membership_accepts_distinct_membros() {
        // Positive control: distinct member names (including a member
        // that is itself an Aplicacao — recursive composition is valid,
        // MESH-COMPOSITION §V) pass the gate.
        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
        validate_no_self_membership(&membros, "checkout").unwrap();
    }

    #[test]
    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
        // `NoMembros` arm (the more-fundamental "graph must have nodes"
        // gate), not by this cross-slot self-edge gate. Keeping the
        // self-membership predicate vacuously-ok on the empty input
        // matches its supervisor-axis peer
        // (`validate_no_self_supervision_empty_children_is_ok`) and
        // makes the gate composable from any future call site (an M4
        // CR materializer's per-membros validator) without re-checking
        // emptiness.
        validate_no_self_membership(&[], "checkout").unwrap();
    }

    #[test]
    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
        // Pinning the Display: the self-membership diagnostic must name
        // the offending caixa verbatim + the "lists itself" framing the
        // author can grep for, so the cluster-far failure surfaces at
        // build time with one-line remediation. Same diagnostic shape
        // as the supervisor-axis `ChildSupervisesSelf` peer.
        let membros = vec![membro("orquestra", "^0.1")];
        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("orquestra"),
            "diagnostic must name the offending caixa nome (got: {msg:?})"
        );
        assert!(
            msg.contains("lists itself"),
            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
        );
    }

    #[test]
    fn default_servico_port_constant_pins_canonical_8080_literal() {
        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
        // at the verbatim `8080` literal both consumers (the
        // `Entrada::port` serde default via [`default_port`] and the
        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
        // discipline (a085b26) on the per-renderer canonical-K8s-axis
        // string-constant axis: a future refactor that drifts the
        // constant out from under either consumer surfaces here ahead
        // of every per-renderer's first emission. The literal value
        // matches the well-known HTTP-alt port the `pleme-computeunit`
        // library chart already emits as its `trigger.service.port`
        // default — by construction the same value the substrate
        // assumes about every Servico's in-cluster L4 listener.
        assert_eq!(
            DEFAULT_SERVICO_PORT, 8080,
            "canonical Servico port literal must remain `8080` verbatim — \
             this is the value both the `Entrada::port` serde default and the \
             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
        );
    }

    #[test]
    fn default_port_helper_returns_canonical_servico_port_constant() {
        // The bridge-arm — pins that the [`default_port`] helper
        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
        // attribute hooks routes through the lifted
        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
        // literal. A future refactor that re-introduces the `8080`
        // literal at the helper's return site (silently re-opening
        // the drift footgun this lift closed) surfaces here ahead of
        // every author-side `(:entrada (:host … :para …))` slot
        // without an explicit `:port`. Peer with the
        // `default_namespace_re_export_points_at_caixa_core_canonical`
        // pin on the caixa-mesh-side re-export axis.
        assert_eq!(
            default_port(),
            DEFAULT_SERVICO_PORT,
            "the serde-default helper must route through the lifted constant"
        );
    }

    #[test]
    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
        // The end-to-end pin — an author-surface `(:entrada (:host …
        // :para …))` without an explicit `:port` slot deserializes to
        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
        // verbatim. Routes the canonical lifted constant through both
        // the serde-default machinery (the `#[serde(default =
        // "default_port")]` attribute) and the typed-value-shape
        // contract (the resulting [`Entrada::port`] value). A future
        // refactor that drifts either axis — replacing the serde
        // hook's helper, changing the typed slot's wire shape — would
        // surface here before any per-renderer's CNP / Gateway /
        // HTTPRoute emission consumed the drifted default.
        let entrada: Entrada =
            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
        assert_eq!(
            entrada.port, DEFAULT_SERVICO_PORT,
            "the serde default must materialize as the lifted canonical Servico port"
        );
    }

    #[test]
    fn servico_port_min_pins_canonical_accept_set_floor() {
        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
        // verbatim `1` literal every typed `:entrada :port` acceptance
        // gate keys off. Peer with the
        // [`default_servico_port_constant_pins_canonical_8080_literal`]
        // discipline on the canonical-Servico-port-constant axis: a
        // future refactor that drifts the accept-set floor out from
        // under the sole consumer at [`AplicacaoSpec::validate`]'s
        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
        // every per-`:entrada` `EntradaPortZero` diagnostic. The
        // literal value matches the IANA-registered TCP/UDP port
        // space floor (`1..=65535` — port `0` is the "any ephemeral"
        // sentinel, not a well-defined destination the substrate's
        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
        // axis can honor).
        assert_eq!(
            SERVICO_PORT_MIN, 1,
            "canonical Servico port accept-set floor must remain `1` verbatim — \
             this is the value the `AplicacaoSpec::validate` gate at \
             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
        );
    }

    #[test]
    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
        // The cross-const invariant pin — the substrate's canonical
        // default port must satisfy its own accept-set floor by
        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
        // override the operator pins through a future
        // `:placement :default-port` slot that lands out-of-range, a
        // per-edition Servico-port migration that lifted the floor
        // above the previous default without coordinating the pair —
        // would silently invalidate the serde-default emission at
        // every author-side `(:entrada (:host … :para …))` slot
        // without an explicit `:port`: the default port would fall
        // below the accept-set floor, the `AplicacaoSpec::validate`
        // gate would reject every default-carrying Aplicacao as
        // `EntradaPortZero`, and the substrate's typed
        // `(defcaixa … :kind Aplicacao)` surface would fail validate
        // on every Aplicacao whose author omitted `:entrada :port`
        // for the substrate's chosen default — a class of authoring-
        // surface footguns the compile-time pin structurally closes.
        // Peer with the
        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
        // (27f9b34) cross-const invariant pin discipline on the peer
        // canonical-Helm-per-values-block child-chart-enablement-toggle
        // axis pair.
        assert!(
            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
             every default-carrying `(:entrada (:host … :para …))` slot without an \
             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
        );
    }

    #[test]
    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
        // The gate-site pin — asserts the `AplicacaoSpec::validate`
        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
        // `EntradaPortZero` diagnostic on the below-floor input
        // `port: 0` (the only below-floor value the `u16` field can
        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
        // is the singleton `{0}`). A future refactor that drifts the
        // gate off the lifted const (silently re-introducing an
        // inline `if e.port == 0` byte-check) surfaces here — the
        // pin cannot distinguish `< 1` from `== 0` on the current
        // floor, but it *does* pin that the diagnostic fires on `0`
        // through whichever gate is wired, so any future accept-set
        // floor migration (a hypothetical unprivileged-only
        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
        // update this test alongside the const declaration —
        // structurally guaranteeing the gate + accept-set + pin
        // trio move together. Peer with the
        // [`rejects_zero_entrada_port`] behavioral pin on the same
        // per-`:entrada :port` axis — that pin asserts the pre-lift
        // behavioral contract (`port: 0` → `EntradaPortZero`); this
        // pin adds the structural link to the lifted floor const.
        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
        let mut s = three_member_spec();
        s.entrada.as_mut().unwrap().port = 0;
        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
    }

    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────

    #[test]
    fn membro_serde_keys_match_lifted_membro_key_consts() {
        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
        // name the exact camelCase JSON keys the
        // `#[serde(rename_all = "camelCase")]` attribute on
        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
        // that each canonical byte-sequence appears verbatim in the
        // JSON — a future accidental `rename_all = "snake_case"` /
        // `"kebab-case"` / verbatim-field-name flip at the derive
        // attribute (any of which would silently break every downstream
        // JSON consumer that reaches for one of the two consts via
        // `Value::get(...)`) surfaces here as a build-time test failure
        // at `aplicacao.rs`, not as an apply-time
        // `.get(<stale-canonical-const>)` returning `None` far from the
        // derive-attr drift's commit. Peer with the sibling
        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
        // same discipline the SupervisorSpec top-level lift established,
        // extended here to the M3 [`Membro`] per-`:membros` axis.
        let m = Membro {
            caixa: "catalog".into(),
            versao: "^0.1".into(),
        };
        let json = serde_json::to_string(&m).unwrap();
        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
            let quoted = format!("\"{key}\"");
            assert!(
                json.contains(&quoted),
                "serialized Membro must carry the lifted MEMBRO_KEY_* \
                 byte-sequence {quoted} verbatim in the JSON emission \
                 (got: {json})",
            );
        }
    }

    #[test]
    fn membro_key_consts_are_pairwise_distinct() {
        // Cross-axis drift-detection pin: a future collapse of the two
        // canonical [`Membro`] per-entry byte-strings onto the same
        // value (e.g. an accidental copy-paste flip of
        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
        // silently reroute every downstream probe on one axis onto the
        // sibling axis's overlay entry and pass every propagation-probe
        // test that expected only the stale axis's value. Peer of the
        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
        // (40cc4e5).
        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
        for (i, a) in all.iter().enumerate() {
            for b in all.iter().skip(i + 1) {
                assert_ne!(
                    a, b,
                    "MEMBRO_KEY_* consts must be pairwise-distinct \
                     canonical byte-sequences — got `{a}` == `{b}`",
                );
            }
        }
    }

    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
    //    URL-path fallback resolver every HTTPRoute-aware renderer
    //    reaching for a per-rule path-list resolution routes through.
    //    The four pin tests below fix the four-way accept-set the
    //    resolver must always honor: (:paths-non-empty-verbatim,
    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
    //    :paths-preserves-order-across-multiple-entries) — drift on any
    //    arm surfaces at caixa-core build time rather than at cluster-
    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
    //    sibling `:politicas` typed-primitive dispatch axis.

    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
        Entrada {
            host: "example.com".into(),
            para: "cart".into(),
            paths: paths.into_iter().map(String::from).collect(),
            port: DEFAULT_SERVICO_PORT,
        }
    }

    #[test]
    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
        // The typed `:entrada :paths` slot carries an author-declared
        // list — the resolver returns each entry verbatim, no
        // catch-all substitution. The canonical "author declared
        // paths, honor them verbatim" arm of the path-list dispatch.
        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
        assert_eq!(
            e.resolved_paths(),
            vec!["/api/cart", "/api/products"],
            "resolved_paths must return each `:entrada :paths` entry \
             verbatim when the typed slot is non-empty (got {:?})",
            e.resolved_paths(),
        );
    }

    #[test]
    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
        // Empty `:entrada :paths` slot — the resolver substitutes the
        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
        // catch-all fallback verbatim. Pins the empty-arm of the
        // resolver's four-way accept-set against a future silent
        // detour that returned an empty Vec (which would emit an
        // HTTPRoute with zero rules — silently dropping every
        // external `:entrada` flow at admission time), routed to a
        // different fallback shape, or dropped the catch-all
        // altogether.
        let e = entrada_with_paths(vec![]);
        assert_eq!(
            e.resolved_paths(),
            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
            "resolved_paths on empty `:entrada :paths` must fall back \
             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
             all — got {:?}",
            e.resolved_paths(),
        );
    }

    #[test]
    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
        // Single-entry `:entrada :paths` — the resolver returns the
        // single declared path verbatim, NOT the catch-all fallback
        // (author declared a path, honor it — the empty-arm and the
        // len-1 arm are semantically distinct axes of the resolver's
        // accept-set). Pins that the resolver treats "author declared
        // one path" as authored input, not as the empty case.
        let e = entrada_with_paths(vec!["/api/only"]);
        assert_eq!(
            e.resolved_paths(),
            vec!["/api/only"],
            "resolved_paths on single-entry `:entrada :paths` must \
             return the declared path verbatim, NOT the catch-all \
             fallback (got {:?})",
            e.resolved_paths(),
        );
    }

    #[test]
    fn resolved_paths_preserves_author_declared_order() {
        // The `:entrada :paths` list is author-ordered — the resolver
        // preserves the author's declaration order verbatim, since
        // per-rule dispatch order at the K8s Gateway API HTTPRoute
        // consumer is significant (first-match-wins under the
        // path-prefix matcher). Pins against a future silent
        // re-sort / dedup / normalize detour that reordered author
        // input.
        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
        assert_eq!(
            e.resolved_paths(),
            vec!["/z/last", "/a/first", "/m/mid"],
            "resolved_paths must preserve author-declared `:entrada \
             :paths` order verbatim — got {:?}",
            e.resolved_paths(),
        );
    }

    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
    //    slot `&[String]` slice accessor every per-`:entrada` consumer
    //    that must see the author's declaration verbatim (not the
    //    fallback-applied projection the sibling `resolved_paths`
    //    returns) routes through. The three pin tests below fix the
    //    accept-set the accessor must honor: (:non-empty-byte-equal,
    //    :empty-projects-empty-slice, :preserves-author-declared-order)
    //    — drift on any arm surfaces at caixa-core build time rather
    //    than at cluster-apply time. Peer discipline with the sibling
    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
    //    peer M3 mesh-slot `Vec<String>`-carry axis.

    #[test]
    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
        // Byte-equal pin: [`Entrada::paths`] must project the raw
        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
        // slice borrowed from the typed slot's own [`Vec<String>`]
        // storage — no re-ordering, no dedup, no per-entry normalization,
        // no fallback substitution (the fallback-applying projection is
        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
        // a future silent detour that re-normalized the list, dropped
        // duplicates the [`AplicacaoSpec::validate`]
        // `EntradaPathDuplicate` refusal already rejects at build time,
        // or (most severe) accidentally routed through the fallback-
        // applying sibling and returned the substrate catch-all when
        // the author declared an empty list — collapsing the raw-slot
        // and fallback-applied axes into one and breaking the
        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
        //
        // Peer of the sibling
        // [`Placement::clusters`]-shape byte-equal pin
        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
        let fixtures: Vec<Vec<String>> = vec![
            Vec::new(),
            vec!["/api/cart".into()],
            vec!["/api/cart".into(), "/api/products".into()],
            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
        ];
        for paths in fixtures {
            let e = Entrada {
                host: "example.com".into(),
                para: "cart".into(),
                paths: paths.clone(),
                port: DEFAULT_SERVICO_PORT,
            };
            assert_eq!(
                e.paths(),
                paths.as_slice(),
                "Entrada::paths must return :entrada :paths verbatim \
                 (got {:?}, expected {:?})",
                e.paths(),
                paths.as_slice(),
            );
            assert_eq!(
                e.paths(),
                e.paths.as_slice(),
                "Entrada::paths accessor and .paths.as_slice() field \
                 access must byte-equal — the accessor is the substrate-\
                 primitive typed dispatch every downstream per-`:entrada` \
                 raw-slot path-list consumer must route through",
            );
            assert_eq!(
                e.paths().len(),
                e.paths.len(),
                "Entrada::paths().len() must byte-equal self.paths.len() \
                 — a length drift would silently split the paired \
                 pre-flight cascade-head `.is_empty()` probe input in \
                 the sibling [`Entrada::resolved_paths`] resolver from \
                 the per-entry validate loop's traversal input in \
                 [`AplicacaoSpec::validate`]",
            );
        }
    }

    #[test]
    fn resolved_paths_reads_through_lifted_paths_accessor() {
        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
        // pre-flight `.paths().is_empty()` cascade-head probe (which
        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
        // catch-all fallback arm when the accessor projects the empty
        // slice) and the per-entry `.paths().iter().map(String::as_str)`
        // projection (which must reach every entry in the same order
        // the accessor projects, so the sibling
        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
        // per-entry projection stay in lockstep by construction) must
        // both key off the lifted accessor. Pins the two-site coherence
        // by exercising each production consumer end-to-end: (1) the
        // catch-all-fallback arm under the empty slice, (2) the
        // author-declared-verbatim arm under a two-entry cohort whose
        // per-entry projection must byte-equal the input's per-entry
        // author-declared paths in the author's declared order.
        //
        // Peer of the sibling M3
        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
        // `validate_placement_reads_through_lifted_clusters_accessor`
        // on the sibling `Placement::clusters` reader-site convergence.
        let empty = entrada_with_paths(vec![]);
        assert_eq!(
            empty.resolved_paths(),
            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
            "resolved_paths on empty :entrada :paths must trip the \
             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
             catch-all fallback — routing through the lifted paths() \
             accessor must not silently drop the fallback arm",
        );

        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
        assert_eq!(
            declared.resolved_paths(),
            vec!["/api/cart", "/api/products"],
            "resolved_paths on non-empty :entrada :paths must return each \
             entry verbatim in the author's declared order — routing \
             through the lifted paths() accessor must not silently \
             reorder or drop entries",
        );
        // Byte-equal pin against the raw-slot accessor to keep the
        // fallback-applying resolver's per-entry projection input in
        // lockstep with the raw-slot accessor's projection.
        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
        assert_eq!(
            declared.resolved_paths(),
            raw_projected,
            "resolved_paths non-empty projection must byte-equal the \
             lifted paths() accessor's per-entry String::as_str projection \
             — the two projections share the same input slice by \
             construction, so any drift here would surface a silent \
             re-ordering / dedup / normalization detour in the resolver",
        );
    }

    #[test]
    fn validate_reads_through_lifted_entrada_paths_accessor() {
        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
        // per-entry value-shape gate's `for p in e.paths()` traversal
        // (which must reach every entry in the same order the accessor
        // projects, so both the per-entry `EntradaPathEmpty` /
        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
        // the duplicate-detection HashSet insert that trips
        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
        // projection) must route through the lifted accessor. Pins the
        // coherence by exercising each production consumer end-to-end:
        // (1) the `EntradaPathEmpty` refusal fires on the second entry
        // of a two-entry cohort whose head is valid but tail is empty
        // (which requires the loop to reach the second entry through
        // the accessor), and (2) the `EntradaPathDuplicate` refusal
        // fires on the second entry of a two-entry cohort that shares
        // a path (which requires the loop to reach both entries — a
        // first-entry-only projection would silently pass since the
        // dedup HashSet has room for the first insert).
        //
        // Peer of the sibling
        // `validate_placement_reads_through_lifted_clusters_accessor`
        // on the sibling `Placement::clusters` reader-site convergence.
        let base = crate::AplicacaoSpec {
            membros: vec![crate::Membro {
                caixa: "cart".into(),
                versao: "^0.1".into(),
            }],
            contratos: Vec::new(),
            politicas: crate::MeshPolicy::default(),
            placement: crate::Placement {
                estrategia: crate::PlacementStrategy::SingleNode,
                clusters: vec!["rio".into()],
                shard_key: None,
                affinity: None,
            },
            entrada: Some(Entrada {
                host: "example.com".into(),
                para: "cart".into(),
                paths: vec!["/api/cart".into(), String::new()],
                port: DEFAULT_SERVICO_PORT,
            }),
        };
        assert_eq!(
            base.validate(),
            Err(crate::AplicacaoError::EntradaPathEmpty),
            "validate must trip EntradaPathEmpty on the second entry of \
             a two-entry cohort — routing through the lifted paths() \
             accessor must not silently short-circuit the loop at the \
             valid head entry",
        );

        let mut dup = base;
        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
        assert_eq!(
            dup.validate(),
            Err(crate::AplicacaoError::EntradaPathDuplicate {
                path: "/api/cart".into(),
            }),
            "validate must trip EntradaPathDuplicate on the second entry \
             of a two-entry cohort that shares a path — routing through \
             the lifted paths() accessor must not silently short-circuit \
             the dedup HashSet insert at the first entry",
        );
    }

    // ── Entrada::hostname / Entrada::hostnames — the substrate-
    //    canonical per-`:entrada` DNS-hostname resolver pair every
    //    Gateway-API-aware renderer reaching for a per-listener
    //    singular `hostname:` filter (Gateway) or a per-route plural
    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
    //    The three pin tests below fix the two-way accept-set the pair
    //    must always honor: (:singular-byte-equal-to-host,
    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
    //    on any arm surfaces at caixa-core build time rather than at
    //    cluster-apply time when the API server refuses the HTTPRoute
    //    for non-intersecting hostname filters. Peer discipline with
    //    the sibling `resolved_paths` accept-set pin block above on the
    //    per-`:entrada` path-list resolver axis.

    fn entrada_with_host(host: &str) -> Entrada {
        Entrada {
            host: host.into(),
            para: "cart".into(),
            paths: Vec::new(),
            port: DEFAULT_SERVICO_PORT,
        }
    }

    #[test]
    fn hostname_returns_entrada_host_byte_equal() {
        // The canonical singular-axis pin: [`Entrada::hostname`] must
        // return the `:entrada :host` field byte-for-byte, borrowed
        // from the typed slot's own [`String`] storage. Pins against a
        // future silent detour that re-normalized the host (an
        // accidental `.to_lowercase()` — validate_entrada_host already
        // enforces lowercase, so any re-normalization is redundant + a
        // drift surface between the validator and the accessor), a
        // trailing-`.` fully-qualified DNS shape substitution, or a
        // Punycode round-trip that lowered a Unicode host through IDNA.
        let e = entrada_with_host("checkout.quero.cloud");
        assert_eq!(
            e.hostname(),
            "checkout.quero.cloud",
            "Entrada::hostname must return :entrada :host verbatim \
             (got {:?})",
            e.hostname(),
        );
        assert_eq!(
            e.hostname(),
            e.host.as_str(),
            "Entrada::hostname must byte-equal the .host field access",
        );
    }

    #[test]
    fn hostnames_returns_singleton_of_hostname_accessor() {
        // The pair-invariant pin: [`Entrada::hostnames`] must always
        // return exactly `vec![hostname()]` — the singleton list whose
        // sole entry is the substrate's canonical per-`:entrada`
        // singular hostname. Pins the two-consumer coherence axis: the
        // Gateway listener's singular `hostname:` filter and the
        // HTTPRoute's plural `spec.hostnames[]` filter list must
        // agree, else the Gateway API v1.x conformance layer rejects
        // the HTTPRoute at attach time with
        // `Accepted:False/NoMatchingParent` (the parent Gateway's
        // listener hostname doesn't intersect the route's hostname
        // filter list) — a divergence whose apply-time symptom is far
        // from any single-site commit and never surfaces in the
        // emitted YAML. Pinning the pair-invariant here makes any
        // future accidental split (an accidental `.to_string() + "."`
        // trailing-`.` on the plural side that didn't land on the
        // singular side, an accidental prefix stripping on one axis,
        // an accidental wildcard prepend the SNI fan-out overlay
        // authors on the plural side without a paired singular
        // migration) trip at caixa-core build time.
        let e = entrada_with_host("checkout.quero.cloud");
        assert_eq!(
            e.hostnames(),
            vec![e.hostname()],
            "Entrada::hostnames must return `vec![hostname()]` under \
             the pair-invariant — got {:?} vs. singleton {:?}",
            e.hostnames(),
            vec![e.hostname()],
        );
    }

    #[test]
    fn hostnames_is_singleton_under_single_host_author_surface() {
        // The singleton-shape pin: under today's single-hostname-per-
        // `:entrada` author surface (the `:host` slot is a single
        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
        // must always return a list of length exactly one. Pins
        // against a future silent detour that returned an empty list
        // (which would emit an HTTPRoute with `spec.hostnames: []` —
        // matching every incoming Host header regardless of the
        // Aplicacao's declared ingress apex, silently over-matching
        // every foreign VirtualHost the parent Gateway also fronts) or
        // a duplicated entry (which the Gateway API v1.x parser
        // accepts as a `[]-length-2 list of equal hostnames]` but
        // whose semantics differ from the intended singleton). The
        // author-surface extension point ("a future `:entrada
        // :alt-hosts` list overlay" the docstring names) is the sole
        // future axis that flips this pin — that migration will re-
        // author this test to pin the new plural cardinality.
        let e = entrada_with_host("checkout.quero.cloud");
        assert_eq!(
            e.hostnames().len(),
            1,
            "Entrada::hostnames must be a singleton under today's \
             single-hostname-per-`:entrada` author surface — got \
             length {}: {:?}",
            e.hostnames().len(),
            e.hostnames(),
        );
    }

    // ── Entrada::destination — the substrate-canonical per-`:entrada`
    //    destination-Servico scalar accessor every Gateway-API
    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
    //    discriminator arg (HTTPRoute name composer) or a per-rule
    //    `backendRefs[0].name` axis routes through. The two pin tests
    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
    //    either arm surfaces at caixa-core build time rather than at
    //    cluster-apply time when an HTTPRoute's `metadata.name` and
    //    `backendRefs[]` silently disagree on which destination Servico
    //    the ingress fronts. Peer discipline with the sibling
    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
    //    blocks above on the per-`:entrada` path-list / DNS-hostname
    //    resolver axes.

    #[test]
    fn destination_returns_entrada_para_byte_equal() {
        // The canonical destination-scalar pin: [`Entrada::destination`]
        // must return the `:entrada :para` field byte-for-byte, borrowed
        // from the typed slot's own [`String`] storage. Pins against a
        // future silent detour that re-normalized the destination (an
        // accidental `.to_lowercase()` — the destination Servico is
        // already validated as a DNS-1123 label upstream, so any
        // re-normalization is redundant + a drift surface between the
        // validator and the accessor), a namespace-prefix rewrite (an
        // accidental `format!("{namespace}/{para}")` per-CR fully-
        // qualified rewrite that didn't land on the peer axis), or a
        // per-cluster suffix stamp the operator authors on one
        // consumer without the other.
        for para in ["cart", "checkout", "catalog", "orders-v2"] {
            let e = Entrada {
                host: "checkout.quero.cloud".into(),
                para: para.into(),
                paths: Vec::new(),
                port: DEFAULT_SERVICO_PORT,
            };
            assert_eq!(
                e.destination(),
                para,
                "Entrada::destination must return :entrada :para verbatim \
                 (got {:?}, expected {para:?})",
                e.destination(),
            );
            assert_eq!(
                e.destination(),
                e.para.as_str(),
                "Entrada::destination must byte-equal the .para field access",
            );
        }
    }

    #[test]
    fn destination_borrows_from_entrada_para_storage() {
        // The borrow-not-copy pin: [`Entrada::destination`] must
        // return a `&str` slice that borrows from the typed slot's
        // own [`String`] storage — same-address invariant with
        // `entrada.para.as_str()`. Pins against a future silent detour
        // that allocated a fresh `String` (`self.para.clone()` in the
        // body would type-check but silently drop the borrow, and
        // every downstream consumer that assumed the returned slice
        // outlives `&self` would break on a stale-reference use-after-
        // free). Peer with the sibling `hostname_returns_entrada_
        // host_byte_equal` on the singular-DNS-hostname axis.
        let e = entrada_with_host("checkout.quero.cloud");
        let dest = e.destination();
        let para_slice = e.para.as_str();
        assert_eq!(
            dest.as_ptr(),
            para_slice.as_ptr(),
            "Entrada::destination must borrow from the .para String's \
             backing storage — a fresh allocation here means the \
             accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            dest.len(),
            para_slice.len(),
            "Entrada::destination and .para.as_str() must byte-equal in \
             length as well as in address",
        );
    }

    #[test]
    fn port_returns_entrada_port_verbatim_across_permutations() {
        // The canonical L4-port-scalar pin: [`Entrada::port`] must
        // return the `:entrada :port` field verbatim as a `u16` across
        // every author-declared value in the validated accept-set
        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
        // silent detour that clamped the port (an accidental
        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
        // land on the peer [`AplicacaoSpec::port_for_destination`]
        // resolver), rewrote it through a per-cluster port-remap table
        // the operator authors on one consumer without the other, or
        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
        // serde-default value (which would silently collapse the
        // distinction between "author explicitly declared `:port 8080`"
        // and "author omitted the slot and inherited the default" the
        // future per-cluster override slot depends on). Peer with the
        // sibling `destination_returns_entrada_para_byte_equal` +
        // `hostname_returns_entrada_host_byte_equal` pins on the
        // per-`:entrada` `&str` scalar axes.
        for port in [
            SERVICO_PORT_MIN,
            DEFAULT_SERVICO_PORT,
            8443u16,
            9090u16,
            u16::MAX,
        ] {
            let e = Entrada {
                host: "checkout.quero.cloud".into(),
                para: "cart".into(),
                paths: Vec::new(),
                port,
            };
            assert_eq!(
                e.port(),
                port,
                "Entrada::port must return :entrada :port verbatim \
                 (got {}, expected {port})",
                e.port(),
            );
            assert_eq!(
                e.port(),
                e.port,
                "Entrada::port accessor and .port field access must \
                 byte-equal — the accessor is the substrate-primitive \
                 typed dispatch every downstream L4-port consumer must \
                 route through",
            );
        }
    }

    #[test]
    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
        // Two-consumer coherence pin: the
        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
        // (which reads through [`Entrada::port`] to compare against
        // [`SERVICO_PORT_MIN`]) and the
        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
        // through [`Entrada::port`] to emit the per-destination
        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
        // lifted accessor, so any future rebrand on the typed slot's
        // reader shape lands at exactly one place. Pins the two-site
        // coherence by exercising a below-floor port through validate
        // (which must reject) and a validated in-accept-set port through
        // port_for_destination (which must emit the same value the
        // accessor returns).
        let mut spec = three_member_spec();
        if let Some(e) = spec.entrada.as_mut() {
            e.port = 0;
        }
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::EntradaPortZero,
            "validate must reject `:entrada :port 0` through the lifted \
             Entrada::port accessor — port zero lies below \
             SERVICO_PORT_MIN and the validator routes through port() \
             to name the floor",
        );

        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
            let mut spec = three_member_spec();
            if let Some(e) = spec.entrada.as_mut() {
                e.port = port;
            }
            spec.validate().expect(
                "entrada with in-accept-set :port must validate — the \
                 structural-floor gate reads through Entrada::port",
            );
            let entrada_ref = spec.entrada.as_ref().expect(":entrada present");
            assert_eq!(
                spec.port_for_destination(entrada_ref.destination()),
                entrada_ref.port(),
                "port_for_destination(entrada.destination()) must equal \
                 entrada.port() — the two consumers of the per-:entrada \
                 L4-port axis (validator, per-destination resolver) both \
                 route through Entrada::port",
            );
        }
    }

    #[test]
    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
        // must return the `:contratos :de` field byte-for-byte, borrowed
        // from the typed slot's own [`String`] storage. Peer of the
        // sibling `destination_returns_entrada_para_byte_equal` pin on
        // the per-`:entrada` axis — same "the substrate-primitive
        // accessor must byte-equal the raw field access verbatim across
        // every author-declared value" discipline extended to the
        // per-`:contratos` caller arm. Pins against a future silent
        // detour that re-normalized the caller (an accidental
        // `.to_lowercase()` — every `:contratos :de` is validated as a
        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
        // re-normalization is redundant + a drift surface between the
        // validator and the accessor), a namespace-prefix rewrite (an
        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
        // rewrite that didn't land on the peer axis), or a per-cluster
        // suffix stamp the operator authors on one consumer without the
        // other.
        for de in ["cart", "checkout", "catalog", "orders-v2"] {
            let c = WitContract {
                de: de.into(),
                para: "downstream".into(),
                wit: "wasi:http/proxy".into(),
                endpoint: Some("/lookup".into()),
                subject: None,
                slot: None,
            };
            assert_eq!(
                c.source(),
                de,
                "WitContract::source must return :contratos :de verbatim \
                 (got {:?}, expected {de:?})",
                c.source(),
            );
            assert_eq!(
                c.source(),
                c.de.as_str(),
                "WitContract::source must byte-equal the .de field access",
            );
        }
    }

    #[test]
    fn wit_contract_source_borrows_from_de_storage() {
        // The borrow-not-copy pin: [`WitContract::source`] must return a
        // `&str` slice that borrows from the typed slot's own [`String`]
        // storage — same-address invariant with `c.de.as_str()`. Pins
        // against a future silent detour that allocated a fresh `String`
        // (`self.de.clone()` in the body would type-check but silently
        // drop the borrow, and every downstream consumer that assumed
        // the returned slice outlives `&self` would break on a stale-
        // reference use-after-free). Peer of the sibling
        // `destination_borrows_from_entrada_para_storage` on the
        // per-`:entrada` axis.
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        let src = c.source();
        let de_slice = c.de.as_str();
        assert_eq!(
            src.as_ptr(),
            de_slice.as_ptr(),
            "WitContract::source must borrow from the .de String's \
             backing storage — a fresh allocation here means the \
             accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            src.len(),
            de_slice.len(),
            "WitContract::source and .de.as_str() must byte-equal in \
             length as well as in address",
        );
    }

    #[test]
    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
        // must return the `:contratos :para` field byte-for-byte,
        // borrowed from the typed slot's own [`String`] storage. Peer of
        // the sibling `destination_returns_entrada_para_byte_equal` on
        // the per-`:entrada` axis — both accessors name "the destination-
        // Servico byte-string" concept on their respective mesh-slot
        // atoms (per-ingress apex vs. per-typed-edge callee) and both
        // must project the underlying `.para` field verbatim so every
        // downstream renderer that composes them with peer accessors
        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
        // per-edge L4 port emit site) reads the same byte-string the
        // author declared.
        for para in ["catalog", "payment", "orders", "inventory-v3"] {
            let c = WitContract {
                de: "cart".into(),
                para: para.into(),
                wit: "wasi:http/proxy".into(),
                endpoint: Some("/lookup".into()),
                subject: None,
                slot: None,
            };
            assert_eq!(
                c.destination(),
                para,
                "WitContract::destination must return :contratos :para \
                 verbatim (got {:?}, expected {para:?})",
                c.destination(),
            );
            assert_eq!(
                c.destination(),
                c.para.as_str(),
                "WitContract::destination must byte-equal the .para \
                 field access",
            );
        }
    }

    #[test]
    fn wit_contract_destination_borrows_from_para_storage() {
        // The borrow-not-copy pin: [`WitContract::destination`] must
        // return a `&str` slice that borrows from the typed slot's own
        // [`String`] storage — same-address invariant with
        // `c.para.as_str()`. Peer of the sibling
        // `destination_borrows_from_entrada_para_storage` on the
        // per-`:entrada` axis.
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        let dest = c.destination();
        let para_slice = c.para.as_str();
        assert_eq!(
            dest.as_ptr(),
            para_slice.as_ptr(),
            "WitContract::destination must borrow from the .para \
             String's backing storage — a fresh allocation here means \
             the accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            dest.len(),
            para_slice.len(),
            "WitContract::destination and .para.as_str() must byte-equal \
             in length as well as in address",
        );
    }

    #[test]
    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
        // The canonical per-`:contratos` WIT-world-reference scalar pin:
        // [`WitContract::world_ref`] must return the `:contratos :wit`
        // field byte-for-byte, borrowed from the typed slot's own
        // [`String`] storage. Sibling of the peer per-`:contratos`
        // [`WitContract::source`] / [`WitContract::destination`]
        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
        // "the substrate-primitive accessor must byte-equal the raw
        // field access verbatim across every author-declared value"
        // discipline extended to the per-`:contratos` WIT-world arm.
        // Pins against a future silent detour that re-canonicalized the
        // WIT world reference (an accidental `.to_lowercase()` pass that
        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
        // gate is already lowercase-prefixed so any re-normalization is
        // redundant + a drift surface between the validator and the
        // accessor), an M4-promotion-shape rewrite that formatted a
        // typed WIT-world enum through [`Display`] and silently drifted
        // the printer output from the source `caixa.lisp`, or a per-
        // cluster WIT-alias rewrite that didn't land on the peer field-
        // access sites. Five values sweep the shape-dispatch accept-set
        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
        // `wasi:keyvalue/`).
        for (wit, endpoint, subject, slot) in [
            ("wasi:http/proxy", Some("/lookup"), None, None),
            ("http:proxy", Some("/health"), None, None),
            ("nats:pub-sub", None, Some("orders.paid"), None),
            ("kafka:events", None, Some("checkout-events"), None),
            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
        ] {
            let c = WitContract {
                de: "cart".into(),
                para: "downstream".into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: subject.map(str::to_string),
                slot: slot.map(str::to_string),
            };
            assert_eq!(
                c.world_ref(),
                wit,
                "WitContract::world_ref must return :contratos :wit \
                 verbatim (got {:?}, expected {wit:?})",
                c.world_ref(),
            );
            assert_eq!(
                c.world_ref(),
                c.wit.as_str(),
                "WitContract::world_ref must byte-equal the .wit field \
                 access",
            );
        }
    }

    #[test]
    fn wit_contract_world_ref_borrows_from_wit_storage() {
        // The borrow-not-copy pin: [`WitContract::world_ref`] must
        // return a `&str` slice that borrows from the typed slot's own
        // [`String`] storage — same-address invariant with
        // `c.wit.as_str()`. Pins against a future silent detour that
        // allocated a fresh `String` (`self.wit.clone()` in the body
        // would type-check but silently drop the borrow, and every
        // downstream consumer that assumed the returned slice outlives
        // `&self` would break on a stale-reference use-after-free — the
        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
        // / [`is_pubsub`][WitContract::is_pubsub] /
        // [`is_store`][WitContract::is_store] methods route through —
        // each borrow from the WitContract's own storage and each would
        // silently misbehave if this accessor produced a detached copy).
        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
        // [`WitContract::destination`] and per-`:entrada`
        // [`Entrada::destination`] / [`Entrada::hostname`] and
        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        let world = c.world_ref();
        let wit_slice = c.wit.as_str();
        assert_eq!(
            world.as_ptr(),
            wit_slice.as_ptr(),
            "WitContract::world_ref must borrow from the .wit String's \
             backing storage — a fresh allocation here means the \
             accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently carry \
             a detached copy",
        );
        assert_eq!(
            world.len(),
            wit_slice.len(),
            "WitContract::world_ref and .wit.as_str() must byte-equal in \
             length as well as in address",
        );
    }

    #[test]
    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
        // Sibling-triple invariant pin composing all three per-`:contratos`
        // substrate-primitive typed dispatches — [`WitContract::source`]
        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
        // [`WitContract::world_ref`] — at the joint
        // `(source(), destination(), world_ref())` call shape every
        // renderer that fans on per-edge caller-callee-shape identity
        // keys off. The invariant, evaluated per-contract:
        //
        //   (c.source(), c.destination(), c.world_ref())
        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
        //
        // Closes the last unlifted per-`:contratos` scalar axis — every
        // downstream consumer that reads the triple now routes through
        // exactly three typed dispatches on the substrate primitive,
        // not two typed + one open-coded field access. A future refactor
        // that silently split any one accessor's projection (an
        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
        // canonicalization that didn't reach the peer `source`/
        // `destination` arms, an accidental `source()` per-cluster
        // caller-alias rewrite that didn't land on the `world_ref` peer)
        // surfaces at caixa-core build time. Peer of the sibling per-
        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
        // per-`:entrada` `(hostname(), destination())` (6db982c /
        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
        // axes, extended to the per-`:contratos` triple.
        for (de, para, wit, endpoint, subject, slot) in [
            (
                "cart",
                "catalog",
                "wasi:http/proxy",
                Some("/lookup"),
                None,
                None,
            ),
            (
                "checkout",
                "orders",
                "nats:pub-sub",
                None,
                Some("orders.paid"),
                None,
            ),
            (
                "cart",
                "kv",
                "wasi:keyvalue/store",
                None,
                None,
                Some("carts/{cart_id}"),
            ),
            (
                "orders-v2",
                "inventory-v3",
                "http:proxy",
                Some("/reserve"),
                None,
                None,
            ),
        ] {
            let c = WitContract {
                de: de.into(),
                para: para.into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: subject.map(str::to_string),
                slot: slot.map(str::to_string),
            };
            assert_eq!(
                (c.source(), c.destination(), c.world_ref()),
                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
                "(WitContract::source, ::destination, ::world_ref) must \
                 project (.de, .para, .wit) verbatim across every author-\
                 declared triple (got ({:?}, {:?}, {:?}), expected \
                 ({de:?}, {para:?}, {wit:?}))",
                c.source(),
                c.destination(),
                c.world_ref(),
            );
        }
    }

    #[test]
    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
        // The canonical per-`:contratos` owned-form caller-callee-pair
        // pin: [`WitContract::edge_pair`] must return the
        // `(source(), destination())` tuple in owned form byte-for-byte,
        // projected through the lifted [`WitContract::source`] /
        // [`WitContract::destination`] scalar accessors. Pins the
        // composite-projection invariant on the per-`:contratos`
        // mesh-slot atom — every author-declared `(de, para)` pair must
        // round-trip verbatim through the substrate primitive's typed
        // dispatch, so the nine [`AplicacaoError`] diagnostic-
        // construction sites the accessor now feeds
        // ([`AplicacaoError::EmptyWit`],
        // [`AplicacaoError::ContratoEndpointEmpty`],
        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
        // [`AplicacaoError::ContratoEndpointInvalid`],
        // [`AplicacaoError::ContratoSubjectEmpty`],
        // [`AplicacaoError::ContratoSubjectInvalid`],
        // [`AplicacaoError::ContratoSlotEmpty`],
        // [`AplicacaoError::ContratoSlotInvalid`],
        // [`AplicacaoError::ContratoDuplicate`]) all read the same
        // `(de, para)` label pair every author sees at the source
        // `caixa.lisp`. Pins against a future silent detour that swapped
        // the `.0` / `.1` arms (an accidental `(destination(),
        // source())` re-order in the body would silently invert every
        // downstream diagnostic's `de:` / `para:` label pair, silently
        // reversing the direction of every operator-facing typed error
        // arrow), a fresh-allocation shape drift (an accidental
        // `.to_string()` on one arm but not the other would leave the
        // owned/borrowed pair mismatched vs. the sibling `source()` /
        // `destination()` returns), or an M4 per-cluster caller/callee-
        // alias rewrite that landed on `source()` without reaching
        // `destination()` (or vice versa). Peer of the sibling per-
        // `:contratos` `(source, destination, world_ref)` triple
        // pin above on the mesh-slot-atom scalar-value axes, extended
        // to the owned-form pair-projection axis.
        for (de, para, wit, endpoint, subject, slot) in [
            (
                "cart",
                "catalog",
                "wasi:http/proxy",
                Some("/lookup"),
                None,
                None,
            ),
            (
                "checkout",
                "orders",
                "nats:pub-sub",
                None,
                Some("orders.paid"),
                None,
            ),
            (
                "cart",
                "kv",
                "wasi:keyvalue/store",
                None,
                None,
                Some("carts/{cart_id}"),
            ),
            (
                "orders-v2",
                "inventory-v3",
                "http:proxy",
                Some("/reserve"),
                None,
                None,
            ),
        ] {
            let c = WitContract {
                de: de.into(),
                para: para.into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: subject.map(str::to_string),
                slot: slot.map(str::to_string),
            };
            assert_eq!(
                c.edge_pair(),
                (de.to_string(), para.to_string()),
                "WitContract::edge_pair must return (:contratos :de, \
                 :contratos :para) as an owned tuple verbatim (got {:?}, \
                 expected ({de:?}, {para:?}))",
                c.edge_pair(),
            );
        }
    }

    #[test]
    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
        // The composition pin: [`WitContract::edge_pair`] must return
        // exactly `(source().to_string(), destination().to_string())` —
        // the owned form of the sibling accessor pair — so any future
        // refactor that silently re-authored the caller-arm / callee-arm
        // projection to bypass the lifted scalar accessors (an accidental
        // `(self.de.clone(), self.para.clone())` regression back to the
        // raw field-access shape, an M4-typed-caller-enum `Display`
        // re-canonicalization on `source()` that didn't reach
        // `edge_pair()`, a per-cluster alias rewrite the operator lands
        // on `destination()` without reaching this composite projection)
        // trips at caixa-core build time. Pins the "typed dispatch
        // composes with typed dispatch, not with raw field access"
        // discipline every downstream diagnostic-construction site now
        // routes through — a `de:` / `para:` label pair whose
        // projection silently drifted off the substrate primitive's
        // scalar accessors would silently split the diagnostic's self-
        // locating signal from the source `caixa.lisp` author's view.
        // Peer of the sibling per-`:politicas` `is_empty` /
        // `validate_politicas` accessor-routing-pin family on the M3
        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        assert_eq!(
            c.edge_pair(),
            (c.source().to_string(), c.destination().to_string()),
            "WitContract::edge_pair must compose exactly \
             (source().to_string(), destination().to_string()) — a \
             bypass of either sibling accessor here would silently \
             decouple the composite-projection axis from the \
             substrate-primitive scalar accessors every downstream \
             consumer routes through",
        );
    }

    #[test]
    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
     {
        // The canonical per-`:contratos` owned-form
        // caller-callee-world-ref-triple pin:
        // [`WitContract::edge_triple`] must return the
        // `(source(), destination(), world_ref())` tuple in owned form
        // byte-for-byte, projected through the lifted
        // [`WitContract::source`] / [`WitContract::destination`] /
        // [`WitContract::world_ref`] scalar accessors. Pins the
        // composite-projection invariant on the per-`:contratos`
        // mesh-slot atom — every author-declared `(de, para, wit)`
        // triple must round-trip verbatim through the substrate
        // primitive's typed dispatch, so the nine
        // [`AplicacaoError`] diagnostic-construction sites the
        // accessor now feeds (the [`WitTarget`]-dispatch's eight
        // wrong-target / missing-target / invalid-wit / capability-
        // with-payload arms in [`WitContract::target`], plus the
        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
        // read the same `(de, para, wit)` triple every author sees at
        // the source `caixa.lisp`. Pins against a future silent
        // detour that swapped any two arms (an accidental `(destination(),
        // source(), world_ref())` re-order in the body would silently
        // invert every downstream diagnostic's `de:` / `para:` label
        // pair, silently reversing the direction of every operator-
        // facing typed error arrow), a fresh-allocation shape drift
        // (an accidental `.to_string()` skipped on one arm would leave
        // the owned/borrowed triple mismatched vs. the sibling
        // `source()` / `destination()` / `world_ref()` returns), or an
        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
        // canonicalization pass that landed on one accessor without
        // reaching the peers. Peer of the sibling per-`:contratos`
        // caller-callee-pair
        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
        // pin on the mesh-slot-atom composite-projection axis,
        // extended to the triple-projection axis.
        for (de, para, wit, endpoint, subject, slot) in [
            (
                "cart",
                "catalog",
                "wasi:http/proxy",
                Some("/lookup"),
                None,
                None,
            ),
            (
                "checkout",
                "orders",
                "nats:pub-sub",
                None,
                Some("orders.paid"),
                None,
            ),
            (
                "cart",
                "kv",
                "wasi:keyvalue/store",
                None,
                None,
                Some("carts/{cart_id}"),
            ),
            (
                "orders-v2",
                "inventory-v3",
                "http:proxy",
                Some("/reserve"),
                None,
                None,
            ),
        ] {
            let c = WitContract {
                de: de.into(),
                para: para.into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: subject.map(str::to_string),
                slot: slot.map(str::to_string),
            };
            assert_eq!(
                c.edge_triple(),
                (de.to_string(), para.to_string(), wit.to_string()),
                "WitContract::edge_triple must return (:contratos :de, \
                 :contratos :para, :contratos :wit) as an owned triple \
                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
                c.edge_triple(),
            );
        }
    }

    #[test]
    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
        // The composition pin: [`WitContract::edge_triple`] must return
        // exactly `(source().to_string(), destination().to_string(),
        // world_ref().to_string())` — the owned form of the sibling
        // scalar-accessor triple — so any future refactor that silently
        // re-authored one arm's projection to bypass the lifted scalar
        // accessors (an accidental `(self.de.clone(), self.para.clone(),
        // self.wit.clone())` regression back to the raw field-access
        // shape the internal `edge` closure and the ContratoDuplicate
        // diagnostic both carried before this lift landed, an
        // M4-typed-caller-enum `Display` re-canonicalization on
        // `source()` that didn't reach `edge_triple()`, a per-cluster
        // alias rewrite the operator lands on `destination()` /
        // `world_ref()` without reaching this composite projection)
        // trips at caixa-core build time. Pins the "typed dispatch
        // composes with typed dispatch, not with raw field access"
        // discipline every downstream diagnostic-construction site now
        // routes through — a `de:` / `para:` / `wit:` triple whose
        // projection silently drifted off the substrate primitive's
        // scalar accessors would silently split the diagnostic's self-
        // locating signal from the source `caixa.lisp` author's view.
        // Peer of the sibling per-`:contratos` edge_pair composition-
        // pin above on the mesh-slot-atom composite-projection axis.
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        assert_eq!(
            c.edge_triple(),
            (
                c.source().to_string(),
                c.destination().to_string(),
                c.world_ref().to_string(),
            ),
            "WitContract::edge_triple must compose exactly \
             (source().to_string(), destination().to_string(), \
             world_ref().to_string()) — a bypass of any sibling accessor \
             here would silently decouple the composite-projection axis \
             from the substrate-primitive scalar accessors every \
             downstream consumer routes through",
        );
    }

    #[test]
    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
        // The canonical semantics-pin: [`WitContract::edge_triple`] must
        // project the full `(de, para, wit)` identity of a `:contratos`
        // edge — the sub-triple every triple-carrying
        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
        // missing-target, capability-with-payload, invalid-wit, and the
        // duplicate-gate). Rejects a drift in shape (an accidental
        // silent detour that returned a `(de, para)` pair or added an
        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
        // would trip here because the return type would no longer
        // pattern-match the eight `let (de, para, wit) = edge();`
        // destructures the [`WitContract::target`] dispatch feeds off
        // + the paired duplicate-gate `let (de, para, wit) =
        // c.edge_triple();` destructure in
        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
        // `:contratos` caller-callee-pair pin above extended to the
        // triple projection surface: closes the "one composite
        // accessor per typed diagnostic-construction sub-tuple"
        // discipline on the per-`:contratos` mesh-slot-atom axis.
        let c = WitContract {
            de: "checkout".into(),
            para: "orders".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("orders.paid".into()),
            slot: None,
        };
        let (de, para, wit) = c.edge_triple();
        assert_eq!(de, "checkout");
        assert_eq!(para, "orders");
        assert_eq!(wit, "nats:pub-sub");
    }

    #[test]
    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
     {
        // The composition pin: [`WitContract::identity`] must return
        // exactly `(source(), destination(), world_ref(), endpoint(),
        // subject(), slot())` — the borrowed form of the six-scalar-
        // accessor identity axis. Any future refactor that silently
        // re-authored one arm's projection to bypass a scalar accessor
        // (a `self.de.as_str()` regression back to raw field access on
        // any of the three required arms, a `self.endpoint.as_deref()`
        // regression on any of the three optional arms, an M4 per-
        // cluster caller/callee-alias rewrite the operator lands on
        // `source()` / `destination()` without reaching this composite
        // projection) trips at caixa-core build time. Sweeps four
        // permutations of the WIT-shape × payload lattice — HTTP with
        // endpoint, pub-sub with subject, store with slot, payload-less
        // capability — so every payload arm is exercised. Peer of the
        // sibling per-`:contratos`
        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
        // composition pin on the mesh-slot-atom composite-projection
        // axis; extends the discipline from the (de, para, wit) prefix
        // onto the full-identity axis carrying the three payload arms.
        for (de, para, wit, endpoint, subject, slot) in [
            (
                "cart",
                "catalog",
                "wasi:http/proxy",
                Some("/lookup"),
                None,
                None,
            ),
            (
                "checkout",
                "orders",
                "nats:pub-sub",
                None,
                Some("orders.paid"),
                None,
            ),
            (
                "cart",
                "kv",
                "wasi:keyvalue/store",
                None,
                None,
                Some("carts/{cart_id}"),
            ),
            ("audit", "sink", "wasi:logging", None, None, None),
        ] {
            let c = WitContract {
                de: de.into(),
                para: para.into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_owned),
                subject: subject.map(str::to_owned),
                slot: slot.map(str::to_owned),
            };
            assert_eq!(
                c.identity(),
                (
                    c.source(),
                    c.destination(),
                    c.world_ref(),
                    c.endpoint(),
                    c.subject(),
                    c.slot(),
                ),
                "WitContract::identity must compose exactly \
                 (source(), destination(), world_ref(), endpoint(), \
                 subject(), slot()) — a bypass of any sibling accessor \
                 here would silently decouple the identity-projection \
                 axis from the substrate-primitive scalar accessors \
                 every dedup-key consumer routes through",
            );
        }
    }

    #[test]
    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
        // The canonical semantics-pin: [`WitContract::identity`] must
        // project the six-axis (de, para, wit, endpoint, subject, slot)
        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
        // gate keys off — two `WitContract`s that agree on all six axes
        // are the same typed edge declared twice, the graph-edge
        // analogue of duplicate `:membros` / `:placement :clusters` /
        // `:entrada :paths` entries. Rejects a shape drift (an
        // accidental silent detour that returned a prefix tuple or
        // added an extra field) by pattern-matching the six-arm shape.
        // Peer of the sibling per-`:contratos`
        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
        // pin extended from the (de, para, wit) prefix onto the full
        // six-axis identity that the dedup key rides.
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/products/:id".into()),
            subject: None,
            slot: None,
        };
        let (de, para, wit, endpoint, subject, slot) = c.identity();
        assert_eq!(de, "cart");
        assert_eq!(para, "catalog");
        assert_eq!(wit, "wasi:http/proxy");
        assert_eq!(endpoint, Some("/products/:id"));
        assert_eq!(subject, None);
        assert_eq!(slot, None);

        // Two byte-identical contracts must produce equal identities —
        // the dedup key's foundational invariant.
        let c2 = c.clone();
        assert_eq!(c.identity(), c2.identity());

        // Any change on any of the six axes must break the identity —
        // sweeps by mutating one axis at a time.
        let mut mutated = c.clone();
        mutated.de = "search".into();
        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
        let mut mutated = c.clone();
        mutated.para = "warehouse".into();
        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
        let mut mutated = c.clone();
        mutated.wit = "http:legacy".into();
        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
        let mut mutated = c.clone();
        mutated.endpoint = Some("/search".into());
        assert_ne!(
            c.identity(),
            mutated.identity(),
            "endpoint axis must partition"
        );
        let mut mutated = c.clone();
        mutated.subject = Some("orders.paid".into());
        assert_ne!(
            c.identity(),
            mutated.identity(),
            "subject axis must partition"
        );
        let mut mutated = c;
        mutated.slot = Some("carts/{id}".into());
        assert_ne!(mutated.identity().5, None, "slot axis must partition");
    }

    #[test]
    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
        // The canonical per-`:contratos` structural-self-edge pin:
        // [`WitContract::is_self_loop`] must return `true` when the
        // `:de` and `:para` fields agree byte-for-byte, across every
        // WIT-shape variant the per-edge shape family carries. Pins
        // the shape-agnostic identity-space partition the
        // [`AplicacaoSpec::validate`] self-edge gate at
        // caixa-core/src/aplicacao.rs:5559 fires against — all four
        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
        // under the same one predicate. Four permutations sweep the
        // accept-set: HTTP with endpoint, pub-sub with subject, KV
        // store with slot, and payload-less capability.
        for (nome, wit, endpoint, subject, slot) in [
            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
            (
                "kv",
                "wasi:keyvalue/store",
                None,
                None,
                Some("carts/{cart_id}"),
            ),
            ("audit", "wasi:logging", None, None, None),
        ] {
            let c = WitContract {
                de: nome.into(),
                para: nome.into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: subject.map(str::to_string),
                slot: slot.map(str::to_string),
            };
            assert!(
                c.is_self_loop(),
                "WitContract::is_self_loop must return true when \
                 :contratos :de == :contratos :para (got false on \
                 {nome:?} under {wit:?})",
            );
        }
    }

    #[test]
    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
        // The complement pin: [`WitContract::is_self_loop`] must return
        // `false` on every well-shaped inter-Servico contract (the
        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
        // names — "Servico A calls Servico B" between two distinct
        // graph nodes). Pins against a future silent detour that
        // inverted the predicate (an accidental `!= ` swap for `==`
        // would silently reject every legitimate inter-Servico edge
        // and admit every self-edge — the exact inversion of the
        // author-intended shape). Four permutations sweep the same
        // WIT-shape accept-set the sibling positive-arm test carries.
        for (de, para, wit, endpoint, subject, slot) in [
            (
                "cart",
                "catalog",
                "wasi:http/proxy",
                Some("/lookup"),
                None,
                None,
            ),
            (
                "checkout",
                "orders",
                "nats:pub-sub",
                None,
                Some("orders.paid"),
                None,
            ),
            (
                "cart",
                "kv",
                "wasi:keyvalue/store",
                None,
                None,
                Some("carts/{cart_id}"),
            ),
            ("audit", "sink", "wasi:logging", None, None, None),
        ] {
            let c = WitContract {
                de: de.into(),
                para: para.into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: subject.map(str::to_string),
                slot: slot.map(str::to_string),
            };
            assert!(
                !c.is_self_loop(),
                "WitContract::is_self_loop must return false when \
                 :contratos :de differs from :contratos :para (got true \
                 on {de:?} → {para:?} under {wit:?})",
            );
        }
    }

    #[test]
    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
        // The composition pin: [`WitContract::is_self_loop`] must
        // resolve to exactly `self.source() == self.destination()` —
        // the equality probe of the sibling scalar-accessor pair — so
        // any future refactor that silently re-authored the predicate
        // to bypass the lifted scalar accessors (an accidental
        // `self.de == self.para` regression back to the raw field-
        // access shape, an M4-typed-caller-enum identity-comparison
        // rule that landed on `source()` without reaching
        // `destination()`, a per-cluster alias rewrite the operator
        // pins on `destination()` without reaching this predicate)
        // trips at caixa-core build time. Pins the "typed dispatch
        // composes with typed dispatch, not with raw field access"
        // discipline the sibling [`WitContract::edge_pair`] /
        // [`WitContract::edge_triple`] composite-projection accessors
        // already carry, extended onto the per-edge endpoint-equality
        // predicate axis. Positive and complement arms both fire.
        let self_edge = WitContract {
            de: "cart".into(),
            para: "cart".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        assert_eq!(
            self_edge.is_self_loop(),
            self_edge.source() == self_edge.destination(),
            "WitContract::is_self_loop must compose exactly \
             `source() == destination()` — a bypass of either sibling \
             accessor here would silently decouple the endpoint-\
             equality predicate from the substrate-primitive scalar \
             accessors every downstream consumer routes through",
        );
        let inter_edge = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        assert_eq!(
            inter_edge.is_self_loop(),
            inter_edge.source() == inter_edge.destination(),
            "WitContract::is_self_loop must compose exactly \
             `source() == destination()` on the complement arm too",
        );
    }

    #[test]
    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
        // pin: [`WitContract::endpoint`] must return the `:contratos
        // :endpoint` field byte-for-byte, borrowed from the typed slot's
        // own `Option<String>` storage. Peer of the sibling
        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
        // mesh-slot `Option<String>` optional-scalar axes — same "the
        // substrate-primitive accessor must byte-equal the raw field
        // access verbatim across every author-declared value" discipline
        // extended to the per-`:contratos` HTTP-payload-carrier arm.
        // Pins against a future silent detour that re-canonicalized the
        // endpoint (an accidental percent-encoding pass that didn't
        // reach the peer field-access site at the dedup key, a per-CR
        // fully-qualified prefix rewrite the operator authors on one
        // consumer without the other, or an M4 typed-path-template
        // `Display` re-canonicalization that silently drifted the
        // printer output from the source `caixa.lisp`). Four values
        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
        // gate upstream admits (short root-path, dashed, param-shaped,
        // deep-hierarchy).
        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
            let c = WitContract {
                de: "cart".into(),
                para: "catalog".into(),
                wit: "wasi:http/proxy".into(),
                endpoint: Some(endpoint.into()),
                subject: None,
                slot: None,
            };
            assert_eq!(
                c.endpoint(),
                Some(endpoint),
                "WitContract::endpoint must return :contratos :endpoint \
                 verbatim (got {:?}, expected Some({endpoint:?}))",
                c.endpoint(),
            );
            assert_eq!(
                c.endpoint(),
                c.endpoint.as_deref(),
                "WitContract::endpoint must byte-equal the .endpoint \
                 field's `.as_deref()` projection",
            );
        }
    }

    #[test]
    fn wit_contract_endpoint_none_when_field_is_none() {
        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
        // payload-carrier accessor pin: when the typed slot is absent —
        // the canonical shape under a non-HTTP `:wit` world per the
        // [`WitContract::target`]-enforced shape ↔ target partition
        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
        // carries `:slot`, [`WitTarget::Capability`] carries none) —
        // [`WitContract::endpoint`] must return `None`. Pins against a
        // future silent detour that projected the absent slot to a
        // `Some("")` empty-string default (the canonical `Option<String>`
        // → `String` collapse footgun the sibling M2
        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
        // emptiness predicates already guard on the peer M2 typed-slot
        // surfaces), a `Some("None")` stringified-None round-trip, or a
        // `Some` arm whose contents were derived from a sibling slot (an
        // accidental fallback to the `:subject` / `:slot` payload that
        // read the pub-sub / store payload into the endpoint axis).
        // Three contracts sweep the accept-set every non-HTTP `:wit`
        // world lands on — pub-sub NATS, key/value, and payload-less
        // capability.
        for (wit, subject, slot) in [
            ("nats:pub-sub", Some("orders.paid"), None),
            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
            ("wasi:cli/environment", None, None),
        ] {
            let c = WitContract {
                de: "cart".into(),
                para: "downstream".into(),
                wit: wit.into(),
                endpoint: None,
                subject: subject.map(str::to_string),
                slot: slot.map(str::to_string),
            };
            assert!(
                c.endpoint().is_none(),
                "WitContract::endpoint must return None when the typed \
                 slot is absent under :wit {wit:?} (got {:?})",
                c.endpoint(),
            );
            assert_eq!(
                c.endpoint(),
                c.endpoint.as_deref(),
                "WitContract::endpoint must byte-equal the .endpoint \
                 field's `.as_deref()` projection in the absent arm",
            );
        }
    }

    #[test]
    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
        // an `Option<&str>` whose `Some` arm borrows from the typed
        // slot's own [`String`] storage — same-address invariant with
        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
        // detour that allocated a fresh `String`
        // (`self.endpoint.clone().map(...)` in the body would type-check
        // but silently drop the borrow, and every downstream consumer
        // that assumed the returned slice outlives `&self` would break
        // on a stale-reference use-after-free — the [`WitContract::target`]
        // Http-arm payload extraction rebinds the returned `Option<&str>`
        // through `.ok_or_else(...)` and threads the `&str` payload into
        // [`WitTarget::Http { endpoint: &'a str }`], the
        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
        // [`ContratoIdentity`] dedup key threads the returned
        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
        // from the WitContract's own storage and each would silently
        // misbehave if this accessor produced a detached copy). Peer of
        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
        // shaped optional-scalar axes — first extension of the
        // `Option<&str>` borrow-not-copy discipline onto the
        // per-`:contratos` HTTP-shaped payload-carrier axis.
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        let ep = c.endpoint().expect("Some arm");
        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
        assert_eq!(
            ep.as_ptr(),
            storage_slice.as_ptr(),
            "WitContract::endpoint must borrow from the .endpoint \
             String's backing storage — a fresh allocation here means \
             the accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            ep.len(),
            storage_slice.len(),
            "WitContract::endpoint and .endpoint.as_deref() must byte-\
             equal in length as well as in address",
        );
    }

    #[test]
    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
        // pin: [`WitContract::subject`] must return the `:contratos
        // :subject` field byte-for-byte, borrowed from the typed slot's
        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
        // optional-scalar axis — same "the substrate-primitive accessor
        // must byte-equal the raw field access verbatim across every
        // author-declared value" discipline extended to the pub-sub arm.
        // Pins against a future silent detour that re-canonicalized the
        // subject (an accidental `.to_lowercase()` normalization that
        // didn't reach the peer field-access site at the dedup key, a
        // per-CR fully-qualified prefix rewrite the operator authors on
        // one consumer without the other, or an M4 typed-subject-template
        // `Display` re-canonicalization that silently drifted the printer
        // output from the source `caixa.lisp`). Four values sweep the
        // NATS accept-set every pub-sub author-declared subject lands on
        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
            let c = WitContract {
                de: "cart".into(),
                para: "notifier".into(),
                wit: "nats:pub-sub".into(),
                endpoint: None,
                subject: Some(subject.into()),
                slot: None,
            };
            assert_eq!(
                c.subject(),
                Some(subject),
                "WitContract::subject must return :contratos :subject \
                 verbatim (got {:?}, expected Some({subject:?}))",
                c.subject(),
            );
            assert_eq!(
                c.subject(),
                c.subject.as_deref(),
                "WitContract::subject must byte-equal the .subject \
                 field's `.as_deref()` projection",
            );
        }
    }

    #[test]
    fn wit_contract_subject_none_when_field_is_none() {
        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
        // shaped payload-carrier accessor pin: when the typed slot is
        // absent — the canonical shape under a non-pub-sub `:wit` world
        // per the [`WitContract::target`]-enforced shape ↔ target
        // partition ([`WitTarget::Http`] carries `:endpoint`,
        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
        // carries none) — [`WitContract::subject`] must return `None`.
        // Pins against a future silent detour that projected the absent
        // slot to a `Some("")` empty-string default (the canonical
        // `Option<String>` → `String` collapse footgun the sibling M2
        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
        // emptiness predicates already guard on the peer M2 typed-slot
        // surfaces), a `Some("None")` stringified-None round-trip, or a
        // `Some` arm whose contents were derived from a sibling slot (an
        // accidental fallback to the `:endpoint` / `:slot` payload that
        // read the HTTP / store payload into the subject axis). Three
        // contracts sweep the accept-set every non-pub-sub `:wit` world
        // lands on — HTTP proxy, key/value store, and payload-less
        // capability.
        for (wit, endpoint, slot) in [
            ("wasi:http/proxy", Some("/lookup"), None),
            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
            ("wasi:cli/environment", None, None),
        ] {
            let c = WitContract {
                de: "cart".into(),
                para: "downstream".into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: None,
                slot: slot.map(str::to_string),
            };
            assert!(
                c.subject().is_none(),
                "WitContract::subject must return None when the typed \
                 slot is absent under :wit {wit:?} (got {:?})",
                c.subject(),
            );
            assert_eq!(
                c.subject(),
                c.subject.as_deref(),
                "WitContract::subject must byte-equal the .subject \
                 field's `.as_deref()` projection in the absent arm",
            );
        }
    }

    #[test]
    fn wit_contract_subject_borrows_from_subject_storage() {
        // The borrow-not-copy pin: [`WitContract::subject`] must return
        // an `Option<&str>` whose `Some` arm borrows from the typed
        // slot's own [`String`] storage — same-address invariant with
        // `c.subject.as_deref().unwrap()`. Pins against a future silent
        // detour that allocated a fresh `String`
        // (`self.subject.clone().map(...)` in the body would type-check
        // but silently drop the borrow, and every downstream consumer
        // that assumed the returned slice outlives `&self` would break
        // on a stale-reference use-after-free — the [`WitContract::target`]
        // PubSub-arm payload extraction rebinds the returned
        // `Option<&str>` through `.ok_or_else(...)` and threads the
        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
        // [`ContratoIdentity`] dedup key threads the returned
        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
        // from the WitContract's own storage and each would silently
        // misbehave if this accessor produced a detached copy). Peer of
        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
        // shaped optional-scalar axis — second extension of the
        // `Option<&str>` borrow-not-copy discipline onto the
        // per-`:contratos` payload-carrier family, this time on the
        // pub-sub arm.
        let c = WitContract {
            de: "cart".into(),
            para: "notifier".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("orders.paid".into()),
            slot: None,
        };
        let sub = c.subject().expect("Some arm");
        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
        assert_eq!(
            sub.as_ptr(),
            storage_slice.as_ptr(),
            "WitContract::subject must borrow from the .subject \
             String's backing storage — a fresh allocation here means \
             the accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            sub.len(),
            storage_slice.len(),
            "WitContract::subject and .subject.as_deref() must byte-\
             equal in length as well as in address",
        );
    }

    #[test]
    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
        // The canonical per-`:contratos` key/value-store-shaped
        // `:slot`-scalar pin: [`WitContract::slot`] must return the
        // `:contratos :slot` field byte-for-byte, borrowed from the
        // typed slot's own `Option<String>` storage. Peer of the
        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
        // [`WitContract::subject`] (90de675) accessor pins on the M3
        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
        // optional-scalar axis — same "the substrate-primitive
        // accessor must byte-equal the raw field access verbatim
        // across every author-declared value" discipline extended to
        // the store arm. Pins against a future silent detour that
        // re-canonicalized the slot template (an accidental
        // `.to_lowercase()` bucket-prefix normalization that didn't
        // reach the peer field-access site at the dedup key, a per-CR
        // fully-qualified prefix rewrite the operator authors on one
        // consumer without the other, or an M4 typed-key-template
        // `Display` re-canonicalization that silently drifted the
        // printer output from the source `caixa.lisp`). Four values
        // sweep the wasi:keyvalue accept-set every store-shaped
        // author-declared slot lands on (flat bucket, single-param
        // template, multi-param template, nested-hierarchy template).
        for slot in [
            "sessions",
            "carts/{cart_id}",
            "orders/{tenant}/{order_id}",
            "cache/tenant-a/orders/{id}",
        ] {
            let c = WitContract {
                de: "cart".into(),
                para: "kv".into(),
                wit: "wasi:keyvalue/store".into(),
                endpoint: None,
                subject: None,
                slot: Some(slot.into()),
            };
            assert_eq!(
                c.slot(),
                Some(slot),
                "WitContract::slot must return :contratos :slot \
                 verbatim (got {:?}, expected Some({slot:?}))",
                c.slot(),
            );
            assert_eq!(
                c.slot(),
                c.slot.as_deref(),
                "WitContract::slot must byte-equal the .slot field's \
                 `.as_deref()` projection",
            );
        }
    }

    #[test]
    fn wit_contract_slot_none_when_field_is_none() {
        // The absent-`:slot` arm of the per-`:contratos` store-shaped
        // payload-carrier accessor pin: when the typed slot is absent —
        // the canonical shape under a non-store `:wit` world per the
        // [`WitContract::target`]-enforced shape ↔ target partition
        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
        // carries `:subject`, [`WitTarget::Capability`] carries none) —
        // [`WitContract::slot`] must return `None`. Pins against a
        // future silent detour that projected the absent slot to a
        // `Some("")` empty-string default (the canonical
        // `Option<String>` → `String` collapse footgun the sibling M2
        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
        // emptiness predicates already guard on the peer M2 typed-slot
        // surfaces), a `Some("None")` stringified-None round-trip, or
        // a `Some` arm whose contents were derived from a sibling
        // slot (an accidental fallback to the `:endpoint` / `:subject`
        // payload that read the HTTP / pub-sub payload into the store
        // axis). Three contracts sweep the accept-set every non-store
        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
        // payload-less capability.
        for (wit, endpoint, subject) in [
            ("wasi:http/proxy", Some("/lookup"), None),
            ("nats:pub-sub", None, Some("orders.paid")),
            ("wasi:cli/environment", None, None),
        ] {
            let c = WitContract {
                de: "cart".into(),
                para: "downstream".into(),
                wit: wit.into(),
                endpoint: endpoint.map(str::to_string),
                subject: subject.map(str::to_string),
                slot: None,
            };
            assert!(
                c.slot().is_none(),
                "WitContract::slot must return None when the typed \
                 slot is absent under :wit {wit:?} (got {:?})",
                c.slot(),
            );
            assert_eq!(
                c.slot(),
                c.slot.as_deref(),
                "WitContract::slot must byte-equal the .slot field's \
                 `.as_deref()` projection in the absent arm",
            );
        }
    }

    #[test]
    fn wit_contract_slot_borrows_from_slot_storage() {
        // The borrow-not-copy pin: [`WitContract::slot`] must return
        // an `Option<&str>` whose `Some` arm borrows from the typed
        // slot's own [`String`] storage — same-address invariant with
        // `c.slot.as_deref().unwrap()`. Pins against a future silent
        // detour that allocated a fresh `String`
        // (`self.slot.clone().map(...)` in the body would type-check
        // but silently drop the borrow, and every downstream consumer
        // that assumed the returned slice outlives `&self` would
        // break on a stale-reference use-after-free — the
        // [`WitContract::target`] Store-arm payload extraction rebinds
        // the returned `Option<&str>` through `.ok_or_else(...)` and
        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
        // [`ContratoIdentity`] dedup key threads the returned
        // `Option<&str>` into the six-tuple's store arm — each borrow
        // from the WitContract's own storage and each would silently
        // misbehave if this accessor produced a detached copy). Peer
        // of the sibling per-`:contratos` [`WitContract::endpoint`]
        // (7020470) / [`WitContract::subject`] (90de675)
        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
        // shaped optional-scalar axis — third and final extension of
        // the `Option<&str>` borrow-not-copy discipline onto the
        // per-`:contratos` payload-carrier family, this time on the
        // store arm.
        let c = WitContract {
            de: "cart".into(),
            para: "kv".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("carts/{cart_id}".into()),
        };
        let slot = c.slot().expect("Some arm");
        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
        assert_eq!(
            slot.as_ptr(),
            storage_slice.as_ptr(),
            "WitContract::slot must borrow from the .slot String's \
             backing storage — a fresh allocation here means the \
             accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            slot.len(),
            storage_slice.len(),
            "WitContract::slot and .slot.as_deref() must byte-equal \
             in length as well as in address",
        );
    }

    #[test]
    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
        // [`Membro::nome`] must return the `:membros :caixa` field
        // byte-for-byte, borrowed from the typed slot's own [`String`]
        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
        // slot-atom scalar-value axes — same "the substrate-primitive
        // accessor must byte-equal the raw field access verbatim across
        // every author-declared value" discipline extended to the
        // per-`:membros` member-identity arm. Pins against a future
        // silent detour that re-normalized the member identity (an
        // accidental `.to_lowercase()` — every `:membros :caixa` is
        // validated as a DNS-1123 label upstream via
        // [`validate_membro_caixa`], so any re-normalization is
        // redundant + a drift surface between the validator and the
        // accessor), a namespace-prefix rewrite (an accidental
        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
        // rewrite that didn't land on the peer axes), or a per-cluster
        // alias stamp the operator authors on one consumer without the
        // other. Four values sweep the accept-set the DNS-1123 gate
        // upstream admits (short single-word / dashed / v-suffixed
        // member names).
        for name in ["cart", "checkout", "catalog", "orders-v2"] {
            let m = Membro {
                caixa: name.into(),
                versao: "^0.1".into(),
            };
            assert_eq!(
                m.nome(),
                name,
                "Membro::nome must return :membros :caixa verbatim \
                 (got {:?}, expected {name:?})",
                m.nome(),
            );
            assert_eq!(
                m.nome(),
                m.caixa.as_str(),
                "Membro::nome must byte-equal the .caixa field access",
            );
        }
    }

    #[test]
    fn membro_nome_borrows_from_caixa_storage() {
        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
        // slice that borrows from the typed slot's own [`String`]
        // storage — same-address invariant with `m.caixa.as_str()`. Pins
        // against a future silent detour that allocated a fresh `String`
        // (`self.caixa.clone()` in the body would type-check but
        // silently drop the borrow, and every downstream consumer that
        // assumed the returned slice outlives `&self` would break on a
        // stale-reference use-after-free — the `HashSet<&str>` collector
        // at [`AplicacaoSpec::validate`]'s `names` seed, the
        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
        // [`AplicacaoSpec::detect_sync_cycles`], the
        // [`crate::render::insert_first_seen`] dedup key at
        // [`AplicacaoSpec::validate_membros`] — each borrow from the
        // Membro's own storage and each would silently misbehave if
        // this accessor produced a detached copy). Peer of the sibling
        // per-`:contratos` [`WitContract::source`] /
        // [`WitContract::destination`] and per-`:entrada`
        // [`Entrada::destination`] borrow-invariant pins on the mesh-
        // slot-atom scalar-value axes.
        let m = Membro {
            caixa: "checkout".into(),
            versao: "^0.1".into(),
        };
        let name = m.nome();
        let caixa_slice = m.caixa.as_str();
        assert_eq!(
            name.as_ptr(),
            caixa_slice.as_ptr(),
            "Membro::nome must borrow from the .caixa String's backing \
             storage — a fresh allocation here means the accessor no \
             longer names the substrate-primitive typed dispatch and \
             every downstream consumer would silently carry a detached \
             copy",
        );
        assert_eq!(
            name.len(),
            caixa_slice.len(),
            "Membro::nome and .caixa.as_str() must byte-equal in length \
             as well as in address",
        );
    }

    #[test]
    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
        // The canonical per-`:membros` member-`:versao`-scalar pin:
        // [`Membro::versao_requirement`] must return the
        // `:membros :versao` field byte-for-byte, borrowed from the typed
        // slot's own [`String`] storage. Sibling of the peer
        // `membro_nome_returns_caixa_byte_equal_across_permutations`
        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
        // — same "the substrate-primitive accessor must byte-equal the
        // raw field access verbatim across every author-declared value"
        // discipline extended to the per-`:membros` member-`:versao`
        // requirement-string arm. Pins against a future silent detour
        // that re-canonicalized the requirement (an accidental
        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
        // drifted the printer output away from the source `caixa.lisp`,
        // an accidental whitespace trim on `"^ 0.1"` that no consumer
        // ever produced from the field-access side, an accidental
        // per-cluster lacre-projected concrete-version rewrite that
        // didn't land on the peer field-access sites). Five values sweep
        // the accept-set the shared
        // [`crate::render::require_valid_versao_requirement`] gate
        // admits (caret / tilde / exact / wildcard / bare-major).
        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
            let m = Membro {
                caixa: "cart".into(),
                versao: req.into(),
            };
            assert_eq!(
                m.versao_requirement(),
                req,
                "Membro::versao_requirement must return :membros :versao \
                 verbatim (got {:?}, expected {req:?})",
                m.versao_requirement(),
            );
            assert_eq!(
                m.versao_requirement(),
                m.versao.as_str(),
                "Membro::versao_requirement must byte-equal the .versao \
                 field access",
            );
        }
    }

    #[test]
    fn membro_versao_requirement_borrows_from_versao_storage() {
        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
        // return a `&str` slice that borrows from the typed slot's own
        // [`String`] storage — same-address invariant with
        // `m.versao.as_str()`. Pins against a future silent detour that
        // allocated a fresh `String` (`self.versao.clone()` in the body
        // would type-check but silently drop the borrow, and every
        // downstream consumer that assumed the returned slice outlives
        // `&self` would break on a stale-reference use-after-free). Peer
        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
        // per-`:contratos` [`WitContract::source`] /
        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
        // the mesh-slot-atom scalar-value axes.
        let m = Membro {
            caixa: "checkout".into(),
            versao: "^0.1".into(),
        };
        let req = m.versao_requirement();
        let versao_slice = m.versao.as_str();
        assert_eq!(
            req.as_ptr(),
            versao_slice.as_ptr(),
            "Membro::versao_requirement must borrow from the .versao \
             String's backing storage — a fresh allocation here means \
             the accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently carry \
             a detached copy",
        );
        assert_eq!(
            req.len(),
            versao_slice.len(),
            "Membro::versao_requirement and .versao.as_str() must byte-\
             equal in length as well as in address",
        );
    }

    #[test]
    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
        // Sibling-pair invariant pin composing both per-`:membros`
        // substrate-primitive typed dispatches — [`Membro::nome`]
        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
        // `(nome(), versao_requirement())` call shape every renderer
        // that fans on per-member identity + version pin keys off. The
        // invariant, evaluated per-member:
        //
        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
        //
        // Closes the last unlifted per-`:membros` scalar axis — every
        // downstream consumer that reads the pair now routes through
        // exactly two typed dispatches on the substrate primitive, not
        // one typed + one open-coded field access. A future refactor
        // that silently split either accessor's projection (an
        // accidental `nome()` namespace-prefix rewrite that didn't
        // reach the peer, an accidental `versao_requirement()` lacre-
        // projected concrete-version rewrite that didn't land on the
        // `nome()` peer) surfaces at caixa-core build time. Peer of the
        // sibling per-`:entrada` `(hostname(), destination())` and
        // per-`:contratos` `(source(), destination())` pair invariants
        // on the mesh-slot-atom scalar-value axes.
        for (caixa, versao) in [
            ("cart", "^0.1"),
            ("checkout", "~0.1.2"),
            ("catalog", "0.1.0"),
            ("orders-v2", "*"),
        ] {
            let m = Membro {
                caixa: caixa.into(),
                versao: versao.into(),
            };
            assert_eq!(
                (m.nome(), m.versao_requirement()),
                (m.caixa.as_str(), m.versao.as_str()),
                "(Membro::nome, Membro::versao_requirement) must project \
                 (.caixa, .versao) verbatim across every author-declared \
                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
                m.nome(),
                m.versao_requirement(),
            );
        }
    }

    #[test]
    fn validate_membros_empty_gate_routes_through_nome_accessor() {
        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
        // not the raw `.caixa` field access. Structurally: setting
        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
        // (i.e. the empty string) — so the emptiness predicate the
        // refusal arm reaches under is the accessor-projected value,
        // not a peer field that would silently drift under a future
        // accessor-side rewrite.
        //
        // Pins against a future silent detour that (a) re-derived the
        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
        // instead of `self.nome().is_empty()`, silently disagreeing with
        // every peer consumer (the `validate_membro_caixa(m.nome())`
        // call one line below, the dedup-key `insert_first_seen(&mut
        // seen, m.nome(), …)` two lines below, the emit-side per-
        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
        // (b) accessor-side introduced a per-tenant alias arm the
        // caller was unaware of, silently rewriting an author-declared
        // `:caixa "checkout"` to `""` — the raw-field-access gate
        // would fail-open while the accessor-routed peer consumers
        // would fail-closed, splitting the diagnostic from the actual
        // failure surface.
        //
        // Peer of the sibling
        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
        // (c0110f1) composition pin — same "the shape-gate predicate
        // must route through the substrate-primitive typed dispatch"
        // discipline extended onto the per-`:membros` empty-`:caixa`
        // refusal-arm axis. Closes the last unlifted `.caixa` production-
        // code read site on `Membro` — after this converge every
        // caixa-core `.caixa` field access outside the accessor's own
        // body is either a test-side field-setter (in-module tests
        // constructing invalid-shape inputs) or a doc-comment reference.
        let mut s = three_member_spec();
        s.membros[1].caixa = String::new();
        assert!(
            s.membros[1].nome().is_empty(),
            "Membro::nome must byte-equal the .caixa field access — an \
             accessor-side detour that no longer projects the raw field \
             would silently split this drift-detection test from the \
             validate() refusal arm",
        );
        assert_eq!(
            s.membros[1].nome(),
            s.membros[1].caixa.as_str(),
            "Membro::nome and .caixa.as_str() must byte-equal on an \
             empty-`:caixa` entry — the emptiness gate keys off the \
             accessor by construction",
        );
        assert_eq!(
            s.validate().unwrap_err(),
            AplicacaoError::MembroCaixaEmpty,
            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
             on an entry whose accessor-projected `nome()` is empty",
        );
    }

    #[test]
    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
        // The canonical per-`:placement` Akka-cluster-sharding
        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
        // the `:placement :shard-key` field byte-for-byte, borrowed
        // from the typed slot's own `Option<String>` storage. Peer of
        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
        // per-`:contratos` [`WitContract::source`] /
        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
        // slot-atom scalar-value axes — same "the substrate-primitive
        // accessor must byte-equal the raw field access verbatim across
        // every author-declared value" discipline extended to the
        // per-`:placement` Akka-cluster-sharding key extractor arm.
        // Pins against a future silent detour that re-normalized the
        // key (an accidental `.to_lowercase()` — every non-empty
        // `:shard-key` is validated as a printable-ASCII single-token
        // reference upstream via [`validate_placement_shard_key`], so
        // any re-normalization is redundant + a drift surface between
        // the validator and the accessor), a per-cluster alias rewrite
        // the operator authors on one consumer without the other, or an
        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
        // that didn't land on the peer field-access sites. Four values
        // sweep the accept-set the shape gate admits — bare identifier,
        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
        // the four canonical Akka-style entity-id extractor shapes the
        // future M4 cluster-sharding reconciler hashes.
        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
            let p = Placement {
                estrategia: PlacementStrategy::Sharded,
                clusters: vec!["rio".into()],
                affinity: None,
                shard_key: Some(key.into()),
            };
            assert_eq!(
                p.shard_key(),
                Some(key),
                "Placement::shard_key must return :placement :shard-key \
                 verbatim (got {:?}, expected Some({key:?}))",
                p.shard_key(),
            );
            assert_eq!(
                p.shard_key(),
                p.shard_key.as_deref(),
                "Placement::shard_key must byte-equal the .shard_key \
                 field's `.as_deref()` projection",
            );
        }
    }

    #[test]
    fn placement_shard_key_none_when_field_is_none() {
        // The absent-`:shard-key` arm of the per-`:placement`
        // Akka-cluster-sharding accessor pin: when the typed slot is
        // absent — the canonical shape under `:estrategia Replicated` /
        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
        // enforced `shard_key.is_some() == matches!(estrategia,
        // Sharded)` partition — [`Placement::shard_key`] must return
        // `None`. Pins against a future silent detour that projected
        // the absent slot to a `Some("")` empty-string default (the
        // canonical `Option<String>` → `String` collapse footgun the
        // sibling M2 [`crate::LimitsSpec::is_empty`] /
        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
        // already guard on the peer M2 typed-slot surfaces), a
        // `Some("None")` stringified-None round-trip, or a `Some` arm
        // whose contents were derived from a sibling slot (an
        // accidental fallback to `estrategia.as_str()` that read the
        // strategy discriminator into the key axis). Two placements
        // sweep the accept-set every `validate`-passing non-`Sharded`
        // shape lands on — `Replicated` (Erlang/OTP distributed-app
        // takeover) and `SingleNode` (single-node hosting).
        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
            let p = Placement {
                estrategia,
                clusters: vec!["rio".into()],
                affinity: None,
                shard_key: None,
            };
            assert!(
                p.shard_key().is_none(),
                "Placement::shard_key must return None when the typed \
                 slot is absent under :estrategia {estrategia:?} (got {:?})",
                p.shard_key(),
            );
            assert_eq!(
                p.shard_key(),
                p.shard_key.as_deref(),
                "Placement::shard_key must byte-equal the .shard_key \
                 field's `.as_deref()` projection in the absent arm",
            );
        }
    }

    #[test]
    fn placement_shard_key_borrows_from_shard_key_storage() {
        // The borrow-not-copy pin: [`Placement::shard_key`] must return
        // an `Option<&str>` whose `Some` arm borrows from the typed
        // slot's own [`String`] storage — same-address invariant with
        // `p.shard_key.as_deref().unwrap()`. Pins against a future
        // silent detour that allocated a fresh `String`
        // (`self.shard_key.clone().map(...)` in the body would type-
        // check but silently drop the borrow, and every downstream
        // consumer that assumed the returned slice outlives `&self`
        // would break on a stale-reference use-after-free — the
        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
        // gate's `Some(k)`-bound match arm reads `k: &str` under the
        // accessor's return type and would silently misbehave if this
        // accessor produced a detached copy). Peer of the sibling
        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
        // [`WitContract::source`] / [`WitContract::destination`]
        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
        // (6db982c) borrow-invariant pins on the mesh-slot-atom
        // scalar-value axes — first extension of the discipline onto
        // an `Option<String>`-shaped optional-scalar axis.
        let p = Placement {
            estrategia: PlacementStrategy::Sharded,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: Some("tenantId".into()),
        };
        let key = p.shard_key().expect("Some arm");
        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
        assert_eq!(
            key.as_ptr(),
            storage_slice.as_ptr(),
            "Placement::shard_key must borrow from the .shard_key \
             String's backing storage — a fresh allocation here means \
             the accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            key.len(),
            storage_slice.len(),
            "Placement::shard_key and .shard_key.as_deref() must byte-\
             equal in length as well as in address",
        );
    }

    #[test]
    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
        // The canonical per-`:placement` M3-Adaptive-compression-hint
        // scalar pin: [`Placement::affinity`] must return the
        // `:placement :affinity` field byte-for-byte, borrowed from the
        // typed slot's own `Option<String>` storage. Peer of the sibling
        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
        // pin on the sibling `Option<&str>` optional-scalar axis — same
        // "the substrate-primitive accessor must byte-equal the raw
        // field access verbatim across every author-declared value"
        // discipline extended to the peer per-`:placement` M3-Adaptive-
        // compression-hint arm. Pins against a future silent detour
        // that re-normalized the hint (an accidental `.to_lowercase()`
        // — every `:affinity` is already validated as a DNS-1123 label
        // upstream via [`validate_placement_affinity`], so any re-
        // normalization is redundant + a drift surface between the
        // validator and the accessor), a per-cluster alias rewrite the
        // operator authors on one consumer without the other, or an
        // accidental hint-family collapse (`low-latency` → `latency`
        // that dropped the qualifier prefix). Four values sweep the
        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
        // canonical adaptive-compression-weight biases the future M4
        // placement engine reads.
        for hint in [
            "data-locality",
            "low-latency",
            "high-throughput",
            "cost-optimized",
        ] {
            let p = Placement {
                estrategia: PlacementStrategy::Replicated,
                clusters: vec!["rio".into()],
                affinity: Some(hint.into()),
                shard_key: None,
            };
            assert_eq!(
                p.affinity(),
                Some(hint),
                "Placement::affinity must return :placement :affinity \
                 verbatim (got {:?}, expected Some({hint:?}))",
                p.affinity(),
            );
            assert_eq!(
                p.affinity(),
                p.affinity.as_deref(),
                "Placement::affinity must byte-equal the .affinity \
                 field's `.as_deref()` projection",
            );
        }
    }

    #[test]
    fn placement_affinity_none_when_field_is_none() {
        // The absent-`:affinity` arm of the per-`:placement`
        // M3-Adaptive-compression-hint accessor pin: when the typed
        // slot is absent — the canonical shape of an Aplicacao that
        // leaves the compression weighting up to the placement engine's
        // cluster-default arm — [`Placement::affinity`] must return
        // `None`. Pins against a future silent detour that projected
        // the absent slot to a `Some("")` empty-string default (the
        // canonical `Option<String>` → `String` collapse footgun the
        // sibling M2 [`crate::LimitsSpec::is_empty`] /
        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
        // already guard on the peer M2 typed-slot surfaces), a
        // `Some("None")` stringified-None round-trip, a `Some` arm
        // whose contents were derived from a sibling slot (an
        // accidental fallback to `estrategia.as_str()` that read the
        // strategy discriminator into the hint axis), or a
        // `Some("default")` implicit-default that would silently biases
        // the routing without the author having written one. Three
        // placements sweep the accept-set every `validate`-passing
        // `:affinity None` shape lands on — one per PlacementStrategy
        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
        // with a shard-key), since `:affinity` is orthogonal to
        // `:estrategia` in the typed grammar.
        for (estrategia, shard_key) in [
            (PlacementStrategy::SingleNode, None),
            (PlacementStrategy::Replicated, None),
            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
        ] {
            let p = Placement {
                estrategia,
                clusters: vec!["rio".into()],
                affinity: None,
                shard_key,
            };
            assert!(
                p.affinity().is_none(),
                "Placement::affinity must return None when the typed \
                 slot is absent under :estrategia {estrategia:?} (got {:?})",
                p.affinity(),
            );
            assert_eq!(
                p.affinity(),
                p.affinity.as_deref(),
                "Placement::affinity must byte-equal the .affinity \
                 field's `.as_deref()` projection in the absent arm",
            );
        }
    }

    #[test]
    fn placement_affinity_borrows_from_affinity_storage() {
        // The borrow-not-copy pin: [`Placement::affinity`] must return
        // an `Option<&str>` whose `Some` arm borrows from the typed
        // slot's own [`String`] storage — same-address invariant with
        // `p.affinity.as_deref().unwrap()`. Pins against a future
        // silent detour that allocated a fresh `String`
        // (`self.affinity.clone().map(...)` in the body would type-
        // check but silently drop the borrow, and every downstream
        // consumer that assumed the returned slice outlives `&self`
        // would break on a stale-reference use-after-free — the
        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
        // gate reads the accessor's `&str` return through the
        // [`validate_placement_affinity`] `&str` parameter and would
        // silently misbehave if this accessor produced a detached
        // copy). Peer of the sibling per-`:placement`
        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
        // extends the discipline onto the sibling per-`:placement`
        // M3-Adaptive-compression-hint arm.
        let p = Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: Some("data-locality".into()),
            shard_key: None,
        };
        let hint = p.affinity().expect("Some arm");
        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
        assert_eq!(
            hint.as_ptr(),
            storage_slice.as_ptr(),
            "Placement::affinity must borrow from the .affinity \
             String's backing storage — a fresh allocation here means \
             the accessor no longer names the substrate-primitive typed \
             dispatch and every downstream consumer would silently \
             carry a detached copy",
        );
        assert_eq!(
            hint.len(),
            storage_slice.len(),
            "Placement::affinity and .affinity.as_deref() must byte-\
             equal in length as well as in address",
        );
    }

    #[test]
    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
        // The canonical per-`:placement` distribution-strategy-scalar
        // pin: [`Placement::estrategia`] must return the `:placement
        // :estrategia` field verbatim as a [`PlacementStrategy`],
        // `Copy`-projected from the typed slot's own `PlacementStrategy`
        // storage across every variant in the closed accept-set
        // (`SingleNode` — Erlang/OTP distributed-app takeover;
        // `Replicated` — active-active across every named cluster;
        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
        // against a future silent detour that re-derived the strategy
        // from a peer axis (an accidental fallback to
        // `if shard_key.is_some() { Sharded } else { Replicated }`
        // collapse that read the shard-key axis into the strategy
        // discriminator), a variant remap the operator authors on one
        // consumer without the other, or a stale-derive detour that
        // substituted [`PlacementStrategy::default`] when the field
        // held any explicit variant (which would silently collapse the
        // distinction between "author explicitly declared `:estrategia
        // Replicated`" and "author omitted the slot and inherited the
        // default" the future per-cluster override slot depends on).
        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
        // pin on the `Copy`-return `u16` scalar axis — same "the
        // substrate-primitive accessor must byte-equal the raw field
        // access verbatim across every author-declared value" discipline
        // extended onto the per-`:placement` distribution-strategy
        // `Copy`-composite-enum scalar axis.
        for estrategia in [
            PlacementStrategy::SingleNode,
            PlacementStrategy::Replicated,
            PlacementStrategy::Sharded,
        ] {
            let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
            let p = Placement {
                estrategia,
                clusters: vec!["rio".into()],
                affinity: None,
                shard_key,
            };
            assert_eq!(
                p.estrategia(),
                estrategia,
                "Placement::estrategia must return :placement :estrategia \
                 verbatim (got {:?}, expected {estrategia:?})",
                p.estrategia(),
            );
            assert_eq!(
                p.estrategia(),
                p.estrategia,
                "Placement::estrategia accessor and .estrategia field \
                 access must byte-equal — the accessor is the substrate-\
                 primitive typed dispatch every downstream distribution-\
                 strategy consumer must route through",
            );
        }
    }

    #[test]
    fn validate_placement_reads_through_lifted_estrategia_accessor() {
        // Three-consumer coherence pin: the
        // [`AplicacaoSpec::validate_placement`]
        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
        // `estrategia:` field (which reads through
        // [`Placement::estrategia`] to name the strategy the empty
        // `:clusters` list was declared against), the same method's
        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
        // reads through [`Placement::estrategia`] to fan across the
        // shape-gate cascades), and the non-`Sharded`-arm
        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
        // `estrategia:` field (which reads through
        // [`Placement::estrategia`] to name the strategy the declared-
        // but-inert `:shard-key` was authored under) must all key off
        // the lifted accessor, so any future rebrand on the typed
        // slot's reader shape lands at exactly one place. Pins the
        // three-site coherence by exercising each error surface end-
        // to-end and asserting the surfaced `estrategia:` field byte-
        // equals the accessor's return. Peer of the sibling per-
        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
        // pin on the M3 mesh-slot `Copy`-return scalar axis.

        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
        // whose `estrategia:` field must byte-equal the accessor's return
        // for every variant in the closed accept-set.
        for estrategia in [
            PlacementStrategy::SingleNode,
            PlacementStrategy::Replicated,
            PlacementStrategy::Sharded,
        ] {
            let mut spec = three_member_spec();
            spec.placement.estrategia = estrategia;
            spec.placement.clusters = Vec::new();
            spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
            let err = spec.validate().unwrap_err();
            match err {
                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
                    assert_eq!(
                        e,
                        spec.placement.estrategia(),
                        "PlacementWithoutClusters.estrategia must byte-equal \
                         Placement::estrategia() — the error carrier reads \
                         through the lifted accessor",
                    );
                }
                other => panic!(
                    "expected PlacementWithoutClusters, got {other:?} for \
                     estrategia={estrategia:?}"
                ),
            }
        }

        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
        // must byte-equal the accessor's return for both non-`Sharded`
        // strategies.
        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
            let mut spec = three_member_spec();
            spec.placement.estrategia = estrategia;
            spec.placement.shard_key = Some("tenantId".into());
            let err = spec.validate().unwrap_err();
            match err {
                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
                    assert_eq!(
                        e,
                        spec.placement.estrategia(),
                        "ShardKeyOnNonSharded.estrategia must byte-equal \
                         Placement::estrategia() — the non-Sharded-arm \
                         refusal reads through the lifted accessor",
                    );
                }
                other => panic!(
                    "expected ShardKeyOnNonSharded, got {other:?} for \
                     estrategia={estrategia:?}"
                ),
            }
        }
    }

    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
    //
    // The [`Placement::clusters`] accessor lift is the second slice-return
    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
    // below cover (1) the accessor's byte-equal projection against the raw
    // field access across the empty / singleton / cohort fixtures the
    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
    // and the per-cluster validate loop fan between, and (2) the two-
    // consumer coherence of the paired pre-flight refusal probe and the
    // per-cluster validate loop routing through the accessor on both arms.

    #[test]
    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
        // [`Placement::clusters`] must return the `:placement :clusters`
        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
        // the same backing buffer the raw `self.clusters.as_slice()`
        // field access borrows from, byte-equal across every
        // representative fixture in the accept-set — the empty slice
        // (the pre-validation sentinel every
        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
        // the singleton slice (the minimal `SingleNode`-shape cohort),
        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
        //
        // Pins against a future silent detour that returned
        // `&Vec<String>` (which would type-check but leak the storage-
        // side `Vec`'s grow/push/reserve surface no consumer of the
        // typed view reaches for), a fresh-allocated `Vec<String>` copy
        // (which would type-check via a coercion but silently break
        // every downstream caller that relied on the slice sharing the
        // backing buffer's identity), or an out-of-order or length-
        // drifted projection (which would silently split the paired
        // pre-flight `.is_empty()` refusal probe's input from the per-
        // cluster validate loop's traversal input).
        //
        // Peer of the sibling M2
        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
        // `:supervisor` static-child-list axis, extended onto the M3
        // per-`:placement` distribution-target-list `Vec`-carry axis.
        let fixtures: Vec<Vec<String>> = vec![
            Vec::new(),
            vec!["rio".into()],
            vec!["rio".into(), "mar".into()],
            vec!["rio".into(), "mar".into(), "plo".into()],
        ];
        for clusters in fixtures {
            let p = Placement {
                clusters: clusters.clone(),
                ..Placement::default()
            };
            assert_eq!(
                p.clusters(),
                clusters.as_slice(),
                "Placement::clusters must return :placement :clusters \
                 verbatim (got {:?}, expected {:?})",
                p.clusters(),
                clusters.as_slice(),
            );
            assert_eq!(
                p.clusters(),
                p.clusters.as_slice(),
                "Placement::clusters accessor and .clusters.as_slice() \
                 field access must byte-equal — the accessor is the \
                 substrate-primitive typed dispatch every downstream \
                 cluster-pool consumer must route through",
            );
            assert_eq!(
                p.clusters().len(),
                p.clusters.len(),
                "Placement::clusters().len() must byte-equal \
                 self.clusters.len() — a length-drift would silently \
                 split the paired pre-flight `.is_empty()` refusal \
                 probe input from the per-cluster validate loop's \
                 traversal input",
            );
        }
    }

    #[test]
    fn validate_placement_reads_through_lifted_clusters_accessor() {
        // Two-consumer coherence pin: the
        // [`AplicacaoSpec::validate_placement`] pre-flight
        // `self.placement.clusters().is_empty()` refusal probe (which
        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
        // the accessor projects the empty slice) and the per-cluster
        // validate loop's `for c in self.placement.clusters()`
        // traversal (which must reach every entry in the same order
        // the accessor projects, so both the per-entry value-shape
        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
        // and the duplicate-detection HashSet insert that trips
        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
        // accessor's projection) must both key off the lifted
        // accessor, so any future rebrand on the typed slot's reader
        // shape lands at exactly one place. Pins the two-site
        // coherence by exercising each production consumer end-to-end:
        // (1) the `PlacementWithoutClusters` refusal under the empty
        // slice, (2) the `PlacementClusterInvalid` refusal fires on
        // the second entry of a two-cluster cohort whose head is
        // valid but tail is not (which requires the loop to reach the
        // second entry through the accessor), and (3) the
        // `PlacementClusterDuplicate` refusal fires on the second
        // entry of a two-cluster cohort that shares a name (which
        // requires the loop to reach both entries — a first-entry-only
        // projection would silently pass since the dedup HashSet has
        // room for the first insert).
        //
        // Peer of the sibling M2
        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
        // (bc92bce) coherence pin on the per-`:supervisor` static-
        // child-list axis, extended onto the M3 per-`:placement`
        // distribution-target-list `Vec`-carry axis.

        // (1) Pre-flight `.is_empty()` probe: the empty slice must
        // trip `PlacementWithoutClusters`.
        let mut spec = three_member_spec();
        spec.placement.clusters = Vec::new();
        match spec.validate().unwrap_err() {
            AplicacaoError::PlacementWithoutClusters { .. } => {}
            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
        }
        assert!(
            spec.placement.clusters().is_empty(),
            "the pre-flight refusal input must be the empty slice per \
             the accessor's projection",
        );

        // (2) Per-cluster validate loop: a two-cluster cohort with an
        // invalid tail entry must trip `PlacementClusterInvalid` on
        // the tail — the loop must reach the second entry through
        // the accessor.
        let mut spec = three_member_spec();
        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
        match spec.validate().unwrap_err() {
            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
                assert_eq!(
                    cluster, "BAD_CLUSTER",
                    "PlacementClusterInvalid.cluster must carry the \
                     tail entry the loop reached through the accessor",
                );
            }
            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
        }
        assert_eq!(
            spec.placement.clusters().len(),
            2,
            "the per-cluster validate loop's traversal input must be \
             a two-element slice per the accessor's projection",
        );

        // (3) Per-cluster validate loop: a two-cluster cohort that
        // shares a name must trip `PlacementClusterDuplicate` on the
        // second entry — the loop must reach both entries through the
        // accessor for the dedup HashSet's second insert to collide.
        let mut spec = three_member_spec();
        spec.placement.clusters = vec!["rio".into(), "rio".into()];
        match spec.validate().unwrap_err() {
            AplicacaoError::PlacementClusterDuplicate { cluster } => {
                assert_eq!(
                    cluster, "rio",
                    "PlacementClusterDuplicate.cluster must carry the \
                     shared cluster name verbatim",
                );
            }
            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
        }
        assert_eq!(
            spec.placement.clusters().len(),
            2,
            "the per-cluster validate loop's traversal input must be \
             a two-element slice per the accessor's projection",
        );
    }

    #[test]
    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
        // The canonical per-`:membros` member-list-slice-shape pin:
        // [`AplicacaoSpec::membros`] must return the `:membros` typed
        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
        // same backing buffer the raw `self.membros.as_slice()` field
        // access borrows from, byte-equal across every representative
        // fixture in the accept-set — the empty slice (the pre-
        // validation sentinel every [`AplicacaoError::NoMembros`]
        // refusal keys off), the singleton slice (the minimal one-
        // Servico Aplicacao shape), and multi-entry cohorts (the peer
        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
        // load-bearing identity of the application graph).
        //
        // Pins against a future silent detour that returned
        // `&Vec<Membro>` (which would type-check but leak the storage-
        // side `Vec`'s grow/push/reserve surface no consumer of the
        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
        // (which would type-check via a coercion but silently break
        // every downstream caller that relied on the slice sharing the
        // backing buffer's identity), or an out-of-order or length-
        // drifted projection (which would silently split the paired
        // `HashSet<&str>` name-set seed's collect input from the
        // pre-flight `.is_empty()` refusal probe's input from the per-
        // member validate loop's traversal input from the
        // programs.yaml emitter's per-entry fan-out loop's input from
        // the `feira app graph` per-member print traversal's input).
        //
        // Peer of the sibling M2
        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
        // `:supervisor` static-child-list axis and the sibling M3
        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
        // (a6e18d7) `&[String]` byte-equal pin on the per-
        // `:placement` distribution-target-list axis — extends the
        // slice-return-accessor byte-equal-projection discipline onto
        // the outermost M3 mesh-slot type's per-Aplicacao member-list
        // `Vec`-carry axis.
        let fixtures: Vec<Vec<Membro>> = vec![
            Vec::new(),
            vec![membro("catalog", "^0.1")],
            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
            vec![
                membro("catalog", "^0.1"),
                membro("cart", "^0.1"),
                membro("payment", "^0.2"),
            ],
        ];
        for membros in fixtures {
            let s = AplicacaoSpec {
                membros: membros.clone(),
                contratos: Vec::new(),
                politicas: MeshPolicy::default(),
                placement: Placement::default(),
                entrada: None,
            };
            assert_eq!(
                s.membros(),
                membros.as_slice(),
                "AplicacaoSpec::membros must return :membros verbatim \
                 (got {:?}, expected {:?})",
                s.membros(),
                membros.as_slice(),
            );
            assert_eq!(
                s.membros(),
                s.membros.as_slice(),
                "AplicacaoSpec::membros accessor and .membros.as_slice() \
                 field access must byte-equal — the accessor is the \
                 substrate-primitive typed dispatch every downstream \
                 member-list consumer must route through",
            );
            assert_eq!(
                s.membros().len(),
                s.membros.len(),
                "AplicacaoSpec::membros().len() must byte-equal \
                 self.membros.len() — a length-drift would silently \
                 split the paired `HashSet<&str>` name-set seed's \
                 collect input from the pre-flight `.is_empty()` \
                 refusal probe input from the per-member validate \
                 loop's traversal input",
            );
        }
    }

    #[test]
    fn validate_reads_through_lifted_membros_accessor() {
        // Three-consumer coherence pin: the
        // [`AplicacaoSpec::validate_membros`] pre-flight
        // `self.membros().is_empty()` refusal probe (which must trip
        // [`AplicacaoError::NoMembros`] when the accessor projects the
        // empty slice), the same method's per-member validate loop's
        // `for m in self.membros()` traversal (which must reach every
        // entry in the same order the accessor projects, so both the
        // per-entry empty-`:caixa` gate that trips
        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
        // detection `insert_first_seen` that trips
        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
        // projection), and the peer [`AplicacaoSpec::validate`]'s
        // `HashSet<&str>` name-set seed's
        // `self.membros().iter().map(Membro::nome).collect()` collect
        // input (which every `:contratos` `:de` / `:para` membership
        // lookup rejects an unknown name against) must all three key
        // off the lifted accessor, so any future rebrand on the typed
        // slot's reader shape lands at exactly one place. Pins the
        // three-site coherence by exercising each production consumer
        // end-to-end: (1) the `NoMembros` refusal under the empty
        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
        // second entry of a two-member cohort whose head is valid but
        // tail has an empty `:caixa` (which requires the loop to
        // reach the second entry through the accessor), and (3) the
        // `MembroDuplicate` refusal fires on the second entry of a
        // two-member cohort that shares a `:caixa` name (which
        // requires the loop to reach both entries through the
        // accessor for the dedup HashSet's second insert to collide).
        //
        // Peer of the sibling M2
        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
        // (bc92bce) coherence pin on the per-`:supervisor` static-
        // child-list axis and the sibling M3
        // `validate_placement_reads_through_lifted_clusters_accessor`
        // (a6e18d7) coherence pin on the per-`:placement` distribution-
        // target-list axis — extends the slice-return-accessor
        // multi-consumer coherence discipline onto the outermost M3
        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.

        // (1) Pre-flight `.is_empty()` probe: the empty slice must
        // trip `NoMembros`.
        let mut spec = three_member_spec();
        spec.membros = Vec::new();
        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
        assert!(
            spec.membros().is_empty(),
            "the pre-flight refusal input must be the empty slice per \
             the accessor's projection",
        );

        // (2) Per-member validate loop: a two-member cohort with an
        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
        // the tail — the loop must reach the second entry through
        // the accessor.
        let mut spec = three_member_spec();
        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::MembroCaixaEmpty,
        );
        assert_eq!(
            spec.membros().len(),
            2,
            "the per-member validate loop's traversal input must be \
             a two-element slice per the accessor's projection",
        );

        // (3) Per-member validate loop: a two-member cohort that
        // shares a `:caixa` name must trip `MembroDuplicate` on the
        // second entry — the loop must reach both entries through the
        // accessor for the dedup HashSet's second insert to collide.
        let mut spec = three_member_spec();
        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
        match spec.validate().unwrap_err() {
            AplicacaoError::MembroDuplicate { caixa } => {
                assert_eq!(
                    caixa, "catalog",
                    "MembroDuplicate.caixa must carry the shared \
                     member name verbatim",
                );
            }
            other => panic!("expected MembroDuplicate, got {other:?}"),
        }
        assert_eq!(
            spec.membros().len(),
            2,
            "the per-member validate loop's traversal input must be \
             a two-element slice per the accessor's projection",
        );
    }

    #[test]
    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
        // The canonical per-`:contratos` contract-list-slice-shape pin:
        // [`AplicacaoSpec::contratos`] must return the `:contratos`
        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
        // slice-view over the same backing buffer the raw
        // `self.contratos.as_slice()` field access borrows from, byte-
        // equal across every representative fixture in the accept-set —
        // the empty slice (the pre-validation "internal-only mesh" shape
        // an Aplicacao whose members exchange no typed edges renders
        // through), the singleton slice (the minimal one-edge Aplicacao
        // shape), and multi-entry cohorts (the peer multi-edge shapes
        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
        // of the application graph).
        //
        // Pins against a future silent detour that returned
        // `&Vec<WitContract>` (which would type-check but leak the
        // storage-side `Vec`'s grow/push/reserve surface no consumer of
        // the typed view reaches for), a fresh-allocated
        // `Vec<WitContract>` copy (which would type-check via a coercion
        // but silently break every downstream caller that relied on the
        // slice sharing the backing buffer's identity), or an out-of-
        // order or length-drifted projection (which would silently split
        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
        // seed's traversal input from the `detect_sync_cycles` per-edge
        // adjacency-list seed's traversal input from the
        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
        // BTreeMap grouping loop's traversal input from the
        // `feira app graph` per-contract print traversal's input).
        //
        // Peer of the immediately-adjacent sibling M3
        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
        // node-list axis, the sibling M3
        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
        // distribution-target-list axis, and the sibling M2
        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
        // `:supervisor` static-child-list axis — extends the slice-
        // return-accessor byte-equal-projection discipline onto the
        // outermost M3 mesh-slot type's per-Aplicacao contract-list
        // `Vec`-carry axis, closing the last unlifted per-
        // `AplicacaoSpec` `Vec`-carry axis.
        let fixtures: Vec<Vec<WitContract>> = vec![
            Vec::new(),
            vec![contract_http("cart", "catalog", "/products/:id")],
            vec![
                contract_http("cart", "catalog", "/products/:id"),
                contract_http("cart", "payment", "/charge"),
            ],
            vec![
                contract_http("cart", "catalog", "/products/:id"),
                contract_http("cart", "payment", "/charge"),
                contract_http("payment", "catalog", "/audit"),
            ],
        ];
        for contratos in fixtures {
            let s = AplicacaoSpec {
                membros: vec![
                    membro("catalog", "^0.1"),
                    membro("cart", "^0.1"),
                    membro("payment", "^0.2"),
                ],
                contratos: contratos.clone(),
                politicas: MeshPolicy::default(),
                placement: Placement::default(),
                entrada: None,
            };
            assert_eq!(
                s.contratos(),
                contratos.as_slice(),
                "AplicacaoSpec::contratos must return :contratos verbatim \
                 (got {:?}, expected {:?})",
                s.contratos(),
                contratos.as_slice(),
            );
            assert_eq!(
                s.contratos(),
                s.contratos.as_slice(),
                "AplicacaoSpec::contratos accessor and \
                 .contratos.as_slice() field access must byte-equal — \
                 the accessor is the substrate-primitive typed dispatch \
                 every downstream contract-list consumer must route \
                 through",
            );
            assert_eq!(
                s.contratos().len(),
                s.contratos.len(),
                "AplicacaoSpec::contratos().len() must byte-equal \
                 self.contratos.len() — a length-drift would silently \
                 split the paired per-edge validate-loop's traversal \
                 input from the sync-cycle adjacency-list seed's \
                 traversal input from the cilium_network_policies \
                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
                 input from the `feira app graph` per-contract print \
                 traversal's input",
            );
        }
    }

    #[test]
    fn validate_reads_through_lifted_contratos_accessor() {
        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
        // per-`:contratos` validate-loop's `for c in self.contratos()`
        // traversal (which must reach every entry in the same order the
        // accessor projects, so both the per-entry
        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
        // dedup `HashSet` insert key off the accessor's projection),
        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
        // `for c in self.contratos()` adjacency-list seed (which drives
        // the sync-subgraph deadlock-detection gate via
        // [`AplicacaoError::SyncCycle`]), and the peer
        // [`caixa_mesh::cilium_network_policies`]'s
        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
        // grouping loop (which drives the per-CNP fan-out) must all
        // three key off the lifted accessor, so any future rebrand on
        // the typed slot's reader shape lands at exactly one place. Pins
        // the three-site coherence by exercising the two caixa-core
        // production consumers end-to-end: (1) the empty-`:contratos`
        // slice must validate without a per-edge diagnostic (the
        // per-edge loop is a no-op under the empty projection), (2) the
        // `ContratoMemberMissing` refusal fires on the second entry of a
        // two-edge cohort whose head references a valid member but tail
        // references a phantom name (which requires the loop to reach
        // the second entry through the accessor), and (3) the
        // `SyncCycle` refusal fires on a self-referential two-edge
        // cohort through the sync-cycle detector's peer projection
        // (which requires the detector to iterate the accessor's
        // projection to add the back-edge to its adjacency list).
        //
        // Peer of the sibling M3
        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
        // three-consumer coherence pin on the per-`:membros` node-list
        // axis and the sibling M3
        // `validate_placement_reads_through_lifted_clusters_accessor`
        // (a6e18d7) coherence pin on the per-`:placement` distribution-
        // target-list axis — extends the slice-return-accessor multi-
        // consumer coherence discipline onto the outermost M3 mesh-slot
        // type's per-Aplicacao contract-list `Vec`-carry axis.

        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
        // and no per-edge diagnostic surfaces. Validate succeeds on
        // the well-formed `:membros` head.
        let mut spec = three_member_spec();
        spec.contratos = Vec::new();
        assert!(
            spec.validate().is_ok(),
            "empty :contratos must validate — the per-edge loop is a \
             no-op under the accessor's empty projection",
        );
        assert!(
            spec.contratos().is_empty(),
            "the per-edge validate loop's traversal input must be the \
             empty slice per the accessor's projection",
        );

        // (2) Per-edge validate loop: a two-edge cohort whose tail
        // references a phantom `:para` member must trip
        // `ContratoMemberMissing` on the tail — the loop must reach
        // the second entry through the accessor for the membership
        // lookup to fail on the phantom name.
        let mut spec = three_member_spec();
        spec.contratos = vec![
            contract_http("cart", "catalog", "/products/:id"),
            contract_http("cart", "phantom", "/x"),
        ];
        let err = spec.validate().unwrap_err();
        assert!(
            matches!(
                err,
                AplicacaoError::ContratoMemberMissing { ref caixa }
                    if caixa == "phantom"
            ),
            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
        );
        assert_eq!(
            spec.contratos().len(),
            2,
            "the per-edge validate loop's traversal input must be \
             a two-element slice per the accessor's projection",
        );

        // (3) Sync-cycle detector: a two-edge synchronous cohort
        // whose second edge closes the sync-subgraph back onto the
        // first must trip [`AplicacaoError::ContratoCycle`] — the
        // detector must iterate the accessor's projection to add
        // both edges to its adjacency list, so a length-drift on
        // the accessor's projection would silently disagree with
        // the sync-cycle detector on which edge closes the loop.
        // Peer projection to the `validate` per-edge loop above:
        // the sync-cycle detector routes through the same lifted
        // accessor, so a rebrand of the reader shape lands at one
        // place. Uses a two-edge cohort (cart → catalog → cart)
        // because the per-edge `ContratoSelfLoop` gate fires before
        // the sync-cycle detector on a single self-referential edge
        // (`cart → cart`) — the cycle-detector's input must be a
        // multi-edge cohort for its per-edge traversal input to be
        // observably wider than the per-edge validate loop's input.
        let mut spec = three_member_spec();
        spec.contratos = vec![
            contract_http("cart", "catalog", "/products/:id"),
            contract_http("catalog", "cart", "/callback"),
        ];
        let err = spec.validate().unwrap_err();
        assert!(
            matches!(err, AplicacaoError::ContratoCycle { .. }),
            "expected ContratoCycle from the sync-cycle detector on a \
             two-edge back-edge cohort, got {err:?}",
        );
        assert_eq!(
            spec.contratos().len(),
            2,
            "the sync-cycle detector's traversal input must be a \
             two-element slice per the accessor's projection",
        );
    }

    #[test]
    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
        // The canonical per-`:politicas` outer-composite-reference-shape
        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
        // the same backing storage the raw `&self.politicas` field
        // access borrows from, byte-equal across every representative
        // fixture in the accept-set — the default `MeshPolicy` (the
        // author-empty "no policy on any axis" shape whose
        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
        // shapes carrying one axis at a time
        // (`{mtls_required, timeout, retries, circuit_breaker,
        // rate_limit}` — the minimal five-axis fan-out over the
        // per-axis lifted accessor family every downstream mesh-artifact
        // emitter dispatches on), and the multi-axis composite (the
        // canonical `three_member_spec` fixture's `{timeout, retries,
        // mtls_required}` triple — the load-bearing shape every
        // Aplicacao-scoped fixture in this suite constructs).
        //
        // Pins against a future silent detour that returned a fresh-
        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
        // impl but silently break every downstream caller that relied
        // on the reference sharing the composite's backing identity), a
        // reference to an operator-resolved overlay (the future
        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
        // acknowledges — its resolution must land at exactly this
        // accessor body, not silently divert the raw slot away from a
        // second consumer), or an axis-shuffled projection (a future
        // detour that swapped `timeout` and `retries` through the
        // accessor would silently split the paired `validate_politicas`
        // per-axis bracket-dispatch's traversal input from the peer
        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
        // emitter's fan-out input from the peer
        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
        // overlay emitter's fan-out input).
        //
        // Peer of the sibling M3
        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
        // node-list `Vec`-carry axis and the sibling M3
        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
        // accessor byte-equal-projection discipline onto the outermost
        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
        // reference axis, the first `&Composite`-return accessor on the
        // outer [`AplicacaoSpec`] type.
        let fixtures: Vec<MeshPolicy> = vec![
            MeshPolicy::default(),
            MeshPolicy {
                mtls_required: Some(true),
                ..MeshPolicy::default()
            },
            MeshPolicy {
                mtls_required: Some(false),
                ..MeshPolicy::default()
            },
            MeshPolicy {
                timeout: Some(Duration::from_secs(30)),
                ..MeshPolicy::default()
            },
            MeshPolicy {
                retries: Some(3),
                ..MeshPolicy::default()
            },
            MeshPolicy {
                circuit_breaker: Some(CircuitBreaker {
                    max_failures: 5,
                    window: Duration::from_secs(30),
                }),
                ..MeshPolicy::default()
            },
            MeshPolicy {
                rate_limit: Some(RateLimit {
                    rate: 100,
                    window: Duration::from_secs(1),
                }),
                ..MeshPolicy::default()
            },
            MeshPolicy {
                timeout: Some(Duration::from_secs(30)),
                retries: Some(3),
                mtls_required: Some(true),
                ..MeshPolicy::default()
            },
        ];
        for politicas in fixtures {
            let s = AplicacaoSpec {
                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
                contratos: Vec::new(),
                politicas: politicas.clone(),
                placement: Placement::default(),
                entrada: None,
            };
            assert_eq!(
                *s.politicas(),
                politicas,
                "AplicacaoSpec::politicas must return :politicas verbatim \
                 (got {:?}, expected {:?})",
                s.politicas(),
                politicas,
            );
            assert!(
                std::ptr::eq(s.politicas(), &s.politicas),
                "AplicacaoSpec::politicas accessor and &self.politicas \
                 field access must borrow the same backing storage — \
                 the accessor is the substrate-primitive typed dispatch \
                 every downstream mesh-policy composite consumer must \
                 route through, and a reference-identity split would \
                 silently break every consumer that relied on the \
                 borrow sharing the composite's storage",
            );
            assert_eq!(
                s.politicas().is_empty(),
                s.politicas.is_empty(),
                "AplicacaoSpec::politicas().is_empty() must byte-equal \
                 self.politicas.is_empty() — an emptiness-drift would \
                 silently split the paired `validate_politicas` \
                 per-axis bracket-dispatch's seed from the peer \
                 caixa-mesh CNP mTLS-overlay emitter's key from the \
                 peer caixa-mesh HTTPRoute timeout+retry overlay \
                 emitter's key",
            );
        }
    }

    #[test]
    fn validate_politicas_reads_through_lifted_politicas_accessor() {
        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
        // followed by the per-axis fan-out `p.timeout()` /
        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
        // the lifted axis-level accessor family) must key off the
        // lifted outer accessor, so any future rebrand on the typed
        // slot's outer-composite reader shape lands at exactly one
        // place. Pins the multi-axis coherence by exercising each
        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
        // a `Some(Duration::ZERO)` timeout under the outer accessor's
        // reference projection, (2) `PolicyRetriesZero` fires on a
        // `Some(0)` retries under the same projection, and (3) an
        // empty [`MeshPolicy::default`] passes `validate_politicas` —
        // the outer accessor's reference-projection reaches every
        // per-axis branch without silently short-circuiting any.
        //
        // Peer of the sibling M3
        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
        // three-consumer coherence pin on the per-`:membros` node-list
        // axis and the sibling M3
        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
        // three-consumer coherence pin on the per-`:contratos`
        // edge-list axis — extends the multi-consumer coherence
        // discipline onto the outermost M3 mesh-slot type's per-
        // Aplicacao mesh-policy composite-reference axis, the first
        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
        // type.

        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
        // reference projection: a `Some(Duration::ZERO)` timeout must
        // trip the zero-floor gate. The bracket-dispatch's first arm
        // reads `p.timeout()` on the reference returned by the outer
        // accessor.
        let mut spec = three_member_spec();
        spec.politicas.timeout = Some(Duration::ZERO);
        spec.politicas.retries = None;
        spec.politicas.circuit_breaker = None;
        spec.politicas.rate_limit = None;
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutZero,
        );
        assert!(
            std::ptr::eq(spec.politicas(), &spec.politicas),
            "the `validate_politicas` per-axis bracket-dispatch's \
             traversal input must be the same backing composite the \
             accessor's reference projection borrows from",
        );

        // (2) `PolicyRetriesZero` refusal under the outer accessor's
        // reference projection: a `Some(0)` retries must trip the
        // zero-floor gate. The bracket-dispatch's second arm reads
        // `p.retries()` on the reference returned by the outer accessor.
        let mut spec = three_member_spec();
        spec.politicas.timeout = None;
        spec.politicas.retries = Some(0);
        spec.politicas.circuit_breaker = None;
        spec.politicas.rate_limit = None;
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::PolicyRetriesZero,
        );

        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
        // — every per-axis arm short-circuits on `None`, so the outer
        // accessor's reference projection reaches the fall-through
        // `Ok(())` without any per-axis refusal firing.
        let mut spec = three_member_spec();
        spec.politicas = MeshPolicy::default();
        assert!(
            spec.validate().is_ok(),
            "an empty `MeshPolicy` must pass `validate_politicas` — \
             every per-axis arm short-circuits on `None` under the \
             outer accessor's reference projection",
        );
        assert!(
            spec.politicas().is_empty(),
            "the outer accessor's reference projection must be the \
             empty composite per the `MeshPolicy::default()` fixture",
        );
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
        // must both key off the lifted axis-level accessors
        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
        // the peer `:circuit-breaker` / `:rate-limit` arms already
        // routing through [`MeshPolicy::circuit_breaker`] /
        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
        // per axis on the substrate primitive" shape at the fan-out
        // (four axes, four accessors, no raw-field-access site
        // anywhere on the bracket-dispatch). Pins the per-axis
        // coherence at the accept-set boundaries the bracket carves:
        //   1. accessor byte-equal to raw field on every representative
        //      accept-set value (`None`, sub-cap, at-cap, past-cap
        //      sentinel) — a future accessor drift that no longer
        //      shipped the raw slot verbatim would surface here,
        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
        //      routed through the accessor's projection, proving the
        //      first arm reads through the accessor rather than a
        //      silent-detour peer-axis field access,
        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
        //      through the accessor's projection, proving the second
        //      arm reads through the accessor,
        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
        //      passes validate under the accessor projection (paired
        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
        //      sibling axis), pinning the upper-boundary accept-arm
        //      also routes through the accessor.
        //
        // Peer of the sibling M3
        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
        // outer-composite-reference coherence pin (which asserts the
        // `let p = self.politicas()` seed); extends the discipline onto
        // the per-axis fan-out layer that consumes the seed's
        // reference. Same shape as
        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.

        // (1) Accessor byte-equal to raw field on the `:timeout` axis
        // across the accept-set boundaries the bracket dispatch's
        // three-arm gate carves out
        // ([`crate::render::require_positive_canonical_bounded_duration`]
        // — zero-floor + canonical-form + upper-cap).
        for timeout in [
            None,
            Some(Duration::ZERO),
            Some(Duration::from_millis(1)),
            Some(POLICY_TIMEOUT_MAX),
        ] {
            let p = MeshPolicy {
                timeout,
                ..MeshPolicy::default()
            };
            assert_eq!(
                p.timeout(),
                p.timeout,
                "MeshPolicy::timeout accessor must byte-equal the raw \
                 .timeout field across every accept-set boundary the \
                 validate_politicas :timeout arm carves out — a drift \
                 here would silently split the validate bracket's arm \
                 from the peer caixa-mesh HTTPRoute timeout-overlay \
                 emitter's read",
            );
        }

        // (2) Accessor byte-equal to raw field on the `:retries` axis
        // across the accept-set boundaries the bracket dispatch's
        // two-arm gate carves out
        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
        // + upper-cap).
        for retries in [
            None,
            Some(0u32),
            Some(1u32),
            Some(POLICY_RETRIES_MAX),
            Some(POLICY_RETRIES_MAX + 1),
            Some(u32::MAX),
        ] {
            let p = MeshPolicy {
                retries,
                ..MeshPolicy::default()
            };
            assert_eq!(
                p.retries(),
                p.retries,
                "MeshPolicy::retries accessor must byte-equal the raw \
                 .retries field across every accept-set boundary the \
                 validate_politicas :retries arm carves out — a drift \
                 here would silently split the validate bracket's arm \
                 from the peer caixa-mesh HTTPRoute retry-overlay \
                 emitter's read",
            );
        }

        // (3) `PolicyTimeoutZero` fires on the accessor-projected
        // zero-floor boundary. A silent detour that no longer read
        // through `p.timeout()` (a peer-axis field read, an accidental
        // Option::and-then chain that collapsed the None arm to Some,
        // an accessor rebrand that clamped the return through the
        // upper cap) would fail to refuse here.
        let mut spec = three_member_spec();
        spec.politicas.timeout = Some(Duration::ZERO);
        spec.politicas.retries = None;
        spec.politicas.circuit_breaker = None;
        spec.politicas.rate_limit = None;
        assert_eq!(
            spec.politicas().timeout(),
            Some(Duration::ZERO),
            "the accessor projection must reflect the fixture's \
             `Some(Duration::ZERO)` :timeout verbatim",
        );
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::PolicyTimeoutZero,
            "the validate_politicas :timeout zero-floor arm must fire \
             through the lifted accessor's projection — a silent \
             detour to a peer-axis field would fail to refuse",
        );

        // (4) `PolicyRetriesZero` fires on the accessor-projected
        // zero-floor boundary on the sibling `:retries` axis.
        let mut spec = three_member_spec();
        spec.politicas.timeout = None;
        spec.politicas.retries = Some(0);
        spec.politicas.circuit_breaker = None;
        spec.politicas.rate_limit = None;
        assert_eq!(
            spec.politicas().retries(),
            Some(0),
            "the accessor projection must reflect the fixture's \
             `Some(0)` :retries verbatim",
        );
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::PolicyRetriesZero,
            "the validate_politicas :retries zero-floor arm must fire \
             through the lifted accessor's projection — a silent \
             detour to a peer-axis field would fail to refuse",
        );

        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
        // must pass validate under the accessor projection — pins the
        // upper-boundary accept-arm also routes through the lifted
        // accessor (a drift that clamped or short-circuited at the
        // upper boundary would fail the whole-spec validate here).
        let mut spec = three_member_spec();
        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
        spec.politicas.circuit_breaker = None;
        spec.politicas.rate_limit = None;
        assert_eq!(
            spec.politicas().timeout(),
            Some(POLICY_TIMEOUT_MAX),
            "the accessor projection must reflect the fixture's \
             at-cap :timeout verbatim",
        );
        assert_eq!(
            spec.politicas().retries(),
            Some(POLICY_RETRIES_MAX),
            "the accessor projection must reflect the fixture's \
             at-cap :retries verbatim",
        );
        assert!(
            spec.validate().is_ok(),
            "at-cap :timeout + :retries must pass validate under the \
             accessor projection — the upper-boundary accept-arm on \
             both axes routes through the lifted accessor",
        );
    }

    #[test]
    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
        // The canonical per-`:placement` outer-composite-reference-shape
        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
        // typed `Placement` verbatim as a `&Placement` reference over the
        // same backing storage the raw `&self.placement` field access
        // borrows from, byte-equal across every representative fixture in
        // the accept-set — the default `Placement` (the substrate seed
        // shape whose [`PlacementStrategy::default`] evaluates to
        // `SingleNode` with an empty `:clusters` pool and both
        // optional-scalar axes `None`), and every canonical strategy /
        // cluster-pool / optional-scalar combination the
        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
        // three [`PlacementStrategy`] variants — `SingleNode`,
        // `Replicated`, `Sharded` — cross-projected with a non-empty
        // `:clusters` pool and, on the `Sharded` arm, a non-empty
        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
        // canonical `three_member_spec` `Replicated` fixture's
        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
        //
        // Pins against a future silent detour that returned a fresh-
        // cloned `Placement` copy (which would type-check via a `Clone`
        // impl but silently break every downstream caller that relied on
        // the reference sharing the composite's backing identity), a
        // reference to an operator-resolved overlay (the future per-
        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
        // acknowledges — its resolution must land at exactly this
        // accessor body, not silently divert the raw slot away from a
        // second consumer), or an axis-shuffled projection (a future
        // detour that swapped `clusters` and `affinity` through the
        // accessor would silently split the paired `validate_placement`
        // per-axis bracket-dispatch's traversal input from the peer
        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
        // programs.yaml distribution-annotation emitter's fan-out input
        // from the peer `feira app graph` per-Aplicacao print line's
        // input).
        //
        // Peer of the sibling M3
        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
        // outer mesh-policy composite-reference axis, and of the sibling
        // slice-return `aplicacao_spec_membros_returns_membros_slice_
        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
        // the outer-accessor byte-equal-projection discipline onto the
        // outermost M3 mesh-slot type's per-Aplicacao distribution
        // composite-reference axis, the second `&Composite`-return
        // accessor on the outer [`AplicacaoSpec`] type.
        let fixtures: Vec<Placement> = vec![
            Placement::default(),
            Placement {
                estrategia: PlacementStrategy::SingleNode,
                clusters: vec!["rio".into()],
                affinity: None,
                shard_key: None,
            },
            Placement {
                estrategia: PlacementStrategy::Replicated,
                clusters: vec!["rio".into(), "mar".into()],
                affinity: None,
                shard_key: None,
            },
            Placement {
                estrategia: PlacementStrategy::Replicated,
                clusters: vec!["rio".into(), "mar".into()],
                affinity: Some("data-locality".into()),
                shard_key: None,
            },
            Placement {
                estrategia: PlacementStrategy::Sharded,
                clusters: vec!["rio".into(), "mar".into()],
                affinity: None,
                shard_key: Some("tenantId".into()),
            },
            Placement {
                estrategia: PlacementStrategy::Sharded,
                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
                affinity: Some("low-latency".into()),
                shard_key: Some("metadata.tenantId".into()),
            },
        ];
        for placement in fixtures {
            let s = AplicacaoSpec {
                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
                contratos: Vec::new(),
                politicas: MeshPolicy::default(),
                placement: placement.clone(),
                entrada: None,
            };
            assert_eq!(
                *s.placement(),
                placement,
                "AplicacaoSpec::placement must return :placement verbatim \
                 (got {:?}, expected {:?})",
                s.placement(),
                placement,
            );
            assert!(
                std::ptr::eq(s.placement(), &s.placement),
                "AplicacaoSpec::placement accessor and &self.placement \
                 field access must borrow the same backing storage — the \
                 accessor is the substrate-primitive typed dispatch every \
                 downstream distribution-composite consumer must route \
                 through, and a reference-identity split would silently \
                 break every consumer that relied on the borrow sharing \
                 the composite's storage",
            );
            assert_eq!(
                s.placement().estrategia(),
                s.placement.estrategia,
                "AplicacaoSpec::placement().estrategia() must byte-equal \
                 self.placement.estrategia — a strategy-drift would \
                 silently split the paired `validate_placement` \
                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
                 peer caixa-mesh programs.yaml `placement.estrategia` \
                 emitter's key from the peer `feira app graph` printer's \
                 strategy label",
            );
            assert_eq!(
                s.placement().clusters(),
                s.placement.clusters.as_slice(),
                "AplicacaoSpec::placement().clusters() must byte-equal \
                 self.placement.clusters — a cluster-pool drift would \
                 silently split the paired `validate_placement` \
                 pre-flight `.is_empty()` refusal probe's traversal from \
                 the peer caixa-mesh programs.yaml `placement.clusters` \
                 emitter's fan-out from the peer `feira app graph` \
                 printer's cluster list",
            );
        }
    }

    #[test]
    fn validate_placement_reads_through_lifted_placement_accessor() {
        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
        // per-axis bracket-dispatch seed (`let p = self.placement();`,
        // followed by the per-axis fan-out `p.clusters()` /
        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
        // lifted axis-level accessor family) must key off the lifted
        // outer accessor, so any future rebrand on the typed slot's
        // outer-composite reader shape lands at exactly one place. Pins
        // the multi-axis coherence by exercising each per-axis refusal
        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
        // `:clusters` pool under the outer accessor's reference
        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
        // strategy with a `None` `:shard-key` under the same projection,
        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
        // with a `Some` `:shard-key` under the same projection, and
        // (4) the canonical `three_member_spec` `Replicated` fixture
        // passes `validate_placement` under the outer accessor's
        // reference projection — the accessor's reference-projection
        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
        // without silently short-circuiting any.
        //
        // Peer of the sibling M3
        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
        // (534dc21) multi-axis coherence pin on the per-`:politicas`
        // outer mesh-policy composite-reference axis — extends the
        // multi-consumer coherence discipline onto the outermost M3
        // mesh-slot type's per-Aplicacao distribution composite-
        // reference axis, the second `&Composite`-return accessor on
        // the outer [`AplicacaoSpec`] type.

        // (1) `PlacementWithoutClusters` refusal under the outer
        // accessor's reference projection: an empty `:clusters` pool
        // must trip the pre-flight refusal probe. The bracket-dispatch's
        // first arm reads `p.clusters()` on the reference returned by
        // the outer accessor.
        let mut spec = three_member_spec();
        spec.placement.clusters = Vec::new();
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::PlacementWithoutClusters {
                estrategia: PlacementStrategy::Replicated,
            },
        );
        assert!(
            std::ptr::eq(spec.placement(), &spec.placement),
            "the `validate_placement` per-axis bracket-dispatch's \
             traversal input must be the same backing composite the \
             accessor's reference projection borrows from",
        );

        // (2) `ShardedWithoutKey` refusal under the outer accessor's
        // reference projection: a `Sharded` strategy with a `None`
        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
        // The bracket-dispatch's third arm reads `p.estrategia()` for
        // the match scrutinee then `p.shard_key()` for the cascade
        // scrutinee, both on the reference returned by the outer
        // accessor.
        let mut spec = three_member_spec();
        spec.placement.estrategia = PlacementStrategy::Sharded;
        spec.placement.shard_key = None;
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::ShardedWithoutKey,
        );

        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
        // reference projection: a non-`Sharded` strategy with a `Some`
        // `:shard-key` must trip the declared-but-inert refusal. The
        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
        // + `p.estrategia()` for the diagnostic on the reference
        // returned by the outer accessor.
        let mut spec = three_member_spec();
        spec.placement.estrategia = PlacementStrategy::Replicated;
        spec.placement.shard_key = Some("tenantId".into());
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::ShardKeyOnNonSharded {
                estrategia: PlacementStrategy::Replicated,
                shard_key: "tenantId".into(),
            },
        );

        // (4) Canonical `three_member_spec` `Replicated` fixture passes
        // `validate_placement` — every per-axis arm reaches the fall-
        // through `Ok(())` without any per-axis refusal firing under the
        // outer accessor's reference projection.
        let spec = three_member_spec();
        assert!(
            spec.validate().is_ok(),
            "the canonical Replicated placement fixture must pass \
             `validate_placement` — every per-axis arm short-circuits on \
             valid input under the outer accessor's reference projection",
        );
        assert_eq!(
            spec.placement().estrategia(),
            PlacementStrategy::Replicated,
            "the outer accessor's reference projection must be the \
             canonical Replicated fixture's strategy",
        );
        assert_eq!(
            spec.placement().clusters(),
            &["rio", "mar"],
            "the outer accessor's reference projection must be the \
             canonical Replicated fixture's cluster pool",
        );
    }

    #[test]
    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
        // The canonical per-`:entrada` outer-composite-optional-
        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
        // the `:entrada` typed `Option<Entrada>` verbatim as an
        // `Option<&Entrada>` reference over the same backing storage
        // the raw `self.entrada.as_ref()` field access borrows from,
        // byte-equal across every representative fixture in the
        // accept-set — the author-omitted `None` shape (the
        // "internal-only mesh" partition every downstream external-
        // gateway emitter treats as "emit nothing"), the minimal
        // singleton `:entrada` composite (host + destination + empty
        // paths + default port), the paths-carrying composite (the
        // canonical `three_member_spec` fixture's ["/api" "/health"]
        // path-list shape every HTTPRoute per-rule fan-out emitter
        // reads), and the non-default port composite (the canonical
        // custom-port shape the port-fallback resolver reads).
        //
        // Pins against a future silent detour that returned a fresh-
        // cloned `Entrada` copy (which would type-check via a `Clone`
        // impl but silently break every downstream caller that
        // relied on the reference sharing the composite's backing
        // identity), a reference to an operator-resolved overlay
        // (the future per-cluster `:entrada-overrides` slot the
        // MESH-COMPOSITION §V federation roadmap acknowledges — its
        // resolution must land at exactly this accessor body, not
        // silently divert the raw slot away from a second consumer),
        // a `None` → `Some(Entrada::default)` cluster-default
        // projection (which would collapse the load-bearing
        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
        // the peer `gateway_routes` early-return + `feira app graph`
        // internal-only-mesh partition both read), or an axis-
        // shuffled projection (a future detour that swapped
        // `host` and `para` through the accessor would silently
        // split the paired `validate` per-`:entrada` shape-and-
        // membership gate's traversal input from the peer
        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
        // fan-out input from the peer `feira app graph` external-
        // gateway summary line).
        //
        // Peer of the sibling M3
        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
        // `:politicas` outer mesh-policy composite-reference axis
        // and of the sibling M3
        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
        // (9abb8f0) `&Placement` byte-equal pin on the per-
        // `:placement` outer distribution-composite composite-
        // reference axis — extends the outer-accessor byte-equal-
        // projection discipline onto the last unlifted outermost M3
        // mesh-slot type's per-Aplicacao external-gateway composite-
        // reference axis, the third and final `&Composite`-return
        // accessor on the outer [`AplicacaoSpec`] type.
        let fixtures: Vec<Option<Entrada>> = vec![
            None,
            Some(Entrada {
                host: "checkout.quero.cloud".into(),
                para: "cart".into(),
                paths: Vec::new(),
                port: DEFAULT_SERVICO_PORT,
            }),
            Some(Entrada {
                host: "checkout.quero.cloud".into(),
                para: "cart".into(),
                paths: vec!["/api".into(), "/health".into()],
                port: DEFAULT_SERVICO_PORT,
            }),
            Some(Entrada {
                host: "checkout.quero.cloud".into(),
                para: "cart".into(),
                paths: vec!["/api".into()],
                port: 9443,
            }),
        ];
        for entrada in fixtures {
            let s = AplicacaoSpec {
                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
                contratos: Vec::new(),
                politicas: MeshPolicy::default(),
                placement: Placement::default(),
                entrada: entrada.clone(),
            };
            assert_eq!(
                s.entrada(),
                entrada.as_ref(),
                "AplicacaoSpec::entrada must return :entrada verbatim \
                 (got {:?}, expected {:?})",
                s.entrada(),
                entrada.as_ref(),
            );
            match (s.entrada(), s.entrada.as_ref()) {
                (Some(a), Some(b)) => assert!(
                    std::ptr::eq(a, b),
                    "AplicacaoSpec::entrada accessor and \
                     self.entrada.as_ref() field access must borrow \
                     the same backing storage — the accessor is the \
                     substrate-primitive typed dispatch every \
                     downstream external-gateway composite consumer \
                     must route through, and a reference-identity \
                     split would silently break every consumer that \
                     relied on the borrow sharing the composite's \
                     storage",
                ),
                (None, None) => {}
                _ => panic!(
                    "AplicacaoSpec::entrada presence bit must byte-\
                     equal self.entrada.is_some() — a presence-bit \
                     drift would silently split the paired `validate` \
                     per-`:entrada` shape-and-membership gate's \
                     traversal head from the peer \
                     caixa-mesh gateway_routes early-return partition \
                     from the peer `feira app graph` internal-only-\
                     mesh partition",
                ),
            }
            assert_eq!(
                s.entrada().is_some(),
                s.entrada.is_some(),
                "AplicacaoSpec::entrada().is_some() must byte-equal \
                 self.entrada.is_some() — a presence-bit drift would \
                 silently split every downstream `Option<&Entrada>` \
                 consumer's partition on the internal-only-mesh arm",
            );
        }
    }

    #[test]
    fn validate_reads_through_lifted_entrada_accessor() {
        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
        // self.entrada() { … }`, followed by the per-axis fan-out
        // `validate_entrada_para(&e.para)` /
        // `EntradaMemberMissing` membership lookup /
        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
        // per-`e.paths` `validate_entrada_path` traversal) must key
        // off the lifted outer accessor, so any future rebrand on
        // the typed slot's outer-composite reader shape lands at
        // exactly one place. Pins the multi-axis coherence by
        // exercising each per-axis refusal end-to-end: (1) the
        // author-omitted `None` shape short-circuits past every
        // per-`:entrada` refusal (the internal-only mesh partition
        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
        // fires on a well-shaped but phantom `:para` under the outer
        // accessor's reference projection, and (3) the canonical
        // `three_member_spec` `:entrada` fixture passes `validate`
        // under the outer accessor's reference projection.
        //
        // Peer of the sibling M3
        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
        // (534dc21) multi-axis coherence pin on the per-`:politicas`
        // outer mesh-policy composite-reference axis and the sibling
        // M3
        // [`validate_placement_reads_through_lifted_placement_accessor`]
        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
        // outer distribution-composite composite-reference axis —
        // extends the multi-consumer coherence discipline onto the
        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
        // external-gateway composite-reference axis, the third and
        // final `&Composite`-return accessor on the outer
        // [`AplicacaoSpec`] type.

        // (1) `None` :entrada — the internal-only-mesh partition
        // short-circuits past every per-`:entrada` refusal. The outer
        // accessor's reference projection reaches the fall-through
        // `Ok(())` on the `None` arm without any per-axis refusal
        // firing.
        let mut spec = three_member_spec();
        spec.entrada = None;
        assert!(
            spec.validate().is_ok(),
            "an author-omitted `:entrada` must pass `validate` — the \
             internal-only-mesh partition short-circuits past every \
             per-`:entrada` refusal under the outer accessor's \
             reference projection",
        );
        assert!(
            spec.entrada().is_none(),
            "the outer accessor's reference projection must name the \
             internal-only-mesh partition per the `None` fixture",
        );

        // (2) `EntradaMemberMissing` refusal under the outer accessor's
        // reference projection: a well-shaped but phantom `:para` must
        // trip the membership-lookup refusal. The gate's second arm
        // reads `e.para` on the reference returned by the outer
        // accessor.
        let mut spec = three_member_spec();
        if let Some(e) = spec.entrada.as_mut() {
            e.para = "phantom".into();
        }
        assert_eq!(
            spec.validate().unwrap_err(),
            AplicacaoError::EntradaMemberMissing {
                para: "phantom".into(),
            },
        );
        match (spec.entrada(), spec.entrada.as_ref()) {
            (Some(a), Some(b)) => assert!(
                std::ptr::eq(a, b),
                "the `validate` per-`:entrada` gate's traversal head \
                 must be the same backing composite the accessor's \
                 reference projection borrows from",
            ),
            _ => panic!("fixture must carry Some(:entrada)"),
        }

        // (3) Canonical `three_member_spec` `:entrada` fixture passes
        // `validate` — every per-axis arm reaches the fall-through
        // `Ok(())` without any per-axis refusal firing under the
        // outer accessor's reference projection.
        let spec = three_member_spec();
        assert!(
            spec.validate().is_ok(),
            "the canonical `:entrada` fixture must pass `validate` — \
             every per-axis arm short-circuits on valid input under \
             the outer accessor's reference projection",
        );
        assert!(
            spec.entrada().is_some(),
            "the outer accessor's reference projection must be the \
             canonical `:entrada` fixture's composite",
        );
    }

    #[test]
    fn port_for_destination_reads_through_lifted_entrada_accessor() {
        // Peer coherence pin: the
        // [`AplicacaoSpec::port_for_destination`] per-destination
        // L4-port fallback resolver's composite-projection seed
        // (`self.entrada().filter(…).map_or(…)`) must key off the
        // lifted outer accessor. Pins the coherence by exercising
        // the resolver end-to-end: (1) the `None` `:entrada` shape
        // falls through to `DEFAULT_SERVICO_PORT` under the outer
        // accessor's reference projection, (2) a non-matching
        // destination falls through to `DEFAULT_SERVICO_PORT` under
        // the outer accessor's reference projection, and (3) the
        // matching destination resolves to the `:entrada :port`
        // value under the outer accessor's reference projection.
        //
        // Peer of the sibling
        // [`validate_reads_through_lifted_entrada_accessor`] multi-
        // consumer coherence pin on the same per-`:entrada` outer-
        // composite axis — extends the multi-consumer coherence
        // discipline onto the second per-`:entrada` production
        // consumer, the L4-port fallback resolver.

        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
        // arm under the outer accessor's reference projection.
        let mut spec = three_member_spec();
        spec.entrada = None;
        assert_eq!(
            spec.port_for_destination("cart"),
            DEFAULT_SERVICO_PORT,
            "the port-fallback resolver must fall through to \
             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
             under the outer accessor's reference projection",
        );

        // (2) Non-matching destination — the resolver's `filter(…)`
        // arm rejects a mismatched destination and falls through
        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
        // reference projection.
        let mut spec = three_member_spec();
        if let Some(e) = spec.entrada.as_mut() {
            e.para = "cart".into();
            e.port = 9443;
        }
        assert_eq!(
            spec.port_for_destination("catalog"),
            DEFAULT_SERVICO_PORT,
            "the port-fallback resolver must fall through to \
             DEFAULT_SERVICO_PORT on a non-matching destination \
             under the outer accessor's reference projection",
        );

        // (3) Matching destination — the resolver's `map_or(…)` arm
        // returns the `:entrada :port` value under the outer
        // accessor's reference projection.
        let mut spec = three_member_spec();
        if let Some(e) = spec.entrada.as_mut() {
            e.para = "cart".into();
            e.port = 9443;
        }
        assert_eq!(
            spec.port_for_destination("cart"),
            9443,
            "the port-fallback resolver must return the \
             `:entrada :port` value on a matching destination \
             under the outer accessor's reference projection",
        );
    }

    #[test]
    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
        // The canonical per-`:politicas` `:mtls-required` mTLS-
        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
        // must return the `:politicas :mtls-required` typed bool
        // verbatim as an `Option<bool>`, byte-equal to the raw field
        // access across every value in the three-way accept-set —
        // `None` (cluster default applies), `Some(true)` (mTLS
        // handshake enforced — the sandboxing-by-default arm the
        // MeshPolicy's docstring names), `Some(false)` (handshake
        // skipped — the explicit debug-edge opt-out).
        //
        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
        // shape — first `Option<Copy-T>`-return accessor on the M3
        // mesh-slot family. Pins against a future silent detour that
        // re-derived the toggle from a peer axis (an accidental
        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
        // whenever a breaker is set), a `None` → `Some(false)` cluster-
        // default projection (the canonical `Option<bool>` → `bool`
        // collapse footgun the surrounding `is_empty()` predicate
        // guards on the peer emptiness axis), or a `Some(true)` /
        // `Some(false)` variant swap that landed on one consumer
        // without the other.
        for required in [None, Some(true), Some(false)] {
            let p = MeshPolicy {
                mtls_required: required,
                ..MeshPolicy::default()
            };
            assert_eq!(
                p.mtls_required(),
                required,
                "MeshPolicy::mtls_required must return :politicas \
                 :mtls-required verbatim (got {:?}, expected {required:?})",
                p.mtls_required(),
            );
            assert_eq!(
                p.mtls_required(),
                p.mtls_required,
                "MeshPolicy::mtls_required must byte-equal the raw \
                 .mtls_required field access across every value in the \
                 three-way accept-set",
            );
        }
    }

    #[test]
    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
        // arm must key off [`MeshPolicy::mtls_required`], not the raw
        // `.mtls_required` field access. Structurally: toggling ONLY
        // the `mtls_required` slot on an otherwise-default MeshPolicy
        // must flip `is_empty()` from `true` (all-`None`) to `false`
        // (one axis carries a value); the flip must be observed for
        // both `Some(true)` and `Some(false)` since the emptiness
        // semantic reads "any axis carries a value" — not "any axis
        // carries a truthy value" — the same non-collapsing shape the
        // sibling M2 [`crate::LimitsSpec::is_empty`] /
        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
        // peer `Option<T>`-typed slot surfaces.
        //
        // Pins against a future silent detour that re-derived the
        // emptiness predicate off a peer axis (an accidental
        // `.rate_limit.is_none()`-only chain that dropped the
        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
        // collapse to a truthy-only check (which would silently
        // classify `Some(false)` as empty), or an accessor-side
        // detour that no longer names the substrate-primitive typed
        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
        // == false` fallback in the accessor that would silently
        // classify both `None` and `Some(false)` as the same value).
        //
        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
        // (7cd2a28) accessor-composition pin on the sibling optional-
        // scalar axis — same "the emptiness / shape-gate predicate
        // must route through the substrate-primitive typed dispatch"
        // discipline extended onto the peer per-`:politicas` emptiness
        // predicate.
        let empty = MeshPolicy::default();
        assert!(
            empty.is_empty(),
            "MeshPolicy::default() must be is_empty() — every axis \
             defaults to None",
        );
        for required in [Some(true), Some(false)] {
            let p = MeshPolicy {
                mtls_required: required,
                ..MeshPolicy::default()
            };
            assert!(
                !p.is_empty(),
                "MeshPolicy::is_empty must return false when \
                 :mtls-required is {required:?} — the emptiness \
                 predicate reads \"any axis carries a value\", not \
                 \"any axis carries a truthy value\"",
            );
            assert_eq!(
                p.mtls_required().is_none(),
                p.is_empty(),
                "when :mtls-required is the only set axis, \
                 is_empty() must equal mtls_required().is_none() — \
                 the accessor and the emptiness predicate must \
                 route through the same substrate-primitive typed \
                 dispatch on the :mtls-required arm",
            );
        }
    }

    #[test]
    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
        // accessor must return by value, not by reference. Peer of the
        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
        // borrow-invariant pin on the sibling `Option<String>` slot,
        // but extended onto the peer `Option<bool>` copy-invariant
        // shape — the accessor's returned `Option<bool>` must outlive
        // `&self` (multiple calls must return equal values from a
        // dropped-`&self` copy, since the returned Option carries no
        // borrow), and calling the accessor twice on the same
        // MeshPolicy must yield the same `Option<bool>` verbatim
        // (idempotent, no side effects on `&self`).
        //
        // Pins against a future silent detour that returned
        // `Option<&bool>` (which would type-check but silently break
        // every downstream caller — [`single_field_overlay`]'s first
        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
        // detached copy at the call site), an accidental
        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
        // would also type-check but return `Option<&bool>`), or a
        // one-arm-only accessor that reads `Some(*b)` in the Some arm
        // but reads a fresh Default::default() in the None arm.
        for required in [None, Some(true), Some(false)] {
            let p = MeshPolicy {
                mtls_required: required,
                ..MeshPolicy::default()
            };
            let first = p.mtls_required();
            let second = p.mtls_required();
            assert_eq!(
                first, second,
                "MeshPolicy::mtls_required must be idempotent — two \
                 successive calls on the same &self must return the \
                 same Option<bool>",
            );
            assert_eq!(
                first, required,
                "MeshPolicy::mtls_required must return :politicas \
                 :mtls-required verbatim by copy — got {first:?}, \
                 expected {required:?}",
            );
        }
    }

    #[test]
    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
        // The canonical per-`:politicas` `:retries` transient-failure-
        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
        // the `:politicas :retries` typed `u32` verbatim as an
        // `Option<u32>`, byte-equal to the raw field access across every
        // representative value in the accept-set — `None` (cluster
        // default applies — typically "no retries beyond a single
        // dispatch attempt" the caixa-mesh `retry_overlay` builder
        // documents), `Some(1)` (the lower boundary of the
        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
        // `AplicacaoSpec::validate_politicas` gate carves out on the
        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
        // (the upper boundary the same gate carves out on the sibling
        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
        // past-the-guard sentinel that pins the accessor doesn't perform
        // a silent bounds-collapse at the return path).
        //
        // Sibling of the peer per-`:politicas`
        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
        // peer per-`:politicas` `Option<u32>` shape — second
        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
        // Pins against a future silent detour that re-derived the retry
        // cap from a peer axis (an accidental `.circuit_breaker
        // .as_ref().map(|b| b.max_failures)` collapse that read the
        // breaker's max-failure count as a retry budget), a
        // `None → Some(0)` cluster-default projection (which would
        // silently re-introduce the `PolicyRetriesZero` refusal case at
        // the emit boundary), or a bounds-collapsing accessor that
        // clamped the return through `POLICY_RETRIES_MAX` (the
        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
        // must ship the raw slot verbatim so a validate-time gate
        // regression surfaces at the emit boundary rather than being
        // silently absorbed).
        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
            let p = MeshPolicy {
                retries,
                ..MeshPolicy::default()
            };
            assert_eq!(
                p.retries(),
                retries,
                "MeshPolicy::retries must return :politicas :retries \
                 verbatim (got {:?}, expected {retries:?})",
                p.retries(),
            );
            assert_eq!(
                p.retries(),
                p.retries,
                "MeshPolicy::retries must byte-equal the raw .retries \
                 field access across every value in the accept-set",
            );
        }
    }

    #[test]
    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
        // must key off [`MeshPolicy::retries`], not the raw `.retries`
        // field access. Structurally: toggling ONLY the `retries` slot
        // on an otherwise-default MeshPolicy must flip `is_empty()`
        // from `true` (all-`None`) to `false` (one axis carries a
        // value); the flip must be observed for every value in the
        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
        // the emptiness semantic reads "any axis carries a value" —
        // not "any axis carries a value the validate gate accepts" —
        // the same non-collapsing shape the peer M2
        // [`crate::LimitsSpec::is_empty`] /
        // [`crate::BehaviorSpec::is_empty`] predicates carry.
        //
        // Pins against a future silent detour that re-derived the
        // emptiness predicate off a peer axis (an accidental
        // `.rate_limit.is_none()`-only chain that dropped the
        // `retries` arm entirely), a `retries == Some(_)` collapse
        // that key-off a validate-gate-clamped bounds check (which
        // would silently classify a past-the-guard `Some(u32::MAX)`
        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
        // check), or an accessor-side detour that no longer names the
        // substrate-primitive typed dispatch.
        //
        // Sibling of the peer per-`:politicas`
        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
        // same "the emptiness predicate must route through the
        // substrate-primitive typed dispatch" discipline extended onto
        // the peer per-`:politicas` `Option<u32>` axis.
        let empty = MeshPolicy::default();
        assert!(
            empty.is_empty(),
            "MeshPolicy::default() must be is_empty() — every axis \
             defaults to None",
        );
        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
            let p = MeshPolicy {
                retries,
                ..MeshPolicy::default()
            };
            assert!(
                !p.is_empty(),
                "MeshPolicy::is_empty must return false when \
                 :retries is {retries:?} — the emptiness \
                 predicate reads \"any axis carries a value\", not \
                 \"any axis carries a value the validate gate \
                 accepts\"",
            );
            assert_eq!(
                p.retries().is_none(),
                p.is_empty(),
                "when :retries is the only set axis, is_empty() \
                 must equal retries().is_none() — the accessor and \
                 the emptiness predicate must route through the same \
                 substrate-primitive typed dispatch on the :retries \
                 arm",
            );
        }
    }

    #[test]
    fn mesh_policy_retries_projects_option_u32_by_copy() {
        // The by-copy pin: [`MeshPolicy::retries`] returns
        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
        // accessor must return by value, not by reference. Sibling of
        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
        // extended onto the sibling `Option<u32>` copy-invariant
        // shape — the accessor's returned `Option<u32>` must outlive
        // `&self` (multiple calls must return equal values from a
        // dropped-`&self` copy, since the returned Option carries no
        // borrow), and calling the accessor twice on the same
        // MeshPolicy must yield the same `Option<u32>` verbatim
        // (idempotent, no side effects on `&self`).
        //
        // Pins against a future silent detour that returned
        // `Option<&u32>` (which would type-check but silently break
        // every downstream caller — [`crate::render::single_field_overlay`]'s
        // first parameter is `Option<T: Clone>`, and `&u32` would
        // fold to a detached copy at the call site), an accidental
        // `Option::as_ref()` projection (`self.retries.as_ref()` would
        // also type-check but return `Option<&u32>`), or a one-arm-
        // only accessor that reads `Some(*n)` in the Some arm but
        // reads a fresh `Default::default()` (`0_u32`) in the None
        // arm.
        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
            let p = MeshPolicy {
                retries,
                ..MeshPolicy::default()
            };
            let first = p.retries();
            let second = p.retries();
            assert_eq!(
                first, second,
                "MeshPolicy::retries must be idempotent — two \
                 successive calls on the same &self must return the \
                 same Option<u32>",
            );
            assert_eq!(
                first, retries,
                "MeshPolicy::retries must return :politicas :retries \
                 verbatim by copy — got {first:?}, expected {retries:?}",
            );
        }
    }

    #[test]
    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
        // return the `:politicas :timeout` typed [`Duration`] verbatim
        // as an `Option<Duration>`, byte-equal to the raw field access
        // across every representative value in the accept-set — `None`
        // (cluster default applies — typically the gateway class's
        // implementation-side per-request wall-clock cap the caixa-mesh
        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
        // set the surrounding `AplicacaoSpec::validate_politicas` gate
        // carves out on the sibling `PolicyTimeoutZero` /
        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
        // (the upper boundary the same gate carves out on the sibling
        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
        // (a past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse into `None` on the zero-
        // Duration arm — validate rejects zero but the accessor must
        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
        // past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse at the return path).
        //
        // Sibling of the peer per-`:politicas`
        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
        // `Option<u32>` optional-scalar axis and the peer per-
        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
        // pin on the sibling `Option<bool>` optional-scalar axis,
        // extended onto the peer per-`:politicas` `Option<Duration>`
        // shape — third `Option<Copy-T>`-return accessor on the M3
        // mesh-slot family. Pins against a future silent detour that
        // re-derived the per-call cap from a peer axis (an accidental
        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
        // read the breaker's rolling-window duration as a per-call
        // deadline), a `None → Some(Duration::MAX)` cluster-default
        // projection (which would silently re-introduce the
        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
        // blocking" arm at the emit boundary), or a bounds-collapsing
        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
        // (the `AplicacaoSpec::validate` gate owns the bounds; the
        // accessor must ship the raw slot verbatim so a validate-time
        // gate regression surfaces at the emit boundary rather than
        // being silently absorbed).
        for timeout in [
            None,
            Some(Duration::from_millis(1)),
            Some(POLICY_TIMEOUT_MAX),
            Some(Duration::ZERO),
            Some(Duration::MAX),
        ] {
            let p = MeshPolicy {
                timeout,
                ..MeshPolicy::default()
            };
            assert_eq!(
                p.timeout(),
                timeout,
                "MeshPolicy::timeout must return :politicas :timeout \
                 verbatim (got {:?}, expected {timeout:?})",
                p.timeout(),
            );
            assert_eq!(
                p.timeout(),
                p.timeout,
                "MeshPolicy::timeout must byte-equal the raw .timeout \
                 field access across every value in the accept-set",
            );
        }
    }

    #[test]
    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
        // field access. Structurally: toggling ONLY the `timeout` slot
        // on an otherwise-default MeshPolicy must flip `is_empty()`
        // from `true` (all-`None`) to `false` (one axis carries a
        // value); the flip must be observed for every value in the
        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
        // gate accepts (`Some(Duration::from_millis(1))`,
        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
        // reads "any axis carries a value" — not "any axis carries a
        // value the validate gate accepts" — the same non-collapsing
        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
        // [`crate::BehaviorSpec::is_empty`] predicates carry.
        //
        // Pins against a future silent detour that re-derived the
        // emptiness predicate off a peer axis (an accidental
        // `.rate_limit.is_none()`-only chain that dropped the
        // `timeout` arm entirely), a `timeout == Some(_)` collapse
        // that key-off a validate-gate-clamped bounds check (which
        // would silently classify a past-the-guard `Some(Duration::MAX)`
        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
        // check), or an accessor-side detour that no longer names the
        // substrate-primitive typed dispatch.
        //
        // Sibling of the peer per-`:politicas`
        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
        // the sibling `Option<u32>` optional-scalar axis and the peer
        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
        // accessor-composition pin on the sibling `Option<bool>`
        // optional-scalar axis — same "the emptiness predicate must
        // route through the substrate-primitive typed dispatch"
        // discipline extended onto the peer per-`:politicas`
        // `Option<Duration>` axis.
        let empty = MeshPolicy::default();
        assert!(
            empty.is_empty(),
            "MeshPolicy::default() must be is_empty() — every axis \
             defaults to None",
        );
        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
            let p = MeshPolicy {
                timeout,
                ..MeshPolicy::default()
            };
            assert!(
                !p.is_empty(),
                "MeshPolicy::is_empty must return false when \
                 :timeout is {timeout:?} — the emptiness \
                 predicate reads \"any axis carries a value\", not \
                 \"any axis carries a value the validate gate \
                 accepts\"",
            );
            assert_eq!(
                p.timeout().is_none(),
                p.is_empty(),
                "when :timeout is the only set axis, is_empty() \
                 must equal timeout().is_none() — the accessor and \
                 the emptiness predicate must route through the same \
                 substrate-primitive typed dispatch on the :timeout \
                 arm",
            );
        }
    }

    #[test]
    fn mesh_policy_timeout_projects_option_duration_by_copy() {
        // The by-copy pin: [`MeshPolicy::timeout`] returns
        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
        // and the accessor must return by value, not by reference.
        // Sibling of the peer per-`:politicas`
        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
        // sibling `Option<u32>` optional-scalar axis and the peer
        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
        // by-copy pin on the sibling `Option<bool>` optional-scalar
        // axis, extended onto the peer per-`:politicas`
        // `Option<Duration>` copy-invariant shape — the accessor's
        // returned `Option<Duration>` must outlive `&self` (multiple
        // calls must return equal values from a dropped-`&self`
        // copy, since the returned Option carries no borrow), and
        // calling the accessor twice on the same MeshPolicy must
        // yield the same `Option<Duration>` verbatim (idempotent, no
        // side effects on `&self`).
        //
        // Pins against a future silent detour that returned
        // `Option<&Duration>` (which would type-check but silently
        // break every downstream caller — [`crate::render::single_field_overlay`]'s
        // first parameter is `Option<T: Clone>`, and `&Duration`
        // would fold to a detached copy at the call site), an
        // accidental `Option::as_ref()` projection
        // (`self.timeout.as_ref()` would also type-check but return
        // `Option<&Duration>`), or a one-arm-only accessor that
        // reads `Some(*d)` in the Some arm but reads a fresh
        // `Default::default()` (`Duration::ZERO`) in the None arm
        // (which would silently re-classify every unset `:timeout`
        // as the `PolicyTimeoutZero`-refused zero-Duration value at
        // the accessor boundary).
        for timeout in [
            None,
            Some(Duration::from_millis(1)),
            Some(POLICY_TIMEOUT_MAX),
            Some(Duration::ZERO),
            Some(Duration::MAX),
        ] {
            let p = MeshPolicy {
                timeout,
                ..MeshPolicy::default()
            };
            let first = p.timeout();
            let second = p.timeout();
            assert_eq!(
                first, second,
                "MeshPolicy::timeout must be idempotent — two \
                 successive calls on the same &self must return the \
                 same Option<Duration>",
            );
            assert_eq!(
                first, timeout,
                "MeshPolicy::timeout must return :politicas :timeout \
                 verbatim by copy — got {first:?}, expected {timeout:?}",
            );
        }
    }

    #[test]
    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
        // The canonical per-`:politicas` `:rate-limit` Envoy-
        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
        // [`MeshPolicy::rate_limit`] must return the `:politicas
        // :rate-limit` typed [`RateLimit`] verbatim as an
        // `Option<RateLimit>`, byte-equal to the raw field access
        // across every representative value in the accept-set — `None`
        // (cluster default applies — no per-Aplicacao rate declaration,
        // the gateway-class per-listener default arm the future caixa-
        // mesh `local_rate_limit_overlay` emitter documents),
        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
        // accept-set the surrounding
        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
        // sibling `PolicyRateLimitZero` refusal, paired with the
        // canonical-window "1 second" arm of the three-unit
        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
        // (the upper boundary the same gate carves out on the sibling
        // `PolicyRateLimitExceedsCap` refusal, paired with the
        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
        // (a past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse into `None` on the
        // zero-rate/zero-window arm — validate rejects zero but the
        // accessor must ship the raw slot verbatim so a validate-time
        // gate regression surfaces at the emit boundary rather than
        // being silently absorbed), and
        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
        // (a past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse at the return path).
        //
        // First `Option<Copy-composite-T>`-return accessor pin on the
        // M3 mesh-slot family (peer of the sibling per-`:politicas`
        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
        // Copy accessor pins, extended onto the peer per-`:politicas`
        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
        // and the accessor returns by value). Pins against a future
        // silent detour that re-derived the rate declaration from a
        // peer axis (an accidental
        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
        // collapse that read the breaker's trip threshold + rolling
        // window as a rate declaration), a `None → Some(default())`
        // cluster-default projection (which would silently re-
        // introduce a "cluster default is 0/s" arm the emit boundary
        // would take as "declared but inert" — the canonical
        // declared-but-inert footgun the sibling
        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
        // amplification-shape axis), a bounds-collapsing accessor
        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
        // accessor must ship the raw slot verbatim), or a
        // by-reference detour (`Option<&RateLimit>`) that broke every
        // downstream consumer keying off `Option<RateLimit>` by-copy.
        for rl in [
            None,
            Some(RateLimit {
                rate: 1,
                window: Duration::from_secs(1),
            }),
            Some(RateLimit {
                rate: POLICY_RATE_LIMIT_MAX,
                window: Duration::from_secs(3600),
            }),
            Some(RateLimit {
                rate: 0,
                window: Duration::ZERO,
            }),
            Some(RateLimit {
                rate: u32::MAX,
                window: Duration::MAX,
            }),
        ] {
            let p = MeshPolicy {
                rate_limit: rl,
                ..MeshPolicy::default()
            };
            assert_eq!(
                p.rate_limit(),
                rl,
                "MeshPolicy::rate_limit must return :politicas :rate-limit \
                 verbatim (got {:?}, expected {rl:?})",
                p.rate_limit(),
            );
            assert_eq!(
                p.rate_limit(),
                p.rate_limit,
                "MeshPolicy::rate_limit must byte-equal the raw \
                 .rate_limit field access across every value in the \
                 accept-set",
            );
        }
    }

    #[test]
    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
        // must key off [`MeshPolicy::rate_limit`], not the raw
        // `.rate_limit` field access. Structurally: toggling ONLY the
        // `rate_limit` slot on an otherwise-default MeshPolicy must
        // flip `is_empty()` from `true` (all-`None`) to `false` (one
        // axis carries a value); the flip must be observed for every
        // representative value in the accept-set the surrounding
        // [`AplicacaoSpec::validate_politicas`] gate accepts
        // (`Some(RateLimit { rate: 1, window: 1s })`,
        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
        // since the emptiness semantic reads "any axis carries a
        // value" — not "any axis carries a value the validate gate
        // accepts" — the same non-collapsing shape the peer M2
        // [`crate::LimitsSpec::is_empty`] /
        // [`crate::BehaviorSpec::is_empty`] predicates carry.
        //
        // Pins against a future silent detour that re-derived the
        // emptiness predicate off a peer axis (an accidental
        // `.timeout.is_none()`-only chain that dropped the
        // `rate_limit` arm entirely — the last unlifted inline field
        // access on `is_empty` before this lift), a `rate_limit ==
        // Some(_)` collapse that key-off a validate-gate-clamped
        // bounds check (which would silently classify a past-the-
        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
        // because it fails the value-shape gate), or an accessor-
        // side detour that no longer names the substrate-primitive
        // typed dispatch.
        //
        // Fourth "the emptiness predicate must route through the
        // substrate-primitive typed dispatch" composition pin on the
        // M3 mesh-slot family — closes the last unlifted composition
        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
        // 7073d0f is_empty-composition pins on the sibling primitive-
        // Copy axes, extended onto the peer per-`:politicas`
        // composite-Copy `Option<RateLimit>` axis).
        let empty = MeshPolicy::default();
        assert!(
            empty.is_empty(),
            "MeshPolicy::default() must be is_empty() — every axis \
             defaults to None",
        );
        for rl in [
            RateLimit {
                rate: 1,
                window: Duration::from_secs(1),
            },
            RateLimit {
                rate: POLICY_RATE_LIMIT_MAX,
                window: Duration::from_secs(3600),
            },
        ] {
            let p = MeshPolicy {
                rate_limit: Some(rl),
                ..MeshPolicy::default()
            };
            assert!(
                !p.is_empty(),
                "MeshPolicy::is_empty must return false when \
                 :rate-limit is {rl:?} — the emptiness predicate \
                 reads \"any axis carries a value\", not \"any axis \
                 carries a value the validate gate accepts\"",
            );
            assert_eq!(
                p.rate_limit().is_none(),
                p.is_empty(),
                "when :rate-limit is the only set axis, is_empty() \
                 must equal rate_limit().is_none() — the accessor \
                 and the emptiness predicate must route through the \
                 same substrate-primitive typed dispatch on the \
                 :rate-limit arm",
            );
        }
    }

    #[test]
    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
        // `:rate-limit` value-shape gate must key off
        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
        // field bind. Structurally: a `MeshPolicy` whose only set
        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
        // the `PolicyRateLimitZero` refusal exactly, and the same
        // MeshPolicy with the rate at the canonical lower boundary
        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
        // The pair jointly pins the accessor + validate-gate
        // composition: any future silent detour that had the accessor
        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
        // silently absorb the `PolicyRateLimitZero` refusal at the
        // accessor boundary — the composition pin catches that at
        // caixa-core build time.
        //
        // Sibling of the peer [`validate_politicas`]
        // `:mtls-required` / `:retries` / `:timeout` composition pins
        // on the sibling primitive-Copy optional-scalar axes — same
        // "the validate / shape-gate predicate must route through the
        // substrate-primitive typed dispatch" discipline extended
        // onto the peer per-`:politicas` composite-Copy
        // `Option<RateLimit>` axis. Second composition-with-accessor
        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
        let mut spec = three_member_spec();
        spec.politicas = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 0,
                window: Duration::from_secs(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
            "validate_politicas must reject rate == 0 with \
             PolicyRateLimitZero — the accessor and the validate gate \
             must route through the same substrate-primitive typed \
             dispatch on the :rate-limit zero-floor arm",
        );
        spec.politicas = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 1,
                window: Duration::from_secs(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            spec.validate().is_ok(),
            "validate_politicas must accept rate == 1 (the canonical \
             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
             set) with a canonical 1s window",
        );
    }

    #[test]
    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
        // `outlier_detection`-mesh consecutive-failure-ejection scalar
        // pin: [`MeshPolicy::circuit_breaker`] must return the
        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
        // raw field access across every representative value in the
        // accept-set — `None` (cluster default applies — no
        // per-Aplicacao breaker declaration, the gateway-class per-
        // listener default arm the future caixa-mesh
        // `outlier_detection_overlay` emitter documents),
        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
        // (the lower boundary of the accept-set the surrounding
        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
        // refusals),
        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
        // (the upper boundary the same gate carves out on the sibling
        // `PolicyBreakerMaxFailuresExceedsCap` /
        // `PolicyBreakerWindowExceedsCap` refusals),
        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
        // (a past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse into `None` on the
        // zero-failures/zero-window arm — validate rejects zero but
        // the accessor must ship the raw slot verbatim so a validate-
        // time gate regression surfaces at the emit boundary rather
        // than being silently absorbed), and
        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
        // (a past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse at the return path).
        //
        // Second `Option<Copy-composite-T>`-return accessor pin on the
        // M3 mesh-slot family (peer of the sibling per-`:politicas`
        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
        // composite-Copy accessor pin, and of the sibling per-
        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
        // [`MeshPolicy::retries`] bdfb399 /
        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
        // accessor pins). Pins against a future silent detour that
        // re-derived the breaker declaration from a peer axis (an
        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
        // collapse that read the rate-limit's bucket capacity + refill
        // period as a breaker declaration), a `None → Some(default())`
        // cluster-default projection (which would silently re-
        // introduce the `PolicyBreakerZeroFailures` /
        // `PolicyBreakerZeroWindow` refusal cases at the emit
        // boundary), a bounds-collapsing accessor that clamped
        // `cb.max_failures` through
        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
        // [`AplicacaoSpec::validate`] gate owns the bounds; the
        // accessor must ship the raw slot verbatim), or a
        // by-reference detour (`Option<&CircuitBreaker>`) that broke
        // every downstream consumer keying off `Option<CircuitBreaker>`
        // by-copy.
        for cb in [
            None,
            Some(CircuitBreaker {
                max_failures: 1,
                window: Duration::from_millis(1),
            }),
            Some(CircuitBreaker {
                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
                window: POLICY_BREAKER_WINDOW_MAX,
            }),
            Some(CircuitBreaker {
                max_failures: 0,
                window: Duration::ZERO,
            }),
            Some(CircuitBreaker {
                max_failures: u32::MAX,
                window: Duration::MAX,
            }),
        ] {
            let p = MeshPolicy {
                circuit_breaker: cb,
                ..MeshPolicy::default()
            };
            assert_eq!(
                p.circuit_breaker(),
                cb,
                "MeshPolicy::circuit_breaker must return :politicas \
                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
                p.circuit_breaker(),
            );
            assert_eq!(
                p.circuit_breaker(),
                p.circuit_breaker,
                "MeshPolicy::circuit_breaker must byte-equal the raw \
                 .circuit_breaker field access across every value in \
                 the accept-set",
            );
        }
    }

    #[test]
    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
        // `.circuit_breaker` field access. Structurally: toggling ONLY
        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
        // must flip `is_empty()` from `true` (all-`None`) to `false`
        // (one axis carries a value); the flip must be observed for
        // every representative value in the accept-set the surrounding
        // [`AplicacaoSpec::validate_politicas`] gate accepts
        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
        // since the emptiness semantic reads "any axis carries a
        // value" — not "any axis carries a value the validate gate
        // accepts" — the same non-collapsing shape the peer M2
        // [`crate::LimitsSpec::is_empty`] /
        // [`crate::BehaviorSpec::is_empty`] predicates carry.
        //
        // Pins against a future silent detour that re-derived the
        // emptiness predicate off a peer axis (an accidental
        // `.rate_limit.is_none()`-only chain that dropped the
        // `circuit_breaker` arm entirely — the last unlifted inline
        // field access on `is_empty` before this lift), a
        // `circuit_breaker == Some(_)` collapse that key-off a
        // validate-gate-clamped bounds check (which would silently
        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
        // 0, window: 0s })` as empty because it fails the value-shape
        // gate), or an accessor-side detour that no longer names the
        // substrate-primitive typed dispatch.
        //
        // Fifth "the emptiness predicate must route through the
        // substrate-primitive typed dispatch" composition pin on the
        // M3 mesh-slot family — closes the last unlifted composition
        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
        // composition pins on the sibling primitive-Copy + composite-
        // Copy axes, extended onto the peer per-`:politicas`
        // composite-Copy `Option<CircuitBreaker>` axis).
        let empty = MeshPolicy::default();
        assert!(
            empty.is_empty(),
            "MeshPolicy::default() must be is_empty() — every axis \
             defaults to None",
        );
        for cb in [
            CircuitBreaker {
                max_failures: 1,
                window: Duration::from_millis(1),
            },
            CircuitBreaker {
                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
                window: POLICY_BREAKER_WINDOW_MAX,
            },
        ] {
            let p = MeshPolicy {
                circuit_breaker: Some(cb),
                ..MeshPolicy::default()
            };
            assert!(
                !p.is_empty(),
                "MeshPolicy::is_empty must return false when \
                 :circuit-breaker is {cb:?} — the emptiness predicate \
                 reads \"any axis carries a value\", not \"any axis \
                 carries a value the validate gate accepts\"",
            );
            assert_eq!(
                p.circuit_breaker().is_none(),
                p.is_empty(),
                "when :circuit-breaker is the only set axis, \
                 is_empty() must equal circuit_breaker().is_none() — \
                 the accessor and the emptiness predicate must route \
                 through the same substrate-primitive typed dispatch \
                 on the :circuit-breaker arm",
            );
        }
    }

    #[test]
    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
        // `:circuit-breaker` value-shape gate must key off
        // [`MeshPolicy::circuit_breaker`], not the raw
        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
        // whose only set axis is a `Some(CircuitBreaker { max_failures:
        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
        // refusal exactly, and the same MeshPolicy with the breaker at
        // the canonical lower boundary
        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
        // pass validate. The pair jointly pins the accessor +
        // validate-gate composition: any future silent detour that had
        // the accessor omit the `Some(CircuitBreaker { max_failures:
        // 0, .. })` arm (a
        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
        // collapse) would silently absorb the
        // `PolicyBreakerZeroFailures` refusal at the accessor
        // boundary — the composition pin catches that at caixa-core
        // build time.
        //
        // Sibling of the peer [`validate_politicas`]
        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
        // composition pins on the sibling primitive-Copy + composite-
        // Copy optional-scalar axes — same "the validate / shape-gate
        // predicate must route through the substrate-primitive typed
        // dispatch" discipline extended onto the peer per-`:politicas`
        // composite-Copy `Option<CircuitBreaker>` axis. Second
        // composition-with-accessor pin on the M3 mesh-slot
        // `Option<CircuitBreaker>` arm alongside the
        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
        let mut spec = three_member_spec();
        spec.politicas = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 0,
                window: Duration::from_millis(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            matches!(
                spec.validate(),
                Err(AplicacaoError::PolicyBreakerZeroFailures)
            ),
            "validate_politicas must reject max_failures == 0 with \
             PolicyBreakerZeroFailures — the accessor and the validate \
             gate must route through the same substrate-primitive \
             typed dispatch on the :circuit-breaker zero-floor arm",
        );
        spec.politicas = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 1,
                window: Duration::from_millis(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            spec.validate().is_ok(),
            "validate_politicas must accept a CircuitBreaker at the \
             canonical lower boundary (max_failures = 1, window = \
             1ms) — the accessor and the validate gate must route \
             through the same substrate-primitive typed dispatch on \
             the :circuit-breaker arm",
        );
    }

    #[test]
    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
        // Envoy-outlier-detection trip-threshold scalar pin:
        // [`CircuitBreaker::max_failures`] must return the
        // `:politicas :circuit-breaker :max-failures` typed `u32`
        // verbatim, byte-equal to the raw field access across every
        // representative value in the accept-set — `1` (the lower
        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
        // refusal), `0` (a past-the-guard sentinel that pins the accessor
        // doesn't perform a silent bounds-collapse into `1` on the zero
        // arm — validate rejects zero but the accessor must ship the
        // raw slot verbatim so a validate-time gate regression surfaces
        // at the emit boundary rather than being silently absorbed),
        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
        // doesn't perform a silent bounds-collapse through
        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
        //
        // First sub-struct required-scalar accessor pin on the M3
        // mesh-slot family — sibling in shape to the peer per-`:membros`
        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
        // (a40b0e3) required-`String`-carry accessor pins and the peer
        // per-`:contratos` [`WitContract::source`] /
        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
        // accessor pins, extended onto the peer per-`CircuitBreaker`
        // required-`u32` scalar-value axis. Pins against a future silent
        // detour that re-derived the trip threshold from a peer axis (an
        // accidental `self.window.as_secs() as u32` collapse that read
        // the breaker's rolling-window duration as a failure count), a
        // `0 → 1` cluster-default projection (which would silently absorb
        // the `PolicyBreakerZeroFailures` refusal case at the accessor
        // boundary), or a bounds-collapsing accessor that clamped the
        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
        // must ship the raw slot verbatim).
        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
            let cb = CircuitBreaker {
                max_failures,
                window: Duration::from_secs(60),
            };
            assert_eq!(
                cb.max_failures(),
                max_failures,
                "CircuitBreaker::max_failures must return :politicas \
                 :circuit-breaker :max-failures verbatim (got {}, \
                 expected {max_failures})",
                cb.max_failures(),
            );
            assert_eq!(
                cb.max_failures(),
                cb.max_failures,
                "CircuitBreaker::max_failures must byte-equal the raw \
                 .max_failures field access across every value in the \
                 u32 accept-set",
            );
        }
    }

    #[test]
    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
        // `:circuit-breaker :max-failures` zero-floor arm must key off
        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
        // field access. Structurally: a `CircuitBreaker { max_failures:
        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
        // pass validate. The pair jointly pins the accessor +
        // validate-gate composition: any future silent detour that had
        // the accessor return a fresh `1` on the zero arm (a
        // `.max_failures().max(1)` collapse) would silently absorb the
        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
        // and the validate gate would accept a struct-literal
        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
        // catches that at caixa-core build time.
        //
        // Peer of the sibling per-`:politicas`
        // [`MeshPolicy::mtls_required`] (c0110f1) /
        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
        // (7073d0f) accessor-composition pins on the sibling optional-
        // scalar axes — same "the validate / shape-gate predicate must
        // route through the substrate-primitive typed dispatch"
        // discipline extended onto the peer per-`CircuitBreaker`
        // required-scalar composition axis.
        let mut spec = three_member_spec();
        spec.politicas = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 0,
                window: Duration::from_secs(60),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            matches!(
                spec.validate(),
                Err(AplicacaoError::PolicyBreakerZeroFailures)
            ),
            "validate_politicas must reject max_failures == 0 with \
             PolicyBreakerZeroFailures — the accessor and the validate \
             gate must route through the same substrate-primitive typed \
             dispatch on the :max-failures zero-floor arm",
        );
        spec.politicas = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 1,
                window: Duration::from_secs(60),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            spec.validate().is_ok(),
            "validate_politicas must accept max_failures == 1 (the \
             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
             accept-set)",
        );
    }

    #[test]
    fn circuit_breaker_max_failures_projects_u32_by_copy() {
        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
        // `u32` by copy — `u32` is `Copy` and the accessor must return
        // by value, not by reference. Peer of the sibling
        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
        // optional-scalar axes, extended onto the peer
        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
        // the accessor's returned `u32` must outlive `&self` (multiple
        // calls must return equal values from a dropped-`&self` copy,
        // since the returned scalar carries no borrow), and calling
        // the accessor twice on the same CircuitBreaker must yield the
        // same `u32` verbatim (idempotent, no side effects on `&self`).
        //
        // Pins against a future silent detour that returned `&u32`
        // (which would type-check but silently break every downstream
        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
        // first parameter is `u32`, and `&u32` would fold to a detached
        // copy at the call site with a `*` deref the sibling accessors
        // don't need), an accidental `.max_failures.wrapping_add(0)`
        // detour that returned a fresh copy through an arithmetic
        // no-op (breaking a future `const fn` regression), or a
        // one-arm-only accessor that returned a saturating value on
        // some sentinel input (breaking the pass-through invariant the
        // sibling required-scalar accessors carry).
        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
            let cb = CircuitBreaker {
                max_failures,
                window: Duration::from_secs(60),
            };
            let first = cb.max_failures();
            let second = cb.max_failures();
            assert_eq!(
                first, second,
                "CircuitBreaker::max_failures must be idempotent — two \
                 successive calls on the same &self must return the \
                 same u32",
            );
            assert_eq!(
                first, max_failures,
                "CircuitBreaker::max_failures must return :politicas \
                 :circuit-breaker :max-failures verbatim by copy — \
                 got {first}, expected {max_failures}",
            );
        }
    }

    #[test]
    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
        // The canonical per-`:politicas :circuit-breaker` `:window`
        // Envoy-outlier-detection rolling-observation-interval scalar
        // pin: [`CircuitBreaker::window`] must return the
        // `:politicas :circuit-breaker :window` typed `Duration`
        // verbatim, byte-equal to the raw field access across every
        // representative value in the accept-set — `Duration::from_millis(1)`
        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
        // gate carves out on the sibling `PolicyBreakerZeroWindow`
        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
        // same gate carves out on the sibling
        // `PolicyBreakerWindowExceedsCap` refusal),
        // `Duration::ZERO` (a past-the-guard sentinel that pins the
        // accessor doesn't perform a silent bounds-collapse into
        // `Duration::from_millis(1)` on the zero arm — validate rejects
        // zero but the accessor must ship the raw slot verbatim so a
        // validate-time gate regression surfaces at the emit boundary
        // rather than being silently absorbed),
        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
        // far above the 1h cap — that pins the accessor doesn't perform
        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
        // at the return path).
        //
        // Second sub-struct required-scalar accessor pin on the M3
        // mesh-slot family — sibling in shape to the just-landed
        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
        // (3a74062) required-`u32` accessor pin on the peer
        // per-`CircuitBreaker` required-axis, extended onto the
        // per-sub-struct required-`Duration` axis. Pins against a
        // future silent detour that re-derived the observation window
        // from a peer axis (an accidental
        // `Duration::from_secs(self.max_failures as u64)` collapse that
        // read the breaker's trip count as an observation-interval
        // duration), a `Duration::ZERO → Duration::from_millis(1)`
        // cluster-default projection (which would silently absorb the
        // `PolicyBreakerZeroWindow` refusal case at the accessor
        // boundary), or a bounds-collapsing accessor that clamped the
        // return through `POLICY_BREAKER_WINDOW_MAX` (the
        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
        // must ship the raw slot verbatim).
        for window in [
            Duration::from_millis(1),
            POLICY_BREAKER_WINDOW_MAX,
            Duration::ZERO,
            Duration::from_secs(86_400),
        ] {
            let cb = CircuitBreaker {
                max_failures: 5,
                window,
            };
            assert_eq!(
                cb.window(),
                window,
                "CircuitBreaker::window must return :politicas \
                 :circuit-breaker :window verbatim (got {:?}, \
                 expected {window:?})",
                cb.window(),
            );
            assert_eq!(
                cb.window(),
                cb.window,
                "CircuitBreaker::window must byte-equal the raw \
                 .window field access across every value in the \
                 Duration accept-set",
            );
        }
    }

    #[test]
    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
        // `:circuit-breaker :window` zero-floor arm must key off
        // [`CircuitBreaker::window`], not the raw `.window` field
        // access. Structurally: a `CircuitBreaker { window:
        // Duration::ZERO, .. }` embedded in a
        // `:politicas :circuit-breaker` slot must surface the
        // `PolicyBreakerZeroWindow` refusal exactly, and a
        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
        // accept-set) must pass validate. The pair jointly pins the
        // accessor + validate-gate composition: any future silent
        // detour that had the accessor return a fresh
        // `Duration::from_millis(1)` on the zero arm (a
        // `.window().max(Duration::from_millis(1))` collapse) would
        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
        // accessor boundary and the validate gate would accept a
        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
        // — the composition pin catches that at caixa-core build time.
        //
        // Peer of the sibling per-`CircuitBreaker`
        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
        // pin on the peer required-scalar `:max-failures` axis — same
        // "the validate / shape-gate predicate must route through the
        // substrate-primitive typed dispatch" discipline extended onto
        // the peer per-`CircuitBreaker` required-`Duration` composition
        // axis.
        let mut spec = three_member_spec();
        spec.politicas = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 5,
                window: Duration::ZERO,
            }),
            ..MeshPolicy::default()
        };
        assert!(
            matches!(
                spec.validate(),
                Err(AplicacaoError::PolicyBreakerZeroWindow)
            ),
            "validate_politicas must reject window == Duration::ZERO \
             with PolicyBreakerZeroWindow — the accessor and the \
             validate gate must route through the same substrate-\
             primitive typed dispatch on the :window zero-floor arm",
        );
        spec.politicas = MeshPolicy {
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 5,
                window: Duration::from_millis(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            spec.validate().is_ok(),
            "validate_politicas must accept window == \
             Duration::from_millis(1) (the lower boundary of the \
             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
        );
    }

    #[test]
    fn circuit_breaker_window_projects_duration_by_copy() {
        // The by-copy pin: [`CircuitBreaker::window`] returns
        // `Duration` by copy — `Duration` is `Copy` and the accessor
        // must return by value, not by reference. Peer of the sibling
        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
        // (3a74062) by-copy pin on the peer required-scalar
        // `:max-failures` axis, extended onto the peer
        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
        // — the accessor's returned `Duration` must outlive `&self`
        // (multiple calls must return equal values from a
        // dropped-`&self` copy, since the returned scalar carries no
        // borrow), and calling the accessor twice on the same
        // CircuitBreaker must yield the same `Duration` verbatim
        // (idempotent, no side effects on `&self`).
        //
        // Pins against a future silent detour that returned
        // `&Duration` (which would type-check but silently break every
        // downstream `Duration`-by-value consumer —
        // [`crate::render::require_positive_canonical_bounded_duration`]'s
        // first parameter is `Duration`, and `&Duration` would fold to
        // a detached copy at the call site with a `*` deref the sibling
        // accessors don't need), an accidental `.window + Duration::ZERO`
        // detour that returned a fresh copy through an arithmetic
        // no-op (breaking a future `const fn` regression), or a
        // one-arm-only accessor that returned a saturating value on
        // some sentinel input (breaking the pass-through invariant the
        // sibling required-scalar accessors carry).
        for window in [
            Duration::from_millis(1),
            POLICY_BREAKER_WINDOW_MAX,
            Duration::ZERO,
            Duration::from_secs(86_400),
        ] {
            let cb = CircuitBreaker {
                max_failures: 5,
                window,
            };
            let first = cb.window();
            let second = cb.window();
            assert_eq!(
                first, second,
                "CircuitBreaker::window must be idempotent — two \
                 successive calls on the same &self must return the \
                 same Duration",
            );
            assert_eq!(
                first, window,
                "CircuitBreaker::window must return :politicas \
                 :circuit-breaker :window verbatim by copy — \
                 got {first:?}, expected {window:?}",
            );
        }
    }

    #[test]
    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
        // Apex-identity pair-invariant pin composing both substrate-
        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
        // and [`WitContract::destination`] — at the emit-side call shape
        // every per-`(:de, :para)` CNP L4 port reader now takes. The
        // invariant, evaluated per-edge:
        //
        //   spec.port_for_destination(c.destination()) == expected_port
        //
        // where `expected_port` is `entrada.port` when
        // `c.destination() == entrada.destination()` and
        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
        // pin on the per-`:entrada` axis — that pin encodes the apex
        // ingress L4 identity via `entrada.destination()`; this pin
        // encodes the per-edge L4 identity via `c.destination()`, and
        // both compose on the same substrate-primitive resolver so a
        // future refactor that silently split either accessor's apex
        // behavior surfaces at caixa-core build time.
        let mut spec = three_member_spec();
        if let Some(e) = spec.entrada.as_mut() {
            e.para = "cart".into();
            e.port = 8443;
        }
        let apex_contract = WitContract {
            de: "checkout".into(),
            para: "cart".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/hello".into()),
            subject: None,
            slot: None,
        };
        assert_eq!(
            spec.port_for_destination(apex_contract.destination()),
            8443,
            "`spec.port_for_destination(c.destination())` must equal \
             `entrada.port` when the contract callee names the ingress \
             apex — the CNP per-edge L4 port and the HTTPRoute apex \
             backendRef port share this substrate-primitive resolver.",
        );
        let non_apex_contract = WitContract {
            de: "cart".into(),
            para: "payment".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/charge".into()),
            subject: None,
            slot: None,
        };
        assert_eq!(
            spec.port_for_destination(non_apex_contract.destination()),
            DEFAULT_SERVICO_PORT,
            "`spec.port_for_destination(c.destination())` must fall back \
             to the substrate-canonical port floor when the contract \
             callee is not the ingress apex — the resolver's non-apex \
             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
        );
    }

    #[test]
    fn membro_key_consts_are_lower_camel_case_shape() {
        // Shape-pin: every `MEMBRO_KEY_*` const must be a
        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
        // `kebab-case` hyphens, no leading colon, no `PascalCase`
        // leading capital, no whitespace / dots) — the canonical shape
        // the `#[serde(rename_all = "camelCase")]` derive produces on
        // [`Membro`]. A future flip to a non-camelCase attribute at
        // the derive surfaces both here (this test fails on the
        // stale-constant shape) and at
        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
        // fails on the mismatch between const and derive). Peer with
        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
        // on the sibling `SupervisorSpec` top-level axis.
        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
            assert!(
                !key.is_empty(),
                "MEMBRO_KEY_* must be non-empty (got {key:?})"
            );
            let first = key.chars().next().unwrap();
            assert!(
                first.is_ascii_lowercase(),
                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
                 (got {key:?}, leads with {first:?})",
            );
            assert!(
                key.chars().all(|c| c.is_ascii_alphanumeric()),
                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
            );
        }
    }

    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────

    #[test]
    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
        // keys the `#[serde(rename_all = "camelCase")]` attribute on
        // [`WitContract`] emits for the required-triad. The three
        // sibling payload-arm keys already pin under
        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
        // `STORE_FIELD_NAME` — pin all six alongside so a future
        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
        // verbatim-field-name flip at the derive attribute (any of which
        // would silently break every downstream JSON consumer that
        // reaches for one of the six via `Value::get(...)`) surfaces
        // here as a build-time test failure at `aplicacao.rs`, not as an
        // apply-time `.get(<stale-canonical-const>)` returning `None`
        // far from the derive-attr drift's commit. Peer with the sibling
        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
        // pin on the M3 `:membros` per-entry axis — same discipline the
        // `Membro` per-entry lift established, extended here to the
        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
        // axis on the Aplicacao surface without a lifted serde-key peer.
        let c = WitContract {
            de: "cart".into(),
            para: "catalog".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/lookup".into()),
            subject: None,
            slot: None,
        };
        let json = serde_json::to_string(&c).unwrap();
        for key in [
            crate::CONTRATO_KEY_DE,
            crate::CONTRATO_KEY_PARA,
            crate::CONTRATO_KEY_WIT,
            WitTarget::HTTP_FIELD_NAME,
        ] {
            let quoted = format!("\"{key}\"");
            assert!(
                json.contains(&quoted),
                "serialized WitContract must carry the lifted \
                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
                 {quoted} verbatim in the JSON emission (got: {json})",
            );
        }

        // Pin the two remaining payload-arm keys by round-tripping a
        // `WitContract` under each payload-shape (pub-sub, store) — the
        // required-triad appears on every emission but the payload arms
        // only surface when their `Option<String>` field is `Some`.
        let pubsub = WitContract {
            de: "cart".into(),
            para: "events".into(),
            wit: "nats:pub-sub".into(),
            endpoint: None,
            subject: Some("orders.placed".into()),
            slot: None,
        };
        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
        assert!(
            pubsub_json.contains(&pubsub_quoted),
            "serialized pub-sub WitContract must carry the lifted \
             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
             verbatim in the JSON emission (got: {pubsub_json})",
        );
        let store = WitContract {
            de: "cart".into(),
            para: "sessions".into(),
            wit: "wasi:keyvalue/store".into(),
            endpoint: None,
            subject: None,
            slot: Some("cart/$id".into()),
        };
        let store_json = serde_json::to_string(&store).unwrap();
        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
        assert!(
            store_json.contains(&store_quoted),
            "serialized store WitContract must carry the lifted \
             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
             verbatim in the JSON emission (got: {store_json})",
        );
    }

    #[test]
    fn contrato_key_consts_are_pairwise_distinct() {
        // Cross-axis drift-detection pin: a future collapse of the six
        // canonical [`WitContract`] per-entry byte-strings onto the same
        // value (e.g. an accidental copy-paste flip of
        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
        // every downstream probe on one axis onto the sibling axis's
        // overlay entry and pass every propagation-probe test that
        // expected only the stale axis's value. Peer of the sibling
        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
        // widened here to the six-way axis the `WitContract`
        // required-triad + `WitTarget` payload-triad jointly cover.
        let all = [
            crate::CONTRATO_KEY_DE,
            crate::CONTRATO_KEY_PARA,
            crate::CONTRATO_KEY_WIT,
            WitTarget::HTTP_FIELD_NAME,
            WitTarget::PUBSUB_FIELD_NAME,
            WitTarget::STORE_FIELD_NAME,
        ];
        for (i, a) in all.iter().enumerate() {
            for b in all.iter().skip(i + 1) {
                assert_ne!(
                    a, b,
                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
                     must be pairwise-distinct canonical byte-sequences \
                     — got `{a}` == `{b}`",
                );
            }
        }
    }

    #[test]
    fn contrato_key_consts_are_lower_camel_case_shape() {
        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
        // byte-sequence (no `snake_case` underscores, no `kebab-case`
        // hyphens, no leading colon, no `PascalCase` leading capital, no
        // whitespace / dots) — the canonical shape the
        // `#[serde(rename_all = "camelCase")]` derive produces on
        // [`WitContract`]. A future flip to a non-camelCase attribute at
        // the derive surfaces both here (this test fails on the
        // stale-constant shape) and at
        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
        // (that test fails on the mismatch between const and derive).
        // Peer with `membro_key_consts_are_lower_camel_case_shape`
        // (ce80ca0) on the sibling `Membro` per-entry axis.
        for key in [
            crate::CONTRATO_KEY_DE,
            crate::CONTRATO_KEY_PARA,
            crate::CONTRATO_KEY_WIT,
            WitTarget::HTTP_FIELD_NAME,
            WitTarget::PUBSUB_FIELD_NAME,
            WitTarget::STORE_FIELD_NAME,
        ] {
            assert!(
                !key.is_empty(),
                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
                 non-empty (got {key:?})"
            );
            let first = key.chars().next().unwrap();
            assert!(
                first.is_ascii_lowercase(),
                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
                 with an ASCII-lowercase byte (got {key:?}, leads with \
                 {first:?})",
            );
            assert!(
                key.chars().all(|c| c.is_ascii_alphanumeric()),
                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
                 whitespace (got {key:?})",
            );
        }
    }

    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────

    #[test]
    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
        // name the exact camelCase JSON keys the
        // `#[serde(rename_all = "camelCase")]` attribute on
        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
        // pin that each canonical byte-sequence appears verbatim in the
        // JSON — a future accidental `rename_all = "snake_case"` /
        // `"kebab-case"` / verbatim-field-name flip at the derive
        // attribute (any of which would silently break every downstream
        // JSON consumer that reaches for one of the four consts via
        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
        // emitter's per-Aplicacao hostname/paths/port projection, the
        // future `app-operator` reconciler's per-Aplicacao ingress
        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
        // materializer's admission-time cross-check) surfaces here as
        // a build-time test failure at `aplicacao.rs`, not as an
        // apply-time `.get(<stale-canonical-const>)` returning `None`
        // far from the derive-attr drift's commit. Peer with the
        // sibling
        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
        // (ca463a4) and
        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
        // pins on the M3 collection-slot atom axes — same discipline
        // both collection-slot lifts established, extended here to the
        // singleton `:entrada` mesh-slot atom axis, the last M3
        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
        // axis on the Aplicacao surface without a lifted serde-key
        // peer.
        let e = Entrada {
            host: "checkout.quero.cloud".into(),
            para: "cart".into(),
            paths: vec!["/cart".into()],
            port: 8080,
        };
        let json = serde_json::to_string(&e).unwrap();
        for key in [
            crate::ENTRADA_KEY_HOST,
            crate::ENTRADA_KEY_PARA,
            crate::ENTRADA_KEY_PATHS,
            crate::ENTRADA_KEY_PORT,
        ] {
            let quoted = format!("\"{key}\"");
            assert!(
                json.contains(&quoted),
                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
                 byte-sequence {quoted} verbatim in the JSON emission \
                 (got: {json})",
            );
        }
    }

    #[test]
    fn entrada_key_consts_are_pairwise_distinct() {
        // Cross-axis drift-detection pin: a future collapse of the four
        // canonical [`Entrada`] singleton byte-strings onto the same
        // value (e.g. an accidental copy-paste flip of
        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
        // silently reroute every downstream probe on one axis onto the
        // sibling axis's overlay entry and pass every propagation-probe
        // test that expected only the stale axis's value — the
        // Gateway/HTTPRoute emitter would read the hostname string
        // where the destination-Servico name was expected (or vice
        // versa), the admission-webhook cross-check would compare the
        // wrong pair of values, and the resulting Gateway resource
        // would either be admitted with garbage or rejected at the
        // controller far from the rebrand commit's source. Peer of the
        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
        // tetrad (40cc4e5), the two-way distinct pin on the
        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
        // triad (ca463a4).
        let all = [
            crate::ENTRADA_KEY_HOST,
            crate::ENTRADA_KEY_PARA,
            crate::ENTRADA_KEY_PATHS,
            crate::ENTRADA_KEY_PORT,
        ];
        for (i, a) in all.iter().enumerate() {
            for b in all.iter().skip(i + 1) {
                assert_ne!(
                    a, b,
                    "ENTRADA_KEY_* consts must be pairwise-distinct \
                     canonical byte-sequences — got `{a}` == `{b}`",
                );
            }
        }
    }

    #[test]
    fn entrada_key_consts_are_lower_camel_case_shape() {
        // Shape-pin: every `ENTRADA_KEY_*` const must be a
        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
        // `kebab-case` hyphens, no leading colon, no `PascalCase`
        // leading capital, no whitespace / dots) — the canonical shape
        // the `#[serde(rename_all = "camelCase")]` derive produces on
        // [`Entrada`]. A future flip to a non-camelCase attribute at
        // the derive surfaces both here (this test fails on the
        // stale-constant shape) and at
        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
        // test fails on the mismatch between const and derive). Peer
        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
        // and `contrato_key_consts_are_lower_camel_case_shape`
        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
        // entry axes.
        for key in [
            crate::ENTRADA_KEY_HOST,
            crate::ENTRADA_KEY_PARA,
            crate::ENTRADA_KEY_PATHS,
            crate::ENTRADA_KEY_PORT,
        ] {
            assert!(
                !key.is_empty(),
                "ENTRADA_KEY_* must be non-empty (got {key:?})"
            );
            let first = key.chars().next().unwrap();
            assert!(
                first.is_ascii_lowercase(),
                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
                 (got {key:?}, leads with {first:?})",
            );
            assert!(
                key.chars().all(|c| c.is_ascii_alphanumeric()),
                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
            );
        }
    }

    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────

    #[test]
    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
        // [`crate::POLITICAS_KEY_RETRIES`] /
        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
        // on [`MeshPolicy`] emits. Three of the five axes
        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
        // camelCase transforms — the derive-attribute is load-bearing
        // on those, unlike the sibling `Entrada` / `Membro` /
        // `WitContract` structs whose fields are all lowercase-single-
        // word and where the derive is a no-op on every axis.
        // Serialize a fully-populated [`MeshPolicy`] (every axis
        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
        // on none of the five slots) and pin that each canonical
        // byte-sequence appears verbatim in the JSON — a future
        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
        // verbatim-field-name flip at the derive attribute (any of
        // which would silently break every downstream JSON consumer
        // that reaches for one of the five consts via
        // `Value::get(...)` — the future M4 per-edge `:politicas`
        // overlay projection onto Cilium `L7Rules` and Gateway API
        // `HTTPRoute` backend timeouts, the future
        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
        // admission-time mesh-policy cross-check, the future
        // `feira lint` per-`:politicas` bound-check gate) surfaces here
        // as a build-time test failure at `aplicacao.rs`, not as an
        // apply-time `.get(<stale-canonical-const>)` returning `None`
        // far from the derive-attr drift's commit. Peer with the
        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
        // atom axes — same discipline every M3 sibling lift
        // established, extended here to the singleton `:politicas`
        // mesh-slot atom axis, closing the last M3 typed-struct
        // top-level `#[serde(rename_all = "camelCase")]` axis on the
        // Aplicacao surface without a lifted serde-key peer.
        let p = MeshPolicy {
            timeout: Some(Duration::from_secs(30)),
            retries: Some(3),
            circuit_breaker: Some(CircuitBreaker {
                max_failures: 5,
                window: Duration::from_secs(60),
            }),
            mtls_required: Some(true),
            rate_limit: Some(RateLimit {
                rate: 100,
                window: Duration::from_secs(1),
            }),
        };
        let json = serde_json::to_string(&p).unwrap();
        for key in [
            crate::POLITICAS_KEY_TIMEOUT,
            crate::POLITICAS_KEY_RETRIES,
            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
            crate::POLITICAS_KEY_MTLS_REQUIRED,
            crate::POLITICAS_KEY_RATE_LIMIT,
        ] {
            let quoted = format!("\"{key}\"");
            assert!(
                json.contains(&quoted),
                "serialized MeshPolicy must carry the lifted \
                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
                 JSON emission (got: {json})",
            );
        }
    }

    #[test]
    fn politicas_key_consts_are_pairwise_distinct() {
        // Cross-axis drift-detection pin: a future collapse of the five
        // canonical [`MeshPolicy`] singleton byte-strings onto the same
        // value (e.g. an accidental copy-paste flip of
        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
        // would silently reroute every downstream probe on one axis
        // onto the sibling axis's overlay entry and pass every
        // propagation-probe test that expected only the stale axis's
        // value — the M4 per-edge `:politicas` overlay projection would
        // read the retry-count string where the timeout duration was
        // expected (or vice versa), the CR materializer's admission
        // cross-check would compare the wrong pair of values, and the
        // resulting mesh reconciler would either bind the wrong axis
        // or reject the resource at reconcile far from the rebrand
        // commit's source. Peer of the sibling four-way distinct pin
        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
        let all = [
            crate::POLITICAS_KEY_TIMEOUT,
            crate::POLITICAS_KEY_RETRIES,
            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
            crate::POLITICAS_KEY_MTLS_REQUIRED,
            crate::POLITICAS_KEY_RATE_LIMIT,
        ];
        for (i, a) in all.iter().enumerate() {
            for b in all.iter().skip(i + 1) {
                assert_ne!(
                    a, b,
                    "POLITICAS_KEY_* consts must be pairwise-distinct \
                     canonical byte-sequences — got `{a}` == `{b}`",
                );
            }
        }
    }

    #[test]
    fn politicas_key_consts_are_lower_camel_case_shape() {
        // Shape-pin: every `POLITICAS_KEY_*` const must be a
        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
        // `kebab-case` hyphens, no leading colon, no `PascalCase`
        // leading capital, no whitespace / dots) — the canonical shape
        // the `#[serde(rename_all = "camelCase")]` derive produces on
        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
        // at the derive surfaces both here (this test fails on the
        // stale-constant shape) and at
        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
        // (that test fails on the mismatch between const and derive).
        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
        // (ca463a4) on the sibling M3 typed-struct axes.
        for key in [
            crate::POLITICAS_KEY_TIMEOUT,
            crate::POLITICAS_KEY_RETRIES,
            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
            crate::POLITICAS_KEY_MTLS_REQUIRED,
            crate::POLITICAS_KEY_RATE_LIMIT,
        ] {
            assert!(
                !key.is_empty(),
                "POLITICAS_KEY_* must be non-empty (got {key:?})"
            );
            let first = key.chars().next().unwrap();
            assert!(
                first.is_ascii_lowercase(),
                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
                 byte (got {key:?}, leads with {first:?})",
            );
            assert!(
                key.chars().all(|c| c.is_ascii_alphanumeric()),
                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
            );
        }
    }

    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──

    #[test]
    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
        // [`CircuitBreaker`] emits inside the
        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
        // two axes (`max_failures` → `maxFailures`) is a non-trivial
        // camelCase transform — the derive-attribute is load-bearing on
        // that axis, unlike the sibling `window` field where the derive
        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
        // pin that each canonical byte-sequence appears verbatim in the
        // JSON — a future accidental `rename_all = "snake_case"` /
        // `"kebab-case"` / verbatim-field-name flip at the derive
        // attribute (any of which would silently break every downstream
        // JSON consumer that reaches for one of the two consts via
        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
        // per-edge `:politicas` overlay projection onto the mesh's
        // per-backend consecutive-failure-counter tripping threshold, the
        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
        // admission-time breaker cross-check, the future `feira lint`
        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
        // here as a build-time test failure at `aplicacao.rs`, not as an
        // apply-time `.get(<stale-canonical-const>)` returning `None`
        // far from the derive-attr drift's commit. Peer with the sibling
        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
        // (b55cca7) parent-axis pin — that test pins the outer
        // sub-block key the derive on [`MeshPolicy`] emits, this test
        // pins the inner keys the derive on the payload type emits, so
        // the two together lock the whole [`MeshPolicy`] breaker-tuning
        // shape end-to-end at build time.
        let cb = CircuitBreaker {
            max_failures: 5,
            window: Duration::from_secs(60),
        };
        let json = serde_json::to_string(&cb).unwrap();
        for key in [
            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
            crate::CIRCUIT_BREAKER_KEY_WINDOW,
        ] {
            let quoted = format!("\"{key}\"");
            assert!(
                json.contains(&quoted),
                "serialized CircuitBreaker must carry the lifted \
                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
                 in the JSON emission (got: {json})",
            );
        }
    }

    #[test]
    fn circuit_breaker_key_consts_are_pairwise_distinct() {
        // Cross-axis drift-detection pin: a future collapse of the two
        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
        // same value (e.g. an accidental copy-paste flip of
        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
        // `"maxFailures"`) would silently reroute every downstream
        // probe on one axis onto the sibling axis's overlay entry and
        // pass every propagation-probe test that expected only the
        // stale axis's value — the M4 per-edge `:politicas` overlay
        // projection would read the failure-count where the window
        // duration was expected (or vice versa), the CR materializer's
        // admission cross-check would compare the wrong pair of values,
        // and the resulting mesh reconciler would either bind the wrong
        // axis or reject the resource at reconcile far from the rebrand
        // commit's source. Peer of the sibling five-way distinct pin on
        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
        let all = [
            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
            crate::CIRCUIT_BREAKER_KEY_WINDOW,
        ];
        for (i, a) in all.iter().enumerate() {
            for b in all.iter().skip(i + 1) {
                assert_ne!(
                    a, b,
                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
                     canonical byte-sequences — got `{a}` == `{b}`",
                );
            }
        }
    }

    #[test]
    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
        // `kebab-case` hyphens, no leading colon, no `PascalCase`
        // leading capital, no whitespace / dots) — the canonical shape
        // the `#[serde(rename_all = "camelCase")]` derive produces on
        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
        // at the derive surfaces both here (this test fails on the
        // stale-constant shape) and at
        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
        // (that test fails on the mismatch between const and derive).
        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
        // (ca463a4) on the sibling M3 typed-struct axes.
        for key in [
            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
            crate::CIRCUIT_BREAKER_KEY_WINDOW,
        ] {
            assert!(
                !key.is_empty(),
                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
            );
            let first = key.chars().next().unwrap();
            assert!(
                first.is_ascii_lowercase(),
                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
                 byte (got {key:?}, leads with {first:?})",
            );
            assert!(
                key.chars().all(|c| c.is_ascii_alphanumeric()),
                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
            );
        }
    }

    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────

    #[test]
    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
        // [`Placement`] emits. One of the four axes (`shard_key` →
        // `shardKey`) is a non-trivial camelCase transform — the
        // derive-attribute is load-bearing on that axis, unlike the
        // sibling `estrategia` / `clusters` / `affinity` axes whose
        // source-side field names carry no `_` and where the derive is a
        // no-op. Serialize a fully-populated [`Placement`] (both
        // `Option`-carrying axes `Some(_)` so
        // `skip_serializing_if = "Option::is_none"` fires on neither of
        // the two optional slots) and pin that each canonical
        // byte-sequence appears verbatim in the JSON — a future
        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
        // verbatim-field-name flip at the derive attribute (any of which
        // would silently break every downstream consumer that reaches
        // for one of the four consts via
        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
        // aggregator's per-cluster fanout filter keying off
        // `placement.clusters`, the M3 shard-pool dispatch materializer
        // keying off `placement.shardKey`, the M3 Adaptive compression
        // pass weighting off `placement.affinity`, every downstream
        // dispatcher branching on `placement.estrategia`, the future
        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
        // admission-time placement cross-check, the future `feira lint`
        // per-`:placement` bound-check gate) surfaces here as a
        // build-time test failure at `aplicacao.rs`, not as an
        // apply-time `.get(<stale-canonical-const>)` returning `None`
        // far from the derive-attr drift's commit. Peer with the sibling
        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
        // (b55cca7),
        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
        // (468e959),
        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
        // (ca463a4), and
        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
        // pins on the M3 collection-slot / singleton-slot atom axes —
        // closes the last M3 typed-struct top-level
        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
        // surface without a drift-detection pin.
        let p = Placement {
            estrategia: PlacementStrategy::Sharded,
            clusters: vec!["rio".into(), "mar".into()],
            affinity: Some("data-locality".into()),
            shard_key: Some("$tenantId".into()),
        };
        let json = serde_json::to_string(&p).unwrap();
        for key in [
            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
            crate::M3_PLACEMENT_KEY_CLUSTERS,
            crate::M3_PLACEMENT_KEY_AFFINITY,
            crate::M3_PLACEMENT_KEY_SHARD_KEY,
        ] {
            let quoted = format!("\"{key}\"");
            assert!(
                json.contains(&quoted),
                "serialized Placement must carry the lifted \
                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
                 the JSON emission (got: {json})",
            );
        }
    }

    #[test]
    fn m3_placement_key_consts_are_pairwise_distinct() {
        // Cross-axis drift-detection pin: a future collapse of the four
        // canonical [`Placement`] sub-block byte-strings onto the same
        // value (e.g. an accidental copy-paste flip of
        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
        // `"affinity"`) would silently reroute every downstream probe on
        // one axis onto the sibling axis's overlay entry and pass every
        // propagation-probe test that expected only the stale axis's
        // value — the M3 shard-pool dispatch materializer would read the
        // affinity placement-hint where the shard-selection template was
        // expected (or vice versa), the M3 Adaptive compression pass's
        // cross-check would compare the wrong pair of values, and the
        // resulting placement engine would either bind the wrong axis or
        // reject the resource at reconcile far from the rebrand commit's
        // source. Peer of the sibling two-way distinct pin on the
        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
        let all = [
            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
            crate::M3_PLACEMENT_KEY_CLUSTERS,
            crate::M3_PLACEMENT_KEY_AFFINITY,
            crate::M3_PLACEMENT_KEY_SHARD_KEY,
        ];
        for (i, a) in all.iter().enumerate() {
            for b in all.iter().skip(i + 1) {
                assert_ne!(
                    a, b,
                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
                     canonical byte-sequences — got `{a}` == `{b}`",
                );
            }
        }
    }

    #[test]
    fn m3_placement_key_consts_are_lower_camel_case_shape() {
        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
        // `kebab-case` hyphens, no leading colon, no `PascalCase`
        // leading capital, no whitespace / dots) — the canonical shape
        // the `#[serde(rename_all = "camelCase")]` derive produces on
        // [`Placement`]. A future flip to a non-camelCase attribute at
        // the derive surfaces both here (this test fails on the stale-
        // constant shape) and at
        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
        // (that test fails on the mismatch between const and derive).
        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
        // (ca463a4) on the sibling M3 typed-struct axes.
        for key in [
            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
            crate::M3_PLACEMENT_KEY_CLUSTERS,
            crate::M3_PLACEMENT_KEY_AFFINITY,
            crate::M3_PLACEMENT_KEY_SHARD_KEY,
        ] {
            assert!(
                !key.is_empty(),
                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
            );
            let first = key.chars().next().unwrap();
            assert!(
                first.is_ascii_lowercase(),
                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
                 byte (got {key:?}, leads with {first:?})",
            );
            assert!(
                key.chars().all(|c| c.is_ascii_alphanumeric()),
                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
            );
        }
    }

    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
    //    destination-facing L4 port resolver every per-Aplicacao renderer
    //    reaching for a per-destination Servico TCP port axis routes
    //    through. The four pin tests below fix the four-way accept-set
    //    the resolver must always honor: (:entrada-para-matches,
    //    :entrada-para-mismatches, :entrada-none-so-fallback,
    //    :entrada-port-non-default-honored) — drift on any arm surfaces
    //    at caixa-core build time rather than at cluster-apply time.

    #[test]
    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
        // The typed `:entrada` block's `:para "cart"` matches the
        // queried destination, so the resolver returns the author-
        // declared `:port` scalar verbatim — the canonical "the
        // destination Servico IS the ingress apex, honor the typed
        // listener port" arm of the port-resolution dispatch.
        let mut spec = three_member_spec();
        if let Some(e) = spec.entrada.as_mut() {
            e.para = "cart".into();
            e.port = 9090;
        }
        assert_eq!(
            spec.port_for_destination("cart"),
            9090,
            "port_for_destination(entrada.para) must return entrada.port \
             verbatim, not the DEFAULT_SERVICO_PORT fallback"
        );
    }

    #[test]
    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
        // The typed `:entrada` block names `:para "cart"`, but the
        // queried destination is `"payment"` — a Servico that
        // participates in the mesh graph but is not the ingress apex.
        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
        // canonical port floor, closing the "non-apex destination reads
        // the substrate default" arm. Same fixture the peer
        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
        // pin at caixa-mesh exercises through the CNP emit-side path;
        // this pin exercises the shared underlying resolver directly.
        let spec = three_member_spec();
        assert_eq!(
            spec.port_for_destination("payment"),
            DEFAULT_SERVICO_PORT,
            "port_for_destination(non-apex-destination) must route \
             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
        );
    }

    #[test]
    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
        // Internal-only Aplicacao — no `:entrada` block declared. Every
        // per-destination port query falls back to the lifted
        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
        // the Aplicacao surface admits `:entrada None` (internal mesh
        // with no external gateway); every downstream renderer's per-
        // destination port axis must still resolve to a well-defined
        // scalar even without an ingress apex.
        let mut spec = three_member_spec();
        spec.entrada = None;
        assert_eq!(
            spec.port_for_destination("cart"),
            DEFAULT_SERVICO_PORT,
            "port_for_destination on an internal-only Aplicacao must \
             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
             every destination"
        );
        assert_eq!(
            spec.port_for_destination("payment"),
            DEFAULT_SERVICO_PORT,
            "port_for_destination on an internal-only Aplicacao must \
             fall back uniformly across every destination — the fallback \
             is not entrada-shape-conditional"
        );
    }

    #[test]
    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
        // Structural pin against a hypothetical future refactor that
        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
        // the resolver (a "normalize to the default when the author's
        // port matches the substrate default" collapse) — that would
        // break renderer sites that carry meaning on the emitted port
        // value beyond bare equality (a future per-cluster listener-
        // audit that keys off the author-declared port, not the
        // resolved-with-fallback port). Pin that a non-default
        // entrada.port is returned verbatim so drift here surfaces at
        // caixa-core build time.
        let mut spec = three_member_spec();
        if let Some(e) = spec.entrada.as_mut() {
            e.para = "cart".into();
            e.port = 8443;
        }
        assert_ne!(
            8443, DEFAULT_SERVICO_PORT,
            "test fixture must probe a port distinct from \
             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
        );
        assert_eq!(
            spec.port_for_destination("cart"),
            8443,
            "port_for_destination(entrada.para) must return entrada.port \
             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
        );
    }

    #[test]
    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
        // Apex-identity pair-invariant pin composing both substrate-
        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
        // and [`Entrada::destination`] — at the emit-side call shape
        // every per-Aplicacao renderer's ingress-apex L4 port reader
        // now takes. The invariant:
        //
        //   spec.port_for_destination(entrada.destination()) == entrada.port
        //
        // holds by construction under today's single-destination
        // `:entrada` slot (`destination()` returns `entrada.para`, and
        // the resolver's apex arm matches `para == destination` and
        // returns `entrada.port`), and every downstream consumer that
        // composes the two accessors at the ingress apex — the
        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
        // `backendRefs[0].port` emit-site path, the peer future M4 CR
        // materializer's admission-webhook that promotes the scalar to
        // a per-CR override overlay, every future per-Aplicacao snapshot
        // renderer's apex-facing L4 port reader — reaches through the
        // same composition. Pin the identity across four permutations
        // (`:para` × `:port` including a non-default port to exercise
        // the honor-verbatim arm and a non-cart `:para` to exercise
        // destination-agnostic identity) so a future refactor that
        // silently split either accessor's apex behavior surfaces at
        // caixa-core build time — a subtle `destination()` renaming
        // that returned `entrada.host.as_str()` instead of
        // `entrada.para.as_str()` would blow this pin loudly, closing
        // the last quiet failure mode the two lifts admit in composition.
        //
        // Peer discipline with the sibling caixa-mesh cross-crate pin
        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
        // on the two-renderer pair-invariant axis; this pin encodes the
        // same two-consumer coherence rule at the substrate-primitive
        // level so the invariant survives even if every renderer is
        // deleted.
        for (para, port) in [
            ("cart", DEFAULT_SERVICO_PORT),
            ("cart", 8443u16),
            ("payment", 9090u16),
            ("catalog", 443u16),
        ] {
            let mut spec = three_member_spec();
            if let Some(e) = spec.entrada.as_mut() {
                e.para = para.into();
                e.port = port;
            }
            let expected_port = spec
                .entrada
                .as_ref()
                .expect("three_member_spec carries a typed `:entrada` block")
                .port;
            let composed_port = {
                let entrada = spec.entrada.as_ref().expect("entrada present");
                spec.port_for_destination(entrada.destination())
            };
            assert_eq!(
                composed_port, expected_port,
                "`spec.port_for_destination(entrada.destination())` must \
                 equal `entrada.port` under today's single-destination \
                 `:entrada` slot — this is the apex-identity contract \
                 every downstream ingress-apex L4 port reader relies on. \
                 Input :entrada :para: {para:?}, :entrada :port: {port}"
            );
        }
    }

    #[test]
    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
        // per-`:entrada` apex-arm membership probe must key off
        // [`Entrada::destination`], not the raw `.para` field access.
        // Structurally: setting ONLY the `:entrada :para` field to a
        // fresh non-cart destination on an otherwise-well-formed
        // Aplicacao must (1) leave `e.destination()` byte-equal to
        // `e.para.as_str()` (the accessor is byte-projective by
        // definition), and (2) cause the resolver's apex arm to fire
        // and return `entrada.port` at exactly that new destination
        // while every other destination string falls through to
        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
        // membership check. Pins against a future silent detour that
        // (a) re-derived the apex-arm membership probe off
        // `e.para == destination` in `port_for_destination` instead of
        // `e.destination() == destination`, silently disagreeing with
        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
        // consumers (`entrada.destination()` at
        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
        // caixa-mesh/src/lib.rs:2739) that already reach through the
        // accessor, (b) accessor-side introduced a per-tenant alias
        // arm the caller was unaware of, silently rewriting an
        // author-declared `:para "cart"` value to a canary-aliased
        // form — the raw-field-access resolver would fall through to
        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
        // while the peer emit-site consumers landed on the aliased
        // destination, splitting the ingress-apex L4 port at
        // cluster-apply time.
        //
        // Peer of the sibling
        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
        // (d0de220) composition pin on the per-`:membros` refusal-arm
        // axis — same "the shape-gate predicate must route through the
        // substrate-primitive typed dispatch" discipline extended onto
        // the per-`:entrada` apex-arm membership-probe axis. Closes
        // the last unlifted `.para` production-code read site on
        // `Entrada` in `caixa-core` — after this converge every
        // `caixa-core` `.para` field access outside the accessor's own
        // body and outside the `WitContract` per-`:contratos` sibling
        // axis is either a test-side field-setter or a doc-comment
        // reference.
        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
            let mut spec = three_member_spec();
            if let Some(e) = spec.entrada.as_mut() {
                e.para = para.into();
                e.port = port;
            }
            let e = spec
                .entrada
                .as_ref()
                .expect("three_member_spec carries a typed `:entrada` block");
            assert_eq!(
                e.destination(),
                e.para.as_str(),
                "Entrada::destination must byte-equal the .para field \
                 access — an accessor-side detour that no longer \
                 projects the raw field would silently split this \
                 drift-detection test from the port_for_destination \
                 apex-arm membership probe",
            );
            assert_eq!(
                spec.port_for_destination(para),
                port,
                "port_for_destination must key off the accessor-projected \
                 destination and return `entrada.port` on the apex arm — \
                 input :entrada :para: {para:?}, :entrada :port: {port}",
            );
            assert_eq!(
                spec.port_for_destination("ghost-destination-never-a-member"),
                DEFAULT_SERVICO_PORT,
                "port_for_destination must fall through to \
                 DEFAULT_SERVICO_PORT on a non-matching destination \
                 under the accessor-projected membership check — input \
                 :entrada :para: {para:?}, :entrada :port: {port}",
            );
        }
    }

    #[test]
    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
        // The canonical per-`:politicas :rate-limit` `:rate`
        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
        // typed `u32` verbatim, byte-equal to the raw field access
        // across every representative value in the accept-set — `1` (the
        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
        // carves out on the sibling `PolicyRateLimitZero` refusal),
        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
        // `0` (a past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse into `1` on the zero arm —
        // validate rejects zero but the accessor must ship the raw slot
        // verbatim so a validate-time gate regression surfaces at the
        // emit boundary rather than being silently absorbed), `u32::MAX`
        // (a past-the-guard sentinel that pins the accessor doesn't
        // perform a silent bounds-collapse through
        // `POLICY_RATE_LIMIT_MAX` at the return path).
        //
        // First sub-struct required-scalar accessor pin on the
        // `RateLimit` axis — sibling in shape to the peer
        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
        // required-`u32` accessor pin on the peer per-sub-struct
        // required-axis. Pins against a future silent detour that
        // re-derived the token capacity from a peer axis (an accidental
        // `self.window.as_secs() as u32` collapse that read the
        // rate-limit window duration as a token count), a `0 → 1`
        // cluster-default projection (which would silently absorb the
        // `PolicyRateLimitZero` refusal case at the accessor boundary),
        // or a bounds-collapsing accessor that clamped the return
        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
        // gate owns the bounds; the accessor must ship the raw slot
        // verbatim).
        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
            let rl = RateLimit {
                rate,
                window: Duration::from_secs(1),
            };
            assert_eq!(
                rl.rate(),
                rate,
                "RateLimit::rate must return :politicas :rate-limit :rate \
                 verbatim (got {}, expected {rate})",
                rl.rate(),
            );
            assert_eq!(
                rl.rate(),
                rl.rate,
                "RateLimit::rate must byte-equal the raw .rate field \
                 access across every value in the u32 accept-set",
            );
        }
    }

    #[test]
    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
        // `:rate-limit :rate` zero-floor arm must key off
        // [`RateLimit::rate`], not the raw `.rate` field access.
        // Structurally: a `RateLimit { rate: 0, window:
        // Duration::from_secs(1) }` embedded in a `:politicas
        // :rate-limit` slot must surface the `PolicyRateLimitZero`
        // refusal exactly, and a `RateLimit { rate: 1, window:
        // Duration::from_secs(1) }` (the lower boundary of the
        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
        // The pair jointly pins the accessor + validate-gate composition:
        // any future silent detour that had the accessor return a fresh
        // `1` on the zero arm (a `.rate().max(1)` collapse) would
        // silently absorb the `PolicyRateLimitZero` refusal at the
        // accessor boundary and the validate gate would accept a
        // struct-literal `RateLimit { rate: 0, .. }` — the composition
        // pin catches that at caixa-core build time.
        //
        // Peer of the sibling per-`CircuitBreaker`
        // [`CircuitBreaker::max_failures`] (3a74062) /
        // [`CircuitBreaker::window`] (373957f) accessor-composition
        // pins on the peer required-scalar axes — same "the validate /
        // shape-gate predicate must route through the substrate-primitive
        // typed dispatch" discipline extended onto the peer
        // per-`RateLimit` required-`u32` composition axis.
        let mut spec = three_member_spec();
        spec.politicas = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 0,
                window: Duration::from_secs(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
            "validate_politicas must reject rate == 0 with \
             PolicyRateLimitZero — the accessor and the validate gate \
             must route through the same substrate-primitive typed \
             dispatch on the :rate zero-floor arm",
        );
        spec.politicas = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 1,
                window: Duration::from_secs(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            spec.validate().is_ok(),
            "validate_politicas must accept rate == 1 (the lower \
             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
        );
    }

    #[test]
    fn rate_limit_rate_projects_u32_by_copy() {
        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
        // `u32` is `Copy` and the accessor must return by value, not by
        // reference. Peer of the sibling per-`CircuitBreaker`
        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
        // peer required-scalar `:max-failures` axis, extended onto the
        // peer per-`RateLimit` required-`u32` copy-invariant shape —
        // the accessor's returned `u32` must outlive `&self` (multiple
        // calls must return equal values from a dropped-`&self` copy,
        // since the returned scalar carries no borrow), and calling the
        // accessor twice on the same RateLimit must yield the same
        // `u32` verbatim (idempotent, no side effects on `&self`).
        //
        // Pins against a future silent detour that returned `&u32`
        // (which would type-check but silently break every downstream
        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
        // first parameter is `u32`, and `&u32` would fold to a detached
        // copy at the call site with a `*` deref the sibling accessors
        // don't need), an accidental `.rate.wrapping_add(0)` detour that
        // returned a fresh copy through an arithmetic no-op (breaking a
        // future `const fn` regression), or a one-arm-only accessor
        // that returned a saturating value on some sentinel input
        // (breaking the pass-through invariant the sibling required-
        // scalar accessors carry).
        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
            let rl = RateLimit {
                rate,
                window: Duration::from_secs(1),
            };
            let first = rl.rate();
            let second = rl.rate();
            assert_eq!(
                first, second,
                "RateLimit::rate must be idempotent — two successive \
                 calls on the same &self must return the same u32",
            );
            assert_eq!(
                first, rate,
                "RateLimit::rate must return :politicas :rate-limit :rate \
                 verbatim by copy — got {first}, expected {rate}",
            );
        }
    }

    #[test]
    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
        // The canonical per-`:politicas :rate-limit` `:window`
        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
        // pin: [`RateLimit::window`] must return the
        // `:politicas :rate-limit :window` typed `Duration` verbatim,
        // byte-equal to the raw field access across every
        // representative value in the accept-set — `Duration::from_secs(1)`
        // (the `"s"` canonical window, the lower row of
        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
        // [`AplicacaoSpec::validate_politicas`] gate accepts via
        // [`is_canonical_rate_limit_window`]),
        // `Duration::from_secs(60)` (the `"m"` canonical window, the
        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
        // window, the upper row), `Duration::ZERO` (a past-the-guard
        // sentinel that pins the accessor doesn't perform a silent
        // bounds-collapse into `Duration::from_secs(1)` on the zero
        // arm — validate rejects an off-set window through
        // `PolicyRateLimitWindowNotCanonical` but the accessor must
        // ship the raw slot verbatim so a validate-time gate
        // regression surfaces at the emit boundary rather than being
        // silently absorbed), `Duration::from_millis(500)` (a
        // sub-canonical past-the-guard sentinel that pins the accessor
        // doesn't silently normalize a non-canonical fractional
        // magnitude onto the nearest canonical row).
        //
        // Second sub-struct required-scalar accessor pin on the
        // `RateLimit` axis — sibling in shape to the just-landed
        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
        // accessor pin on the peer per-sub-struct required-axis,
        // extended onto the per-`RateLimit` required-`Duration` axis.
        // Pins against a future silent detour that re-derived the
        // refill period from a peer axis (an accidental
        // `Duration::from_secs(self.rate as u64)` collapse that read
        // the rate-limit token capacity as a refill-interval
        // duration), a `Duration::ZERO → Duration::from_secs(1)`
        // canonical-default projection (which would silently absorb
        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
        // accessor boundary), or a canonical-set-collapsing accessor
        // that clamped the return through [`rate_limit_window_unit`]
        // (the `AplicacaoSpec::validate` gate owns the canonical-set
        // membership; the accessor must ship the raw slot verbatim).
        for window in [
            Duration::from_secs(1),
            Duration::from_secs(60),
            Duration::from_secs(3600),
            Duration::ZERO,
            Duration::from_millis(500),
        ] {
            let rl = RateLimit { rate: 100, window };
            assert_eq!(
                rl.window(),
                window,
                "RateLimit::window must return :politicas :rate-limit :window \
                 verbatim (got {:?}, expected {window:?})",
                rl.window(),
            );
            assert_eq!(
                rl.window(),
                rl.window,
                "RateLimit::window must byte-equal the raw .window field \
                 access across every value in the Duration accept-set",
            );
        }
    }

    #[test]
    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
        // `:rate-limit :window` canonical-set arm must key off
        // [`RateLimit::window`], not the raw `.window` field access.
        // Structurally: a `RateLimit { window: Duration::from_millis(500),
        // .. }` embedded in a `:politicas :rate-limit` slot must
        // surface the `PolicyRateLimitWindowNotCanonical` refusal
        // exactly (with the sub-canonical `Duration::from_millis(500)`
        // magnitude carried through verbatim), and a `RateLimit
        // { window: Duration::from_secs(1), .. }` (the lower row of
        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
        // The pair jointly pins the accessor + validate-gate
        // composition: any future silent detour that had the accessor
        // normalize the off-set window to the nearest canonical row
        // (a `.window().max(Duration::from_secs(1))` collapse, or a
        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
        // collapse) would silently absorb the
        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
        // boundary — including a drift in the error's `window` payload
        // (the emit-side diagnostic reader keys off the offending
        // magnitude verbatim, so a normalization at the accessor
        // boundary would silently pin the wrong magnitude in the
        // refusal). The composition pin catches that at caixa-core
        // build time.
        //
        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
        // (7f81a60) accessor-composition pin on the peer required-
        // scalar `:rate` axis — same "the validate / shape-gate
        // predicate must route through the substrate-primitive typed
        // dispatch, and the error payload must project through the
        // same accessor" discipline extended onto the peer
        // per-`RateLimit` required-`Duration` composition axis.
        let mut spec = three_member_spec();
        spec.politicas = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 100,
                window: Duration::from_millis(500),
            }),
            ..MeshPolicy::default()
        };
        match spec.validate() {
            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
                assert_eq!(
                    window,
                    Duration::from_millis(500),
                    "PolicyRateLimitWindowNotCanonical must carry the \
                     offending :window magnitude verbatim through the \
                     accessor — got {window:?}, expected 500ms",
                );
            }
            other => panic!(
                "validate_politicas must reject non-canonical :window \
                 with PolicyRateLimitWindowNotCanonical — the accessor \
                 and the validate gate must route through the same \
                 substrate-primitive typed dispatch on the :window \
                 canonical-set arm; got {other:?}",
            ),
        }
        spec.politicas = MeshPolicy {
            rate_limit: Some(RateLimit {
                rate: 100,
                window: Duration::from_secs(1),
            }),
            ..MeshPolicy::default()
        };
        assert!(
            spec.validate().is_ok(),
            "validate_politicas must accept window == Duration::from_secs(1) \
             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
        );
    }

    #[test]
    fn rate_limit_window_projects_duration_by_copy() {
        // The by-copy pin: [`RateLimit::window`] returns `Duration`
        // by copy — `Duration` is `Copy` and the accessor must return
        // by value, not by reference. Peer of the sibling per-`RateLimit`
        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
        // required-scalar `:rate` axis, extended onto the peer
        // per-`RateLimit` required-`Duration` copy-invariant shape —
        // the accessor's returned `Duration` must outlive `&self`
        // (multiple calls must return equal values from a
        // dropped-`&self` copy, since the returned scalar carries no
        // borrow), and calling the accessor twice on the same
        // RateLimit must yield the same `Duration` verbatim
        // (idempotent, no side effects on `&self`).
        //
        // Pins against a future silent detour that returned
        // `&Duration` (which would type-check but silently break every
        // downstream `Duration`-by-value consumer —
        // [`is_canonical_rate_limit_window`]'s first parameter is
        // `Duration`, and `&Duration` would fold to a detached copy at
        // the call site with a `*` deref the sibling accessors don't
        // need), an accidental `.window + Duration::ZERO` detour that
        // returned a fresh copy through an arithmetic no-op (breaking
        // a future `const fn` regression), or a one-arm-only accessor
        // that returned a canonical fallback on some sentinel input
        // (breaking the pass-through invariant the sibling required-
        // scalar accessors carry).
        for window in [
            Duration::from_secs(1),
            Duration::from_secs(60),
            Duration::from_secs(3600),
            Duration::ZERO,
            Duration::from_millis(500),
        ] {
            let rl = RateLimit { rate: 100, window };
            let first = rl.window();
            let second = rl.window();
            assert_eq!(
                first, second,
                "RateLimit::window must be idempotent — two successive \
                 calls on the same &self must return the same Duration",
            );
            assert_eq!(
                first, window,
                "RateLimit::window must return :politicas :rate-limit :window \
                 verbatim by copy — got {first:?}, expected {window:?}",
            );
        }
    }
}