caixa-core 0.1.9

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
//! Layout invariants — the Rust-enforced package structure.
//!
//! This is the caixa analog of Cargo's implicit `src/lib.rs` vs `src/main.rs`
//! rule: the Rust type system dictates the package shape, and the invariant
//! checker runs before any build step. [`StandardLayout`] encodes the
//! canonical layout:
//!
//! - `caixa.lisp`           — always required
//! - `lib/<nome>.lisp`      — required when `:kind Biblioteca` and
//!                            `:bibliotecas` is empty
//! - each `:bibliotecas`    — must resolve on disk
//! - each `:exe`            — must resolve on disk, under `exe/`
//! - each `:servicos`       — must resolve on disk, under `servicos/`
//!
//! Filesystem I/O is injected through [`StandardLayout::with_path_exists`]
//! so tests can run without touching disk.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use thiserror::Error;

use crate::{Caixa, CaixaKind};

/// Contract — a caixa layout checker.
pub trait LayoutInvariants {
    /// Verify every declared path resolves + kind-specific invariants hold.
    fn verify(&self, caixa: &Caixa, root: &Path) -> Result<(), LayoutError>;
}

type ExistsFn = Arc<dyn Fn(&Path) -> bool + Send + Sync>;

/// The default layout contract.
#[derive(Default, Clone)]
pub struct StandardLayout {
    path_exists: Option<ExistsFn>,
}

impl StandardLayout {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Override how file existence is tested. Useful for in-memory tests.
    #[must_use]
    pub fn with_path_exists<F>(mut self, f: F) -> Self
    where
        F: Fn(&Path) -> bool + Send + Sync + 'static,
    {
        self.path_exists = Some(Arc::new(f));
        self
    }

    fn exists(&self, p: &Path) -> bool {
        self.path_exists
            .as_ref()
            .map_or_else(|| p.exists(), |f| f(p))
    }
}

impl std::fmt::Debug for StandardLayout {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StandardLayout")
            .field("custom_exists", &self.path_exists.is_some())
            .finish()
    }
}

impl LayoutInvariants for StandardLayout {
    fn verify(&self, caixa: &Caixa, root: &Path) -> Result<(), LayoutError> {
        let manifest = root.join("caixa.lisp");
        if !self.exists(&manifest) {
            return Err(LayoutError::MissingManifest(manifest));
        }

        // Caixa-identity value-shape gates on the two universal axes
        // (`:nome`, `:versao`) every substrate-side artifact's
        // `metadata.name` / version derivation flows through. The
        // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] doc-
        // comments name the canonical authoring footguns verbatim —
        // `:nome` "MyApp" / "my_app" / "team.app" / "-app" / "café"
        // (DNS-1123 violations the K8s apiserver refuses at admission
        // time on every derived `metadata.name`: `lareira-<nome>`,
        // programs.yaml entry, CiliumNetworkPolicy / HTTPRoute names,
        // `LABEL_APLICACAO` value); `:versao` "0.1" / "v0.1.0" / "latest"
        // / "^0.1" / "0.1.0.0" (SemVer-2 violations Helm / OCI tag /
        // `feira publish` git tag / lacre `concrete_versao` /
        // `:upgrade-from :from` peer matching each refuse downstream).
        // Until this wire-up landed both validators existed as `pub fn`
        // on [`Caixa`] (with full per-arm test coverage in
        // `manifest::tests`) but no production code path called them —
        // `feira build` (the canonical author-time gate) silently
        // accepted a malformed `:nome` / `:versao` and the failure
        // surfaced at `helm install` / `kubectl apply` / `feira publish`
        // time on the *first* downstream consumer to strict-parse the
        // value, far from the source `caixa.lisp` and without any field
        // naming the offending Caixa identity axis. The gate runs
        // *after* [`LayoutError::MissingManifest`] (no caixa to check
        // when the manifest is missing) and *before* every kind-coherence
        // gate (each of which carries `caixa.nome` verbatim in its
        // diagnostic — running them first on a structurally-invalid
        // identity would surface a "this kind has slot X" diagnostic
        // against an unrecoverable name). Cross-axis precedence is
        // `:nome` → `:versao` — the canonical declaration order on
        // [`Caixa`] and the same author-grep ordering the
        // [`ManifestError`] family uses. Same per-axis `*Violation
        // { caixa, issue }` envelope every peer per-axis wrap exposes
        // ([`LayoutError::CodePathViolation`] b868442,
        // [`LayoutError::LimitsViolation`] / [`LayoutError::BehaviorViolation`]
        // / [`LayoutError::UpgradeViolation`] / [`LayoutError::SupervisorViolation`]
        // / [`LayoutError::AplicacaoViolation`]).
        caixa
            .validate_nome()
            .map_err(|err| LayoutError::NomeViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;
        // `:nome`-side joint-length budget on the canonical
        // `lareira-<nome>` chart-name shape — the second arm on the
        // shared `:nome` axis after the bare-DNS-1123 gate above. Runs
        // through the same [`LayoutError::NomeViolation`] envelope so
        // every per-axis diagnostic on `:nome` carries one wrap shape,
        // peer with the [`Caixa::validate_nome`] → `NomeInvalid`
        // routing already at this site. The chart-name budget is the
        // second-axis ceiling [`Caixa::validate_nome`] cannot see — a
        // 56-byte DNS-1123-valid `:nome` passes the bare-`:nome` shape
        // but produces a 64-byte `lareira-<nome>` chart name the
        // apiserver / `helm lint` rejects at admission, far from the
        // source `caixa.lisp` and naming none of the joint-length
        // overflow's three carriers (DNS-1123 cap, prefix, `:nome`
        // length). Closing it at this wire-up turns the
        // [`lareira_chart_name`] doc-comment's explicit M4-admission
        // deferral (caixa-core/src/render.rs:3198) into a build-time
        // structural property of every emitted artifact.
        caixa
            .validate_nome_chart_name_budget()
            .map_err(|err| LayoutError::NomeViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;
        caixa
            .validate_versao()
            .map_err(|err| LayoutError::VersaoViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // `:deps` / `:deps-dev` per-entry shape gate. The third Caixa-
        // level orphan validator on the universal authoring surface (peer
        // of [`Caixa::validate_nome`] / [`Caixa::validate_versao`] wired
        // immediately above): [`Caixa::validate_deps`] walks every
        // [`Dep::validate`] arm — empty / non-DNS-1123 `:nome`, empty /
        // unparseable `:versao` requirement, malformed `:fonte` repo /
        // pin / `:caminho`, malformed `:caracteristicas` Cargo-feature
        // name (de68c0c) — and then closes the per-list set-not-multiset
        // duplicate-`:nome` invariant on each of `:deps` and `:deps-dev`
        // (359fba5). Until this wire-up landed `validate_deps` existed as
        // `pub fn` on [`Caixa`] with full per-arm unit coverage in
        // `manifest::tests` + `dep::tests` (validate_deps_rejects_*,
        // 53 dep-axis tests) but no production code path called it —
        // `feira build` (the canonical author-time gate;
        // `caixa-feira/src/cmd/build.rs:29` routes through
        // `StandardLayout::verify`) silently accepted a malformed `:deps`
        // entry and the failure surfaced at the *first* downstream
        // consumer to strict-parse it: at lacre-resolve time as a
        // `semver::Error` not naming the offending dep (`:versao` per-
        // entry); at `git clone` time as a fetch failure quoting the
        // shell-escape `repo` (`:fonte :repo`); at the resolver's
        // `HashMap<:nome>` collapse as a silent "second-wins" overwrite
        // (within-list `:nome` duplicate); at `cargo metadata` time as a
        // feature-name rejection on the *target* caixa rather than the
        // dep entry referencing it (`:caracteristicas`); at `helm
        // install` / `kubectl apply` time as an apiserver `metadata.name`
        // rejection on the rendered `lareira-<nome>` chart's per-dep
        // derivation (DNS-1123-violating `:deps :nome`) — each far from
        // the source `caixa.lisp`, none naming the offending `:deps` /
        // `:deps-dev` axis. Runs *after* the Caixa-identity gates (the
        // diagnostic carries `caixa.nome().to_string()` verbatim, which the
        // peer [`Caixa::validate_nome`] gate above has just guaranteed is
        // a valid DNS-1123 label) and *before* every kind-coherence gate
        // (the dep surface is universal — every kind has `:deps` /
        // `:deps-dev` — so its shape diagnostic is more fundamental than
        // the kind-coherence partitions on `:bibliotecas` / `:exe` /
        // `:servicos` / `:membros` / `:children` / M2 slots that follow).
        // Same per-axis `*Violation { caixa, issue }` envelope every peer
        // per-axis wrap exposes ([`LayoutError::NomeViolation`] /
        // [`LayoutError::VersaoViolation`] (1f74a5f),
        // [`LayoutError::CodePathViolation`] (b868442),
        // [`LayoutError::LimitsViolation`] / [`LayoutError::BehaviorViolation`]
        // / [`LayoutError::UpgradeViolation`] / [`LayoutError::SupervisorViolation`]
        // / [`LayoutError::AplicacaoViolation`]). Threads [`DepError`]
        // Display through verbatim — every per-arm reason already names
        // the offending dep's `:nome` (e.g. `":deps entry "caixa-teia"
        // :versao "^bad" is not a valid semver requirement: …"`), so the
        // wrap envelope's `issue` carries a self-locating "which dep,
        // which axis, why" without re-shaping the per-arm parser-side
        // reason. With this wire-up the canonical author-time gate
        // refuses every ill-formed `:deps` / `:deps-dev` value-shape by
        // construction — closing the second-to-last orphan-validator gap
        // on the typed Caixa surface (`validate_restart_window` is the
        // remaining orphan, Supervisor-axis specific and wired into the
        // Supervisor branch below alongside `view.validate()`).
        caixa
            .validate_deps()
            .map_err(|err| LayoutError::DepsViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // `:deps` / `:deps-dev` self-dep cross-slot coherence gate. A
        // caixa whose `:deps` or `:deps-dev` lists its own `:nome` is a
        // degenerate self-edge in the lacre closure's dep-graph — the
        // closure is a DAG rooted at the caixa's `:nome`, and the
        // caixa-resolver's traversal 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 its stack. Until this gate landed the
        // within-list duplicate-`:nome` arm of [`Caixa::validate_deps`]
        // (359fba5) closed the multiset axis on each dep list, but the
        // self-edge axis (one entry whose `:nome` happens to equal the
        // parent caixa's `:nome`) silently passed validate. Both lists
        // are walked (in declaration order: `:deps` → `:deps-dev`) so a
        // caixa that self-references on both axes surfaces the `:deps`
        // diagnostic first, peer with the canonical
        // [`Caixa::validate_deps`] cascade and the
        // [`crate::supervisor::validate_no_self_supervision`] /
        // [`crate::aplicacao::validate_no_self_membership`] self-edge
        // gates on the supervision-tree and Aplicacao-membership axes.
        //
        // Runs *after* `validate_deps` so the per-entry / cross-entry
        // dep-shape diagnostics fire first — a self-referential `:deps`
        // entry whose `:nome` is malformed (`:nome ""`, non-DNS-1123,
        // duplicate within its list) surfaces the narrower per-entry
        // diagnostic before the self-edge gate sees the entry. Same
        // ordering posture every peer cross-slot gate uses
        // ([`validate_no_self_supervision`] runs after
        // `SupervisorSpec::validate`, [`validate_no_self_membership`]
        // runs after `AplicacaoSpec::validate`,
        // [`validate_upgrade_from_against_versao`] runs after
        // `validate_upgrade_from`).
        //
        // Threads [`DepError`] Display through verbatim — the per-arm
        // reason already names the offending dep's `:nome` and the
        // list tag (`":deps"` / `":deps-dev"`), so the wrap envelope's
        // `issue` carries a self-locating "which list, which entry,
        // why" without re-shaping the parser-side reason. Closes the
        // self-edge axis on the third typed-name-graph kind on the
        // typed Caixa surface (`:children :caixa` ad4abf1,
        // `:membros :caixa` and this dep-graph gate together cover
        // every typed-name-graph axis the substrate carries).
        crate::dep::validate_no_self_dep(caixa.deps(), caixa.deps_dev(), caixa.nome()).map_err(
            |err| LayoutError::DepsViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            },
        )?;

        // `:etiquetas` per-entry empty + cross-entry duplicate gate. The
        // fourth universal-axis Caixa-level value-shape gate (peer of
        // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
        // [`Caixa::validate_deps`] wired immediately above and
        // [`Caixa::validate_code_paths`] wired below the kind-coherence
        // gates) on the typed Caixa surface. `:etiquetas` is the
        // registry-search-tag axis every kind carries (universal
        // `Vec<String>` slot on [`Caixa`]) and lands verbatim as the
        // Helm chart `Chart.yaml` `keywords:` array on every Servico
        // (`caixa-helm/src/lib.rs:236` folds it through a
        // [`std::collections::BTreeSet`]). Until this wire-up landed
        // `:etiquetas` had no shape gate at any layer — an empty entry
        // (`(:etiquetas (""))` — the canonical paste-from-blank-doc
        // footgun) silently rendered as `keywords: [""]` in `Chart.yaml`,
        // and duplicate entries (`(:etiquetas ("demo" "demo"))` — the
        // copy-paste-the-wrong-tag footgun) were silently dedup'd by
        // the renderer's `BTreeSet` collect — a "second wins / one
        // silently disappears" shape divergent from every peer typed-
        // graph set gate (`:membros :caixa`, `:placement :clusters`,
        // `:entrada :paths`, `:contratos`, `:deps :nome`,
        // `:upgrade-from :from`, the per-instruction-class singularity
        // gates on `:upgrade-from :instructions`). Runs *after* the
        // peer universal `:nome` / `:versao` / `:deps` gates (declaration
        // order on [`Caixa`] is `:nome` → `:versao` → `:edicao` →
        // `:descricao` → `:repositorio` → `:licenca` → `:autores` →
        // `:etiquetas` → `:deps` → `:deps-dev`, but the gate order
        // follows the same identity-axis-first cascade the peer gates
        // establish: `:nome` → `:versao` are the load-bearing identity
        // axes that flow into every diagnostic's caixa prefix, and
        // `:deps` is the universal dep surface that dominates every
        // kind-coherence gate; `:etiquetas` runs after this trio so the
        // diagnostic carries an already-validated `:nome` and the
        // peer universal axes' narrower diagnostics surface first when
        // multiple axes are malformed) and *before* the kind-coherence
        // gates ([`Self::MeshSlotsOnNonAplicacao`] /
        // [`Self::SupervisorSlotsOnNonSupervisor`] /
        // [`Self::ServicoSlotsOnNonServico`] / [`Self::ForeignCodeSlot`])
        // — `:etiquetas` is universal so its shape diagnostic is more
        // fundamental than the kind-coherence partitions on kind-
        // exclusive slot sets.
        //
        // Same per-axis `*Violation { caixa, issue }` envelope every peer
        // per-axis wrap exposes ([`Self::NomeViolation`] /
        // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
        // aa77d0f, [`Self::CodePathViolation`] b868442,
        // [`Self::RestartWindowViolation`] 10e321a). Threads
        // [`ManifestError::EtiquetaEmpty`] / [`ManifestError::EtiquetaDuplicate`]
        // Display through verbatim — each per-arm reason already names
        // the offending tag (for the duplicate arm) or the structural
        // "empty entry" defect (for the empty arm), so the wrap
        // envelope's `issue` carries a self-locating "which axis, which
        // entry, why" without re-shaping the per-arm reason.
        caixa
            .validate_etiquetas()
            .map_err(|err| LayoutError::EtiquetasViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // `:autores` per-entry empty + cross-entry duplicate gate. The
        // fifth universal-axis Caixa-level value-shape gate (peer of
        // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
        // [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] wired
        // immediately above and [`Caixa::validate_code_paths`] wired
        // below the kind-coherence gates) on the typed Caixa surface.
        // `:autores` is the maintainer-axis every kind carries
        // (universal `Vec<String>` slot on [`Caixa`]) and lands verbatim
        // as the Helm chart `Chart.yaml` `maintainers:` array on every
        // Servico (`caixa-helm/src/lib.rs:251` maps each entry to a
        // `Maintainer { name, email: None }` without dedup). Until this
        // wire-up landed `:autores` had no shape gate at any layer — an
        // empty entry (`(:autores (""))` — the canonical paste-from-
        // blank-doc footgun) silently rendered as
        // `maintainers: [{name: "", email: null}]` in `Chart.yaml`, and
        // duplicate entries (`(:autores ("pleme-io" "pleme-io"))` —
        // the copy-paste-the-wrong-author footgun) stacked verbatim in
        // the chart. Unlike the peer `:etiquetas` axis (where the
        // renderer's `BTreeSet` collect silently dedups the `keywords:`
        // array at chart render — a "second wins / one silently
        // disappears" shape), `maintainers:` has *no* renderer-side
        // dedup, so duplicate `:autores` entries render as two identical
        // maintainer records by construction — a strictly worse footgun
        // than the peer `:etiquetas` shape. Runs *after* the peer
        // universal `:nome` / `:versao` / `:deps` / `:etiquetas` gates
        // (the gate order follows the canonical identity-axis-first
        // cascade the peer gates establish; `:autores` and `:etiquetas`
        // are the two Vec-shaped universal metadata axes — they sit
        // adjacent in the cascade after the load-bearing identity +
        // dep trio) and *before* the kind-coherence gates
        // ([`Self::MeshSlotsOnNonAplicacao`] /
        // [`Self::SupervisorSlotsOnNonSupervisor`] /
        // [`Self::ServicoSlotsOnNonServico`] / [`Self::ForeignCodeSlot`])
        // — `:autores` is universal so its shape diagnostic is more
        // fundamental than the kind-coherence partitions on kind-
        // exclusive slot sets.
        //
        // Same per-axis `*Violation { caixa, issue }` envelope every peer
        // per-axis wrap exposes ([`Self::NomeViolation`] /
        // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
        // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
        // [`Self::CodePathViolation`] b868442,
        // [`Self::RestartWindowViolation`] 10e321a). Threads
        // [`ManifestError::AutorEmpty`] / [`ManifestError::AutorDuplicate`]
        // Display through verbatim — each per-arm reason already names
        // the offending author (for the duplicate arm) or the structural
        // "empty entry" defect (for the empty arm), so the wrap
        // envelope's `issue` carries a self-locating "which axis, which
        // entry, why" without re-shaping the per-arm reason.
        caixa
            .validate_autores()
            .map_err(|err| LayoutError::AutoresViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // `:repositorio` git-repo-URL shape gate. The sixth
        // universal-axis Caixa-level value-shape gate (peer of
        // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
        // [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] /
        // [`Caixa::validate_autores`] wired immediately above and
        // [`Caixa::validate_code_paths`] wired below the kind-coherence
        // gates) on the typed Caixa surface. `:repositorio` is the
        // universal git-shaped homepage axis every kind carries
        // (universal `Option<String>` slot on [`Caixa`]) and routes
        // through two load-bearing substrate consumers:
        // [`caixa-helm`] folds it verbatim into the rendered
        // `lareira-<nome>` Helm chart's `Chart.yaml` `home:` field
        // (`build_chart_yaml` at `caixa-helm/src/lib.rs:268`) and into
        // the chart `README.md` `repo = …` interpolation
        // (`caixa-helm/src/lib.rs:359`); [`caixa-flux`] folds it
        // verbatim into the standalone `ClusterBundleOpts::for_caixa`
        // `git_url:` field (`caixa-flux/src/lib.rs:293`), which
        // becomes the FluxCD `GitRepository.spec.url` the cluster's
        // source-controller polls — the load-bearing deploy-time axis.
        // Both consumers use `Option::unwrap_or_else(|| <fallback>)`
        // to substitute a placeholder when the slot is absent (`None`
        // → the fallback fires); a `Some("")` *skips the fallback*
        // and silently passes the empty string through to
        // `Chart.yaml home: ""` / `GitRepository url: ""`. Until this
        // wire-up landed `:repositorio` had no shape gate at any
        // layer — empty (`(:repositorio "")` — the canonical
        // paste-from-blank-doc footgun) and malformed (whitespace,
        // control char / CRLF, leading `-` CLI-arg-injection,
        // missing `:` separator) values silently landed in the
        // rendered artifacts and broke at `helm template` / FluxCD
        // reconcile time far from the source `caixa.lisp`.
        //
        // Runs *after* the peer universal `:nome` / `:versao` /
        // `:deps` / `:etiquetas` / `:autores` gates (the gate order
        // follows the canonical identity-axis-first cascade the peer
        // gates establish; `:repositorio` is the universal git-URL
        // axis — it sits adjacent to `:autores` in the cascade after
        // the load-bearing identity + dep trio + the two Vec-shaped
        // universal metadata axes) and *before* the kind-coherence
        // gates ([`Self::MeshSlotsOnNonAplicacao`] /
        // [`Self::SupervisorSlotsOnNonSupervisor`] /
        // [`Self::ServicoSlotsOnNonServico`] / [`Self::ForeignCodeSlot`])
        // — `:repositorio` is universal so its shape diagnostic is
        // more fundamental than the kind-coherence partitions on
        // kind-exclusive slot sets.
        //
        // Same per-axis `*Violation { caixa, issue }` envelope every
        // peer per-axis wrap exposes ([`Self::NomeViolation`] /
        // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
        // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
        // [`Self::AutoresViolation`] 86c769b, [`Self::CodePathViolation`]
        // b868442, [`Self::RestartWindowViolation`] 10e321a). Threads
        // [`ManifestError::RepositorioEmpty`] /
        // [`ManifestError::RepositorioInvalid`] Display through
        // verbatim — each per-arm reason already names the offending
        // `:repositorio` value (for the invalid arm) or the
        // structural "empty entry" defect (for the empty arm), so
        // the wrap envelope's `issue` carries a self-locating "which
        // axis, which value, why" without re-shaping the per-arm
        // reason. With this gate the two `git URL`-shaped surfaces on
        // the typed Caixa (`:repositorio` here, `:deps :fonte :repo`
        // peer routed through the same shared
        // [`crate::render::is_git_repo_url`] predicate via
        // [`crate::DepSource::validate`]) are now structurally
        // equivalent — every value past validate is
        // guaranteed-acceptable by the shared predicate's constraint
        // union, by construction.
        caixa
            .validate_repositorio()
            .map_err(|err| LayoutError::RepositorioViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // `:descricao` non-empty shape gate. The seventh universal-
        // axis Caixa-level value-shape gate (peer of
        // [`Caixa::validate_nome`] / [`Caixa::validate_versao`] /
        // [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] /
        // [`Caixa::validate_autores`] / [`Caixa::validate_repositorio`]
        // wired immediately above and [`Caixa::validate_code_paths`]
        // wired below the kind-coherence gates) on the typed Caixa
        // surface. `:descricao` is the universal free-form-prose
        // summary axis every kind carries (universal `Option<String>`
        // slot on [`Caixa`]) and routes through two load-bearing
        // [`caixa-helm`] consumers: `build_chart_yaml` folds it
        // verbatim into the rendered `lareira-<nome>` Helm chart's
        // `Chart.yaml` `description:` field
        // (`caixa-helm/src/lib.rs:232-235`), and `build_readme` folds
        // it verbatim into the chart `README.md` header
        // (`caixa-helm/src/lib.rs:333-336`). Both consumers use
        // `Option::unwrap_or_else(|| <fallback>)` to substitute a
        // `caixa.nome`-derived placeholder when the slot is absent
        // (`None` → the fallback fires); a `Some("")` *skips the
        // fallback* and silently passes the empty string through to
        // `Chart.yaml description: ""` / a blank `README.md` header
        // — exact same footgun shape as the peer `:repositorio`
        // surface above. Until this wire-up landed `:descricao` had
        // no shape gate at any layer — the empty
        // (`(:descricao "")` — the canonical paste-from-blank-doc
        // footgun) silently landed in the rendered artifacts and
        // broke at `helm lint` time (`WARNING [chart.metadata.description]:
        // description is required` on `apiVersion: v2` charts) far
        // from the source `caixa.lisp`.
        //
        // Runs *after* the peer universal `:nome` / `:versao` /
        // `:deps` / `:etiquetas` / `:autores` / `:repositorio` gates
        // (the gate order follows the canonical identity-axis-first
        // cascade the peer gates establish; `:descricao` is the
        // universal free-form-prose axis — it sits adjacent to
        // `:repositorio` in the cascade after the load-bearing
        // identity + dep trio + the two Vec-shaped universal
        // metadata axes + the universal git-URL axis) and *before*
        // the kind-coherence gates ([`Self::MeshSlotsOnNonAplicacao`]
        // / [`Self::SupervisorSlotsOnNonSupervisor`] /
        // [`Self::ServicoSlotsOnNonServico`] /
        // [`Self::ForeignCodeSlot`]) — `:descricao` is universal so
        // its shape diagnostic is more fundamental than the kind-
        // coherence partitions on kind-exclusive slot sets.
        //
        // Same per-axis `*Violation { caixa, issue }` envelope every
        // peer per-axis wrap exposes ([`Self::NomeViolation`] /
        // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
        // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
        // [`Self::AutoresViolation`] 86c769b,
        // [`Self::RepositorioViolation`] 577b0a9,
        // [`Self::CodePathViolation`] b868442,
        // [`Self::RestartWindowViolation`] 10e321a). Threads
        // [`ManifestError::DescricaoEmpty`] Display through verbatim
        // — the per-arm reason already names the offending
        // `:descricao` slot + cites the renderer-side footgun, so
        // the wrap envelope's `issue` carries a self-locating
        // "which axis, why" without re-shaping the per-arm reason.
        caixa
            .validate_descricao()
            .map_err(|err| LayoutError::DescricaoViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // `:licenca` non-empty shape gate. The eighth universal-axis
        // Caixa-level value-shape gate (peer of [`Caixa::validate_nome`]
        // / [`Caixa::validate_versao`] / [`Caixa::validate_deps`] /
        // [`Caixa::validate_etiquetas`] / [`Caixa::validate_autores`] /
        // [`Caixa::validate_repositorio`] / [`Caixa::validate_descricao`]
        // wired immediately above and [`Caixa::validate_code_paths`]
        // wired below the kind-coherence gates) on the typed Caixa
        // surface. `:licenca` is the universal SPDX-shaped license-
        // expression axis every kind carries (universal `Option<String>`
        // slot on [`Caixa`]) and routes through one load-bearing
        // [`caixa-helm`] consumer: `build_readme` folds it verbatim into
        // the rendered `lareira-<nome>` Helm chart's `README.md` `##
        // License` section (`caixa-helm/src/lib.rs:361`) via
        // `caixa.licenca.clone().unwrap_or_else(|| "MIT".into())`. The
        // consumer's fallback only fires when the slot is absent (`None`
        // → the `MIT` fallback fires); a `Some("")` *skips the
        // fallback* and silently passes the empty string through to a
        // chart `README.md` whose `License` section renders as a bare
        // trailing period — exact same footgun shape as the peer
        // `:repositorio` (577b0a9) and `:descricao` (4e6db38) surfaces
        // above. Until this wire-up landed `:licenca` had no shape
        // gate at any layer — the empty (`(:licenca "")` — the
        // canonical paste-from-blank-doc footgun) silently landed in
        // the rendered chart `README.md` far from the source
        // `caixa.lisp`.
        //
        // Runs *after* the peer universal `:nome` / `:versao` /
        // `:deps` / `:etiquetas` / `:autores` / `:repositorio` /
        // `:descricao` gates (the gate order follows the canonical
        // identity-axis-first cascade the peer gates establish;
        // `:licenca` sits adjacent to `:descricao` in the cascade
        // after the load-bearing identity + dep trio + the two
        // Vec-shaped universal metadata axes + the universal
        // git-URL + free-form-prose axes) and *before* the kind-
        // coherence gates ([`Self::MeshSlotsOnNonAplicacao`] /
        // [`Self::SupervisorSlotsOnNonSupervisor`] /
        // [`Self::ServicoSlotsOnNonServico`] /
        // [`Self::ForeignCodeSlot`]) — `:licenca` is universal so
        // its shape diagnostic is more fundamental than the kind-
        // coherence partitions on kind-exclusive slot sets.
        //
        // Same per-axis `*Violation { caixa, issue }` envelope every
        // peer per-axis wrap exposes ([`Self::NomeViolation`] /
        // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
        // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
        // [`Self::AutoresViolation`] 86c769b,
        // [`Self::RepositorioViolation`] 577b0a9,
        // [`Self::DescricaoViolation`] 4e6db38,
        // [`Self::CodePathViolation`] b868442,
        // [`Self::RestartWindowViolation`] 10e321a). Threads
        // [`ManifestError::LicencaEmpty`] Display through verbatim
        // — the per-arm reason already names the offending
        // `:licenca` slot + cites the renderer-side footgun, so
        // the wrap envelope's `issue` carries a self-locating
        // "which axis, why" without re-shaping the per-arm reason.
        caixa
            .validate_licenca()
            .map_err(|err| LayoutError::LicencaViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // `:edicao` non-empty shape gate. The ninth (and last
        // un-gated) universal-axis Caixa-level value-shape gate
        // (peer of [`Caixa::validate_nome`] / [`Caixa::validate_versao`]
        // / [`Caixa::validate_deps`] / [`Caixa::validate_etiquetas`] /
        // [`Caixa::validate_autores`] / [`Caixa::validate_repositorio`]
        // / [`Caixa::validate_descricao`] / [`Caixa::validate_licenca`]
        // wired immediately above and [`Caixa::validate_code_paths`]
        // wired below the kind-coherence gates) on the typed Caixa
        // surface. `:edicao` is the universal language-edition axis
        // every kind carries (universal `Option<String>` slot on
        // [`Caixa`]) that selects the tatara-lisp macro surface +
        // compatibility flags the substrate applies when building
        // the caixa. The canonical [`Caixa::template`] scaffold every
        // `feira init` emits carries `:edicao "2026"` verbatim
        // (`caixa-core/src/manifest.rs:1193`) and every renderer-side
        // fixture carries `edicao: Some("2026".into())` by
        // construction (`caixa-helm/src/lib.rs:375`,
        // `caixa-flux/src/lib.rs:445`, `caixa-mesh/src/lib.rs:629`,
        // `caixa-core/src/render.rs:2510`). Until this wire-up landed
        // `:edicao` had no shape gate at any layer — the empty
        // (`(:edicao "")` — the canonical paste-from-blank-doc
        // footgun) silently landed as a bare `(:edicao "")` line
        // in the rendered caixa.lisp and a future renderer-side
        // consumer that folds the value through
        // `Option::unwrap_or_else` would skip its fallback (which
        // only fires on `None`) and pass the empty edition through
        // to the substrate's build-time edition selector far from
        // the source `caixa.lisp` — exact same
        // `Some("")`-skips-`unwrap_or_else` footgun shape as the
        // peer `:repositorio` (577b0a9), `:descricao` (4e6db38),
        // and `:licenca` (3d1e535) surfaces above.
        //
        // Runs *after* the peer universal `:nome` / `:versao` /
        // `:deps` / `:etiquetas` / `:autores` / `:repositorio` /
        // `:descricao` / `:licenca` gates (the gate order follows
        // the canonical identity-axis-first cascade the peer gates
        // establish; `:edicao` sits at the tail of the cascade
        // after the load-bearing identity + dep trio + the two
        // Vec-shaped universal metadata axes + the three universal
        // `Option<String>` chart-metadata axes) and *before* the
        // kind-coherence gates ([`Self::MeshSlotsOnNonAplicacao`] /
        // [`Self::SupervisorSlotsOnNonSupervisor`] /
        // [`Self::ServicoSlotsOnNonServico`] /
        // [`Self::ForeignCodeSlot`]) — `:edicao` is universal so
        // its shape diagnostic is more fundamental than the kind-
        // coherence partitions on kind-exclusive slot sets.
        //
        // Same per-axis `*Violation { caixa, issue }` envelope every
        // peer per-axis wrap exposes ([`Self::NomeViolation`] /
        // [`Self::VersaoViolation`] 1f74a5f, [`Self::DepsViolation`]
        // aa77d0f, [`Self::EtiquetasViolation`] 360a499,
        // [`Self::AutoresViolation`] 86c769b,
        // [`Self::RepositorioViolation`] 577b0a9,
        // [`Self::DescricaoViolation`] 4e6db38,
        // [`Self::LicencaViolation`] 3d1e535,
        // [`Self::CodePathViolation`] b868442,
        // [`Self::RestartWindowViolation`] 10e321a). Threads
        // [`ManifestError::EdicaoEmpty`] Display through verbatim
        // — the per-arm reason already names the offending
        // `:edicao` slot + cites the renderer-side footgun, so
        // the wrap envelope's `issue` carries a self-locating
        // "which axis, why" without re-shaping the per-arm reason.
        // With this gate every universal-axis `Option<String>`
        // surface on the typed Caixa (`:repositorio` 577b0a9,
        // `:descricao` 4e6db38, `:licenca` 3d1e535, `:edicao` here)
        // now carries the same structural empty-arm gate by
        // construction.
        caixa
            .validate_edicao()
            .map_err(|err| LayoutError::EdicaoViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        // Supervisors, Aplicacaos, and Acaos don't run code; reject
        // bibliotecas/exe/servicos declarations BEFORE checking those
        // paths exist (which would otherwise produce a less-helpful
        // "missing entry" error first).
        let has_code = !caixa.bibliotecas().is_empty()
            || !caixa.exe().is_empty()
            || !caixa.servicos().is_empty();
        if caixa.kind().is_supervisor() && has_code {
            return Err(LayoutError::SupervisorOwnsCode(caixa.nome().to_string()));
        }
        if caixa.kind().is_aplicacao() && has_code {
            return Err(LayoutError::AplicacaoOwnsCode(caixa.nome().to_string()));
        }
        // An Acao's sole payload is its `:ci` slot (CANTEIRO §7.1-C) —
        // like Supervisor/Aplicacao it runs no code of its own, so a
        // declared :bibliotecas/:exe/:servicos is the same "silently
        // ignored" footgun the two gates above already close for the
        // other two no-code kinds.
        if caixa.kind().is_acao() && has_code {
            return Err(LayoutError::AcaoOwnsCode(caixa.nome().to_string()));
        }

        // Kind ↔ slot coherence: the M3 mesh slots (:membros,
        // :contratos, :politicas, :placement, :entrada) compose the
        // typed graph of a :kind Aplicacao (MESH-COMPOSITION §III.1).
        // `Caixa::aplicacao_view` only folds them into a validatable
        // AplicacaoSpec when the kind is Aplicacao, and the
        // caixa-mesh/-flux/-helm renderers only emit them for an
        // Aplicacao — so on any *other* kind a declared mesh slot is the
        // manifest field's documented "ignored otherwise": it silently
        // passes verify and then vanishes (never validated, never
        // rendered), far from the source caixa.lisp. Reject it here —
        // before the path-existence loops — mirroring the
        // SupervisorOwnsCode / AplicacaoOwnsCode kind-coherence gates
        // above: a slot foreign to the kind is a build error, not a
        // silent drop. `declared_mesh_slots` is the single typed source
        // of the mesh-slot set + its canonical diagnostic order.
        if !caixa.kind().is_aplicacao() {
            let mesh_slots = caixa.declared_mesh_slots();
            if !mesh_slots.is_empty() {
                return Err(LayoutError::MeshSlotsOnNonAplicacao {
                    caixa: caixa.nome().to_string(),
                    kind: caixa.kind(),
                    slots: mesh_slots.join(" "),
                });
            }
        }

        // Kind ↔ slot coherence (mirror of the mesh-slot gate above on
        // the supervisor-tree slot set): the supervisor slots
        // (:estrategia, :max-restarts, :restart-window, :children)
        // compose the typed OTP supervisor of a :kind Supervisor
        // (INSPIRATIONS §II.2). `Caixa::supervisor_view` only folds them
        // into a validatable SupervisorSpec when the kind is Supervisor,
        // and the wasm-operator's hierarchical reconciler only consumes
        // them for one — so on any *other* kind a declared supervisor
        // slot is the manifest field's documented "ignored otherwise":
        // it silently passes verify and then vanishes (never validated,
        // never reconciled), far from the source caixa.lisp. Reject it
        // here — beside the mesh-slot gate, before the path-existence
        // loops — naming the offending kind + slot(s). `declared_
        // supervisor_slots` is the single typed source of the
        // supervisor-slot set + its canonical diagnostic order.
        if !caixa.kind().is_supervisor() {
            let supervisor_slots = caixa.declared_supervisor_slots();
            if !supervisor_slots.is_empty() {
                return Err(LayoutError::SupervisorSlotsOnNonSupervisor {
                    caixa: caixa.nome().to_string(),
                    kind: caixa.kind(),
                    slots: supervisor_slots.join(" "),
                });
            }
        }

        // Kind ↔ slot coherence (mirror of the mesh-slot + supervisor-slot
        // gates above on the M2 Servico-runtime slot set): the M2 slots
        // (:limits, :behavior, :upgrade-from) configure the runtime of a
        // long-running wasm component, i.e. a :kind Servico — :limits is
        // Lunatic per-process sandboxing (INSPIRATIONS §III.1), :behavior
        // the OTP gen_server callback set (§II.3), :upgrade-from the OTP
        // appup hot-reload table (§II.4). The caixa-helm / caixa-flux
        // renderers gate on `require_kind(_, Servico)` and only emit these
        // slots for a Servico — so on any *other* kind a declared M2 slot
        // is the manifest field's documented "ignored otherwise": its
        // well-formedness is checked by the M2 invariant blocks below, but
        // the value is never rendered into a chart / programs.yaml entry —
        // it silently passes verify and then vanishes, far from the source
        // caixa.lisp. Reject it here — beside the mesh- and supervisor-slot
        // gates, before the M2 validate blocks (which would otherwise spend
        // their diagnostics on a value the kind can never render) — naming
        // the offending kind + slot(s). `declared_servico_slots` is the
        // single typed source of the M2-slot set + its canonical
        // diagnostic order.
        if !caixa.kind().is_servico() {
            let servico_slots = caixa.declared_servico_slots();
            if !servico_slots.is_empty() {
                return Err(LayoutError::ServicoSlotsOnNonServico {
                    caixa: caixa.nome().to_string(),
                    kind: caixa.kind(),
                    slots: servico_slots.join(" "),
                });
            }
        }

        // Kind ↔ slot coherence (mirror of the three gates above on the
        // Acao `:ci` slot, CANTEIRO §7.1-C): `:ci` carries a typed CI
        // run — a canteiro_types::CiRun — that only the caixa-actions
        // renderer decomposes + validates, and only for a :kind Acao.
        // On any *other* kind a declared `:ci` is the manifest field's
        // documented "ignored otherwise": it silently passes verify and
        // then vanishes (never decomposed, never rendered), far from the
        // source caixa.lisp. Reject it here — beside the mesh-,
        // supervisor-, and servico-slot gates — naming the offending
        // kind. Unlike its three siblings this axis is a single
        // `Option` field, not a Vec-of-named-slots, so the gate reads
        // `caixa.ci().is_some()` directly rather than reaching for a
        // `declared_*_slots()` helper.
        if caixa.ci().is_some() && !caixa.kind().is_acao() {
            return Err(LayoutError::CiOnNonAcao {
                caixa: caixa.nome().to_string(),
                kind: caixa.kind(),
            });
        }

        // Kind ↔ slot coherence on the fourth and final axis — the
        // code-surface slot set (the trio M2/Supervisor/Aplicacao gates
        // above close on the M2 runtime, supervisor-tree, and M3 mesh
        // axes; this gate closes the symmetric "kind owns this code
        // shape" relation on `:exe` + `:servicos`). `:exe` is the nix-
        // built executable surface owned only by Binario; `:servicos`
        // is the wasm-component daemon surface owned only by Servico.
        // The caixa-helm / caixa-flux / caixa-flake renderers gate on
        // `require_kind(_, <owning-kind>)` and only emit the slot for
        // its owning kind — so on any *other* code-running kind a
        // declared `:exe` / `:servicos` is the manifest field's
        // documented "ignored otherwise" (see the field docs on
        // `Caixa::exe` + `Caixa::servicos`): the path is validated by
        // the per-kind path-existence loops below, but the value is
        // never rendered into a build target or programs.yaml entry —
        // it silently passes `feira build` and then vanishes, far from
        // the source caixa.lisp.
        //
        // Reject it here — beside the M2/Supervisor/Aplicacao slot
        // gates, after the `SupervisorOwnsCode` / `AplicacaoOwnsCode`
        // OwnCode gates which dominate on those two no-code kinds (a
        // Supervisor / Aplicacao with any of `:bibliotecas` / `:exe` /
        // `:servicos` surfaces the OwnCode diagnostic first), and
        // before the path-existence loops which would otherwise spend
        // a less-helpful `MissingEntry` diagnostic on the foreign
        // slot's path. `declared_foreign_code_slots` is the single
        // typed source of the foreign-code-slot set + its canonical
        // diagnostic order (`:exe` → `:servicos`).
        //
        // Mirrors the 9d37f98 / 510c00a / 760a430 kind ↔ slot
        // coherence trio's "declared-but-inert" footgun closure on the
        // M2 / supervisor-tree / M3 axes, now extended onto the code-
        // surface axis — every code-running kind's exclusive code
        // surface is structurally fenced from every other code-running
        // kind. `:bibliotecas` is deliberately excluded from the foreign
        // set on Binario / Servico (a `lib/` helper bundled into the
        // nix flake's build or the wasm-component's source tree is a
        // legitimate cross-kind authoring shape); on Biblioteca it is
        // the native slot, and on Supervisor / Aplicacao the OwnCode
        // gates above already close it.
        let foreign_code_slots = caixa.declared_foreign_code_slots();
        if !foreign_code_slots.is_empty() {
            return Err(LayoutError::ForeignCodeSlot {
                caixa: caixa.nome().to_string(),
                kind: caixa.kind(),
                slots: foreign_code_slots.join(" "),
            });
        }

        // Per-entry path-shape gate on the three Caixa-level code-surface
        // path lists (`:bibliotecas`, `:exe`, `:servicos`): each entry must
        // be non-empty, relative, and free of `..` components — the same
        // [`crate::render::is_sandboxed_relative_path`] discipline the
        // peer `:behavior :on-*` (b0c8389) and
        // `:upgrade-from :state-change :script` (26da2c7) axes already
        // route through. Runs *after* the kind-coherence gates above (so
        // a `:exe` on a Servico surfaces ForeignCodeSlot rather than a
        // per-entry shape diagnostic, and a Supervisor/Aplicacao with any
        // code surface surfaces OwnCode first) and *before* the existence
        // loops below (so an empty / absolute / parent-escaping entry
        // surfaces its self-locating per-slot diagnostic rather than a
        // downstream `MissingEntry` / `ExeOutsideDir` /
        // `ServicoOutsideDir` against the resolved sandbox-escape path).
        caixa
            .validate_code_paths()
            .map_err(|err| LayoutError::CodePathViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;

        if caixa.kind().requires_lib() && caixa.bibliotecas().is_empty() {
            let expected = root
                .join(crate::render::LAYOUT_DIR_LIB)
                .join(format!("{}.lisp", caixa.nome()));
            if !self.exists(&expected) {
                return Err(LayoutError::MissingLib {
                    caixa: caixa.nome().to_string(),
                    expected,
                });
            }
        }

        if caixa.kind().requires_exe() && caixa.exe().is_empty() {
            return Err(LayoutError::BinarioWithoutExe(caixa.nome().to_string()));
        }

        if caixa.kind().requires_servicos() && caixa.servicos().is_empty() {
            return Err(LayoutError::ServicoWithoutServicos(
                caixa.nome().to_string(),
            ));
        }

        // Required-slot gate on the fifth [`CaixaKind`] arm — mirror of
        // the `BinarioWithoutExe` / `ServicoWithoutServicos` pair above.
        // An `Acao`'s sole payload is its `:ci` slot; an `Acao` caixa
        // that doesn't declare one has no CI run to decompose or
        // validate, so `feira build` refuses it here rather than
        // letting a downstream `caixa-actions::validate` call fail with
        // a less-helpful "no :ci" surprise far from the source
        // caixa.lisp.
        if caixa.kind().requires_ci() && caixa.ci().is_none() {
            return Err(LayoutError::MissingCi(caixa.nome().to_string()));
        }

        for p in caixa.bibliotecas() {
            let full = root.join(p);
            if !self.exists(&full) {
                return Err(LayoutError::MissingEntry {
                    kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
                    path: full,
                });
            }
        }

        let exe_dir = root.join(crate::render::LAYOUT_DIR_EXE);
        for p in caixa.exe() {
            let full = root.join(p);
            if !self.exists(&full) {
                return Err(LayoutError::MissingEntry {
                    kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
                    path: full,
                });
            }
            if !full.starts_with(&exe_dir) {
                return Err(LayoutError::ExeOutsideDir(full));
            }
        }

        let servicos_dir = root.join(crate::render::LAYOUT_DIR_SERVICOS);
        for p in caixa.servicos() {
            let full = root.join(p);
            if !self.exists(&full) {
                return Err(LayoutError::MissingEntry {
                    kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
                    path: full,
                });
            }
            if !full.starts_with(&servicos_dir) {
                return Err(LayoutError::ServicoOutsideDir(full));
            }
        }

        // ── M2 typed-substrate invariants ────────────────────────────────

        // Lunatic-style per-process limits: every declared axis must
        // be meaningfully non-zero. A zero on any axis is the same
        // authorial-intent footgun as a 0-failure circuit-breaker or
        // a 0-port :entrada — wasmtime would consume the value as
        // "trap immediately" rather than the author's "an unspecified
        // bound". See `LimitsSpec::validate` for the full rationale.
        if let Some(l) = caixa.limits() {
            l.validate().map_err(|err| LayoutError::LimitsViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;
        }

        // Behavior callbacks: every declared callback must (a) be
        // value-shape valid (no empty / absolute / parent-escaping
        // path values that would silently subvert the layout
        // checker's `root.join(p)` sandbox), then (b) resolve on disk.
        // The shape pass runs first so the diagnostic names *which
        // :behavior slot* is malformed before the existence check
        // would otherwise surface a less-helpful "missing entry".
        if let Some(b) = caixa.behavior() {
            b.validate().map_err(|err| LayoutError::BehaviorViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;
            for p in b.declared_paths() {
                let full = root.join(p);
                if !self.exists(&full) {
                    return Err(LayoutError::MissingEntry {
                        kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
                        path: full,
                    });
                }
            }
        }

        // Upgrade-from entries: every entry's typed shape must hold
        // (`:from` is a valid semver; every instruction's `:module`
        // is a DNS-1123 label; every `:state-change :script` is
        // non-empty / relative / parent-escape-free) AND the
        // graph-edge-set invariant on the `:from` axis (at most one
        // entry per parsed semver — OTP appup picks at most one
        // matching block per running version, so two entries with the
        // same `:from` are an ambiguous edge), BEFORE the existing
        // path-existence pass runs, so the diagnostic names *which
        // slot* is malformed rather than the less-helpful "missing
        // upgrade-script" (which doesn't fire for non-script axes at
        // all). Mirrors the b0c8389 `BehaviorSpec::validate` wiring on
        // the peer M2 typed slot: the validate pass on the typed value
        // happens first, the on-disk path-existence pass happens
        // second.
        //
        // The duplicate-`:from` arm of [`validate_upgrade_from`]
        // closes the typed-graph-set invariant on the fifth axis to
        // get this discipline — `:children :caixa` (dbf50a9),
        // `:membros :caixa` (4bb3f3d), `:contratos` (5dbcfaf),
        // `:placement :clusters` (c7c7799), `:entrada :paths`
        // (eb3456d) are the prior four. Without it a caixa.lisp with
        // two `(:from "0.1.0" …)` blocks silently passed `feira
        // build` and the wasm-operator picked either set non-
        // deterministically at hot-upgrade time, far from the source.
        //
        // 26da2c7 closed the per-entry validate gap; this commit closes
        // the cross-entry one on the same wiring site.
        crate::upgrade::validate_upgrade_from(caixa.upgrade_from()).map_err(|err| {
            LayoutError::UpgradeViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            }
        })?;
        // Cross-slot precedence gate: every `:upgrade-from :from` must
        // be strictly less than the caixa's own `:versao` under
        // SemVer-2 precedence. An upgrade block whose `:from` is
        // greater than or equal to `:versao` is structurally
        // unreachable by the wasm-operator's `:from`-match dispatch
        // (the operator loads the current `:versao` and matches the
        // *running* version against each entry's `:from`; an entry
        // whose `:from >= :versao` is never reached because the
        // operator never runs a version >= the current one that it
        // could then upgrade *to* the current one).
        //
        // Same cross-slot value-shape discipline as the typed
        // `:placement` strategy ↔ `:shard-key` partition (934bc58):
        // one slot's value constrains the valid set of another's, and
        // the constraint becomes a structural property visible at
        // validate time. Runs *after* the per-entry shape pass + the
        // cross-entry duplicate gate so the precedence diagnostic
        // fires on already-parseable `:from`/`:versao` values (a
        // malformed `:from` surfaces as `FromInvalid` first; a
        // malformed `:versao` falls through silently here and is
        // gated by the narrower `ManifestError::VersaoInvalid` arm
        // at its load-bearing call site). Mirrors the
        // arm-ordering posture every peer cross-axis gate uses
        // (`*_invalid_fires_before_duplicate_check` /
        // `*_takes_precedence_over_*` pins on every typed-graph axis).
        crate::upgrade::validate_upgrade_from_against_versao(caixa.upgrade_from(), caixa.versao())
            .map_err(|err| LayoutError::UpgradeViolation {
                caixa: caixa.nome().to_string(),
                issue: err.to_string(),
            })?;
        // Cross-slot composition gate: every `:upgrade-from` entry whose
        // `:instructions` list carries a `(:state-change …)` instruction
        // must also have `:behavior :on-state-change` declared on the
        // same caixa. The per-version migration script is the
        // `gen_server:code_change/3` analog and the runtime hook it is
        // delivered through during hot upgrade is the `:on-state-change`
        // callback (upgrade.rs module doc verbatim: "Composes with the
        // `:behavior :on-state-change` callback to deliver state
        // migration during hot upgrades"; behavior.rs module doc on
        // `:on-state-change` mirrors the promise from the callback side
        // — "Composes with the `:upgrade-from` slot declared at the
        // Caixa root"). Without the callback the per-version script has
        // no runtime delivery path and the operator's hot-upgrade
        // dispatch either fails the upgrade mid-flight or silently
        // skips the migration, far from the source caixa.lisp.
        //
        // Same cross-slot value-shape discipline as the peer
        // `validate_upgrade_from_against_versao` gate at this wire-up
        // site (the `:from` ↔ `:versao` precedence partition) and the
        // typed `:placement` strategy ↔ `:shard-key` partition
        // (934bc58): one slot's value constrains the valid set of
        // another's, and the constraint becomes a structural property
        // visible at validate time. Runs *after*
        // `validate_upgrade_from_against_versao` (and therefore after
        // `validate_upgrade_from` and `BehaviorSpec::validate`) so
        // narrower per-entry / per-callback diagnostics surface first;
        // a `:state-change` instruction with a malformed `:script`
        // (EmptyScript, AbsoluteScript, ParentEscapeScript) lands on
        // its narrower per-instruction-shape diagnostic before the
        // missing-callback gate fires.
        crate::upgrade::validate_upgrade_from_against_behavior(
            caixa.upgrade_from(),
            caixa.behavior(),
        )
        .map_err(|err| LayoutError::UpgradeViolation {
            caixa: caixa.nome().to_string(),
            issue: err.to_string(),
        })?;
        for entry in caixa.upgrade_from() {
            for instr in entry.instructions() {
                if let Some(p) = instr.declared_path() {
                    let full = root.join(p);
                    if !self.exists(&full) {
                        return Err(LayoutError::MissingEntry {
                            kind: crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
                            path: full,
                        });
                    }
                }
            }
        }

        // Supervisor invariants (typed shape — children, restart strategy).
        // The "supervisor doesn't own code" check is at the top of verify()
        // so it fires before the existence-check loops.
        if caixa.kind().is_supervisor() {
            // Raw `:restart-window` parse gate on the flat
            // `Caixa::restart_window: Option<String>` axis — the last
            // orphan-validator on the typed Caixa surface flagged by the
            // [`Self::validate_deps`] wire-up's closing comment (the
            // "Supervisor-axis specific" remainder) and the
            // [`Caixa::supervisor_view`] doc-comment's "the future
            // layout-side wire-up" pin. Until this gate landed
            // [`Caixa::validate_restart_window`] existed as `pub fn` on
            // [`Caixa`] with full per-arm unit coverage in `manifest::tests`
            // (`validate_restart_window_rejects_*` — fractional seconds,
            // decimal-shaped integer, half-unit minute, leading sign,
            // unknown unit, garbage, empty-after-trim; eight rejection
            // arms total), but no production code path called it —
            // `feira build` (the canonical author-time gate; routes
            // through [`StandardLayout::verify`]) silently accepted a
            // malformed `:restart-window` and [`Caixa::supervisor_view`]
            // soft-swallowed the parse failure as `restart_window: None`
            // (i.e. the canonical "omit the slot to express no reset"
            // sentinel), turning every malformed window into a never-reset
            // supervisor far from the source `caixa.lisp`, with no field
            // naming the offending `:restart-window`. The Erlang/OTP
            // `MaxIntensity / Period` invariant the typed [`SupervisorSpec`]
            // gate (`view.validate()` immediately below) enforces on the
            // `Option<Duration>` value never reached the gate at all on
            // these inputs: the parse error was already laundered to
            // `None`, and `None` is the canonical "never reset" shape
            // that always validates cleanly. Lifting the parse gate to
            // the layout-pipeline wire-up closes the laundering — every
            // value past this gate either parses through the shared
            // `crate::supervisor::duration_codec::parse` (and therefore
            // round-trips canonically) or fires the new
            // [`Self::RestartWindowViolation`] envelope at the source.
            //
            // Runs *inside* the `kind == Supervisor` branch (rather than
            // alongside the peer flat-Caixa gates `validate_nome` /
            // `validate_versao` / `validate_deps` / `validate_code_paths`
            // above the kind dispatch) because `:restart-window` is in
            // the Supervisor slot set per [`Caixa::declared_supervisor_slots`]
            // — every non-Supervisor caixa with `:restart-window` set
            // already errors upstream via the
            // [`Self::SupervisorSlotsOnNonSupervisor`] kind-coherence gate
            // (line 243-252), so reaching this gate on a non-Supervisor
            // kind would be a no-op (the field is `None` by construction).
            // Runs *before* `view.validate()` so the parse-side diagnostic
            // surfaces first on the raw-string axis — a `:restart-window
            // "1.5s"` lands on the more self-locating
            // `RestartWindowViolation` (which names the offending raw
            // string verbatim) rather than the laundered-to-`None`
            // soft-pass that the typed view would silently let through.
            //
            // Same per-axis `*Violation { caixa, issue }` envelope every
            // peer flat-Caixa wrap exposes ([`Self::NomeViolation`] /
            // [`Self::VersaoViolation`] 1f74a5f,
            // [`Self::DepsViolation`] aa77d0f, [`Self::CodePathViolation`]
            // b868442). Threads [`ManifestError::RestartWindowMalformed`]
            // Display through verbatim — the per-arm reason already names
            // the offending raw value (e.g. `":restart-window \"1.5s\" is
            // not a canonical duration: …"`), so the wrap's `issue`
            // carries a self-locating "which axis, which value, why"
            // without re-shaping the parser-side reason.
            caixa
                .validate_restart_window()
                .map_err(|err| LayoutError::RestartWindowViolation {
                    caixa: caixa.nome().to_string(),
                    issue: err.to_string(),
                })?;
            let view = caixa
                .supervisor_view()
                .expect("Supervisor kind must have a supervisor_view");
            view.validate()
                .map_err(|err| LayoutError::SupervisorViolation {
                    caixa: caixa.nome().to_string(),
                    issue: err.to_string(),
                })?;
            // Cross-slot coherence: `:children :caixa` must not name the
            // supervisor's own `:nome`. The typed `SupervisorSpec` view
            // carries the children but not the parent `:nome`, so this
            // self-parent gate reads one slot against another here, the
            // same wire-up shape `validate_upgrade_from_against_versao`
            // uses for the `:from`/`:versao` precedence gate. Runs after
            // `view.validate()` so the per-child shape + duplicate
            // diagnostics surface first; a self-referential child is
            // always a valid DNS-1123 label (it equals the already-valid
            // `:nome`), so this ordering never masks a narrower defect.
            //
            // Routes the `parent_nome` arg through the typed
            // [`Caixa::nome`] accessor (`caixa.nome()`) rather than
            // the raw `&caixa.nome` `&String`-borrow of the underlying
            // field — same one-typed-dispatch-per-`:nome`-consumer
            // discipline the sibling caixa-mesh (980c059) / caixa-helm
            // (22461ef) / caixa-flux (162e2e2) / caixa-crd (61d3429) /
            // caixa-feira (ef83332) `caixa.nome`-arg raw-borrow converges
            // established on the peer renderer / CR-materializer / CLI
            // crates, extended here onto the substrate's own
            // [`LayoutInvariants::verify`] cross-slot self-edge gate
            // wire-up on the supervisor-tree kind arm — the
            // [`crate::supervisor::validate_no_self_supervision`] helper
            // accepts `parent_nome: &str`, so the accessor's `&str`
            // return threads through without an intermediate deref-
            // coerce, closing the raw `&caixa.nome` arg-passing axis at
            // this call site.
            crate::supervisor::validate_no_self_supervision(caixa.children(), caixa.nome())
                .map_err(|err| LayoutError::SupervisorViolation {
                    caixa: caixa.nome().to_string(),
                    issue: err.to_string(),
                })?;
        }

        // Aplicacao invariants — typed graph composition. Like
        // Supervisor, an Aplicacao runs no code itself.
        if caixa.kind().is_aplicacao() {
            let view = caixa
                .aplicacao_view()
                .expect("Aplicacao kind must have an aplicacao_view");
            view.validate()
                .map_err(|err| LayoutError::AplicacaoViolation {
                    caixa: caixa.nome().to_string(),
                    issue: err.to_string(),
                })?;
            // Cross-slot coherence: `:membros :caixa` must not name the
            // Aplicacao's own `:nome`. The typed `AplicacaoSpec` view
            // carries the membros but not the parent `:nome`, so this
            // self-edge gate reads one slot against another here, the
            // same wire-up shape `crate::supervisor::validate_no_self_supervision`
            // (ad4abf1) uses on the peer supervision-tree axis. Runs
            // after `view.validate()` so the per-member shape +
            // duplicate diagnostics surface first; a self-referential
            // member is always a valid DNS-1123 label (it equals the
            // already-valid `:nome`), so this ordering never masks a
            // narrower defect. Because `:contratos` `:de`/`:para` and
            // `:entrada :para` are already required to be members of
            // `:membros`, this single gate also transitively closes
            // those two axes — every validated `:contratos` edge and
            // every validated `:entrada :para` cannot name the
            // Aplicacao itself, without re-deriving the partition.
            //
            // Routes the `parent_nome` arg through the typed
            // [`Caixa::nome`] accessor (`caixa.nome()`) rather than
            // the raw `&caixa.nome` `&String`-borrow of the underlying
            // field — peer of the sibling supervision-tree-arm
            // [`crate::supervisor::validate_no_self_supervision`] arg
            // converge immediately above on the same
            // [`LayoutInvariants::verify`] cross-slot self-edge gate
            // wire-up, extended here onto the Aplicacao-kind arm. Both
            // per-kind arms now key off exactly one typed dispatch on
            // the substrate primitive for the parent-`:nome` self-edge
            // arg, closing the raw `&caixa.nome` arg-passing axis on
            // the cross-slot self-edge gate wire-up across both
            // typed-name-graph kinds ([`crate::supervisor::validate_no_self_supervision`]
            // on the supervision tree, this call on the Aplicacao
            // graph). The [`crate::aplicacao::validate_no_self_membership`]
            // helper accepts `parent_nome: &str`, so the accessor's
            // `&str` return threads through without an intermediate
            // deref-coerce.
            crate::aplicacao::validate_no_self_membership(caixa.membros(), caixa.nome()).map_err(
                |err| LayoutError::AplicacaoViolation {
                    caixa: caixa.nome().to_string(),
                    issue: err.to_string(),
                },
            )?;
        }

        Ok(())
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum LayoutError {
    #[error("manifest missing: {}", .0.display())]
    MissingManifest(PathBuf),
    #[error("caixa '{caixa}' is a Biblioteca but has no lib entry — expected {}", expected.display())]
    MissingLib { caixa: String, expected: PathBuf },
    #[error("caixa '{0}' is a Binario but has no :exe entries")]
    BinarioWithoutExe(String),
    #[error("caixa '{0}' is a Servico but has no :servicos entries")]
    ServicoWithoutServicos(String),
    #[error("declared {kind} entry missing: {}", path.display())]
    MissingEntry { kind: &'static str, path: PathBuf },
    #[error("exe entry outside exe/ directory: {}", .0.display())]
    ExeOutsideDir(PathBuf),
    #[error("servico entry outside servicos/ directory: {}", .0.display())]
    ServicoOutsideDir(PathBuf),
    #[error("caixa '{caixa}' has invalid :nome: {issue}")]
    NomeViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :versao: {issue}")]
    VersaoViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :deps / :deps-dev entry: {issue}")]
    DepsViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :etiquetas entry: {issue}")]
    EtiquetasViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :autores entry: {issue}")]
    AutoresViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :repositorio: {issue}")]
    RepositorioViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :descricao: {issue}")]
    DescricaoViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :licenca: {issue}")]
    LicencaViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :edicao: {issue}")]
    EdicaoViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid code-path entry: {issue}")]
    CodePathViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :limits: {issue}")]
    LimitsViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :behavior callback: {issue}")]
    BehaviorViolation { caixa: String, issue: String },
    #[error("caixa '{caixa}' has invalid :upgrade-from entry: {issue}")]
    UpgradeViolation { caixa: String, issue: String },
    #[error("supervisor caixa '{caixa}' violates typed shape: {issue}")]
    SupervisorViolation { caixa: String, issue: String },
    #[error("supervisor caixa '{caixa}' has invalid :restart-window: {issue}")]
    RestartWindowViolation { caixa: String, issue: String },
    #[error(
        "supervisor caixa '{0}' must not declare :bibliotecas, :exe, or :servicos — supervisors don't run code, they orchestrate other caixas"
    )]
    SupervisorOwnsCode(String),
    #[error("aplicacao caixa '{caixa}' violates typed shape: {issue}")]
    AplicacaoViolation { caixa: String, issue: String },
    #[error(
        "aplicacao caixa '{0}' must not declare :bibliotecas, :exe, or :servicos — aplicacaos compose Servicos, they don't run code themselves"
    )]
    AplicacaoOwnsCode(String),
    #[error(
        "acao caixa '{0}' must not declare :bibliotecas, :exe, or :servicos — acaos carry a typed CI run (:ci), they don't run code themselves"
    )]
    AcaoOwnsCode(String),
    #[error(
        "caixa '{caixa}' is :kind {kind:?} but declares Aplicacao-only mesh slot(s): {slots} — \
         :membros / :contratos / :politicas / :placement / :entrada compose a :kind Aplicacao's \
         typed graph (MESH-COMPOSITION §III.1) and are silently ignored on every other kind \
         (never validated, never rendered); move them to a :kind Aplicacao caixa or remove them"
    )]
    MeshSlotsOnNonAplicacao {
        caixa: String,
        kind: CaixaKind,
        slots: String,
    },
    #[error(
        "caixa '{caixa}' is :kind {kind:?} but declares Supervisor-only slot(s): {slots} — \
         :estrategia / :max-restarts / :restart-window / :children compose a :kind Supervisor's \
         typed OTP supervisor (INSPIRATIONS §II.2) and are silently ignored on every other kind \
         (never validated, never reconciled); move them to a :kind Supervisor caixa or remove them"
    )]
    SupervisorSlotsOnNonSupervisor {
        caixa: String,
        kind: CaixaKind,
        slots: String,
    },
    #[error(
        "caixa '{caixa}' is :kind {kind:?} but declares Servico-only slot(s): {slots} — \
         :limits / :behavior / :upgrade-from configure the runtime of a long-running :kind Servico \
         wasm component (INSPIRATIONS §III.1 / §II.3 / §II.4) and are silently ignored on every \
         other kind (never rendered into a chart or programs.yaml entry); move them to a :kind \
         Servico caixa or remove them"
    )]
    ServicoSlotsOnNonServico {
        caixa: String,
        kind: CaixaKind,
        slots: String,
    },
    #[error(
        "caixa '{caixa}' is :kind {kind:?} but declares foreign code-surface slot(s): {slots} — \
         :exe is the nix-built executable surface owned only by :kind Binario, :servicos is the \
         wasm-component + ComputeUnit daemon surface owned only by :kind Servico; \
         caixa-helm / caixa-flux / caixa-flake gate emission on `require_kind(_, <owning-kind>)`, \
         so a declared :exe / :servicos on the wrong code-running kind is silently ignored — the \
         path is validated by the layout's path-existence loops but never rendered into a build \
         target or programs.yaml entry. Move the slot to its owning kind, change :kind to match \
         (Binario for :exe, Servico for :servicos), or drop the slot entirely"
    )]
    ForeignCodeSlot {
        caixa: String,
        kind: CaixaKind,
        slots: String,
    },
    #[error("caixa '{0}' is an Acao but has no :ci slot")]
    MissingCi(String),
    #[error(
        "caixa '{caixa}' is :kind {kind:?} but declares the Acao-only :ci slot — \
         :ci carries a typed CI run (canteiro_types::CiRun, CANTEIRO §7.1-C) that only the \
         caixa-actions renderer validates for :kind Acao, and is silently ignored on every \
         other kind (never decomposed, never rendered); move it to a :kind Acao caixa or \
         remove it"
    )]
    CiOnNonAcao { caixa: String, kind: CaixaKind },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Caixa, CaixaKind};
    use std::path::PathBuf;

    fn caixa(kind: CaixaKind) -> Caixa {
        Caixa {
            nome: "demo".into(),
            versao: "0.1.0".into(),
            kind,
            edicao: None,
            descricao: None,
            repositorio: None,
            licenca: None,
            autores: vec![],
            etiquetas: vec![],
            deps: vec![],
            deps_dev: vec![],
            exe: vec![],
            bibliotecas: vec![],
            servicos: vec![],
            // M2 typed-substrate slots default to absent.
            limits: None,
            behavior: None,
            upgrade_from: vec![],
            estrategia: None,
            max_restarts: None,
            restart_window: None,
            children: vec![],
            // M3 Aplicacao slots default to absent.
            membros: vec![],
            contratos: vec![],
            politicas: None,
            placement: None,
            entrada: None,
            ci: None,
        }
    }

    #[test]
    fn missing_manifest_errors() {
        let layout = StandardLayout::new().with_path_exists(|_| false);
        let err = layout
            .verify(&caixa(CaixaKind::Biblioteca), Path::new("/tmp/x"))
            .unwrap_err();
        assert!(matches!(err, LayoutError::MissingManifest(_)));
    }

    #[test]
    fn biblioteca_needs_default_lib_path() {
        let root = PathBuf::from("/tmp/x");
        let expect_manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == expect_manifest);
        let err = layout
            .verify(&caixa(CaixaKind::Biblioteca), &root)
            .unwrap_err();
        assert!(matches!(err, LayoutError::MissingLib { .. }));
    }

    #[test]
    fn biblioteca_passes_when_default_lib_exists() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        layout
            .verify(&caixa(CaixaKind::Biblioteca), &root)
            .expect("should pass");
    }

    #[test]
    fn binario_without_exe_errors() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let err = layout
            .verify(&caixa(CaixaKind::Binario), &root)
            .unwrap_err();
        assert!(matches!(err, LayoutError::BinarioWithoutExe(_)));
    }

    #[test]
    fn exe_outside_dir_errors() {
        // A relative entry that lives under the caixa root but *not*
        // under `exe/` — the canonical case the `starts_with(exe_dir)`
        // fence catches. The prior parent-escape shape this test used
        // (`"../sibling/tool"`) is now caught at validate time by
        // [`Caixa::validate_code_paths`] with the narrower
        // [`crate::ManifestError::CodePathParentEscape`] diagnostic
        // (see the layout-level integration pin
        // `code_path_violation_on_parent_escape_fires_before_existence_check`),
        // so this fence pin uses a non-`..` non-absolute shape outside
        // `exe/` to preserve coverage of the ExeOutsideDir surface.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let outside = root.join("lib/tool");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == outside);
        let mut c = caixa(CaixaKind::Binario);
        c.exe = vec!["lib/tool".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::ExeOutsideDir(_)));
    }

    // ── code-path shape gate (lifted to layout-level verify) ─────────────

    #[test]
    fn code_path_violation_on_empty_bibliotecas_entry() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.bibliotecas = vec!["".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        // The wire-up wraps `ManifestError` Display into the
        // CodePathViolation envelope (peer of LimitsViolation /
        // BehaviorViolation / UpgradeViolation), so the issue string
        // names the offending slot at the source.
        let LayoutError::CodePathViolation { caixa, issue } = err else {
            panic!("expected LayoutError::CodePathViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":bibliotecas"),
            "issue must name the offending slot: {issue}",
        );
    }

    #[test]
    fn code_path_violation_on_absolute_servicos_entry() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["/etc/servicos/escape.yaml".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::CodePathViolation { caixa, issue } = err else {
            panic!("expected LayoutError::CodePathViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":servicos"),
            "issue must name the offending slot: {issue}",
        );
        assert!(
            issue.contains("/etc/servicos/escape.yaml"),
            "issue must quote the offending path: {issue}",
        );
    }

    #[test]
    fn code_path_violation_on_parent_escape_fires_before_existence_check() {
        // The new gate runs BEFORE the existence loops, so a
        // parent-escaping `:exe` entry surfaces CodePathViolation
        // (naming `:exe` at the source) rather than the downstream
        // ExeOutsideDir / MissingEntry against the resolved sandbox-
        // escape path. Even if the resolved escape target exists
        // on disk (which we simulate here by claiming it does), the
        // shape diagnostic wins.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let resolved_escape = root.join("exe/../../escape.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == resolved_escape);
        let mut c = caixa(CaixaKind::Binario);
        c.exe = vec!["exe/../../escape.lisp".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::CodePathViolation { caixa, issue } = err else {
            panic!("expected LayoutError::CodePathViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":exe"),
            "issue must name the offending slot: {issue}",
        );
    }

    // ── etiquetas universal-axis gate wired into verify ─────────────────
    //
    // Pins the layout-pipeline wire-up of [`Caixa::validate_etiquetas`]:
    // the fourth universal-axis Caixa-level value-shape gate (peer of
    // `validate_nome` / `validate_versao` / `validate_deps` /
    // `validate_code_paths`), wired before the kind-coherence gates so
    // a structurally-invalid `:etiquetas` entry on any kind surfaces
    // the per-axis `EtiquetasViolation { caixa, issue }` envelope at
    // the source rather than silently rendering as `keywords: [""]`
    // in `Chart.yaml` (Servico kind, via caixa-helm's `BTreeSet`
    // collect) or silently dedup'ing at chart render (every kind).
    // Until this wire-up landed `:etiquetas` had no shape gate at any
    // layer — the registry-search-tag axis was the largest universal
    // authoring surface on the typed Caixa surface with no validate
    // discipline.
    //
    // Same per-axis `*Violation { caixa, issue }` envelope every peer
    // per-axis wrap exposes; the wire-up runs after `validate_deps`
    // (universal axis ordering: `:nome` → `:versao` → `:deps` →
    // `:etiquetas`) and before every kind-coherence gate
    // (`:etiquetas` is universal so its shape diagnostic is more
    // fundamental than the partition-on-kind diagnostics).

    #[test]
    fn etiquetas_violation_on_empty_entry() {
        // Canonical paste-from-blank-doc footgun on every kind. The
        // wrap envelope wraps [`ManifestError::EtiquetaEmpty`]'s
        // Display through verbatim, so the issue string names the
        // offending `:etiquetas` axis at the source — the author can
        // grep their caixa.lisp for `:etiquetas` and fix the empty
        // entry in one edit. Mirrors the peer
        // `code_path_violation_on_empty_bibliotecas_entry` shape
        // (b868442) on the `:bibliotecas` axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.etiquetas = vec!["".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::EtiquetasViolation { caixa, issue } = err else {
            panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":etiquetas"),
            "issue must name the offending slot: {issue}",
        );
    }

    #[test]
    fn etiquetas_violation_on_duplicate_entry() {
        // Canonical copy-paste-the-wrong-tag footgun. Without the wire-
        // up the duplicate was silently dedup'd by caixa-helm's
        // `BTreeSet` collect at chart render — a "second wins / one
        // silently disappears" shape. The wrap envelope names the
        // offending tag verbatim through the inner
        // [`ManifestError::EtiquetaDuplicate`]'s Display.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.etiquetas = vec!["demo".into(), "demo".into()];
        // The servicos path doesn't exist in this fixture, but the
        // `:etiquetas` gate fires before the existence loop (universal
        // axis dominates kind-specific existence checks). Wire is
        // intact iff the wrap envelope surfaces first.
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::EtiquetasViolation { caixa, issue } = err else {
            panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("demo"),
            "issue must quote the offending tag: {issue}",
        );
    }

    #[test]
    fn etiquetas_violation_fires_before_kind_coherence_mesh_slot() {
        // Cross-axis precedence pin: a Biblioteca with malformed
        // `:etiquetas` *and* declared mesh slots (`:membros`) surfaces
        // the universal `:etiquetas` diagnostic first, not the
        // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
        // `:etiquetas` is universal (every kind owns the slot), so its
        // shape diagnostic is more fundamental than the partition-on-
        // kind diagnostic. Mirrors the peer
        // `deps_violation_fires_before_*` precedence pins (aa77d0f) on
        // the universal `:deps` axis vs the same kind-coherence gates.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.etiquetas = vec!["".into()];
        c.membros = vec![crate::aplicacao::Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::EtiquetasViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn etiquetas_violation_fires_after_deps_violation() {
        // Cross-axis precedence pin (inside the universal-axis trio):
        // a caixa with both a malformed `:deps` entry *and* a malformed
        // `:etiquetas` entry surfaces `DepsViolation` first — `:deps`
        // is the third universal axis in declaration order
        // (`:nome` → `:versao` → `:deps` → `:etiquetas`) and runs first
        // in `verify`. Mirrors the peer
        // `nome_violation_fires_before_versao_violation` shape on the
        // identity-axis pair.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![crate::Dep::simple("Caixa-Teia", "^0.1")]; // uppercase :nome
        c.etiquetas = vec!["".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::DepsViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn etiquetas_violation_accepts_canonical_template() {
        // Positive control sanity pin: the canonical `Caixa::template`
        // shape (`:etiquetas ()` — empty list) passes the gate
        // trivially. Mirrors the peer
        // `validate_code_paths_accepts_canonical_template` pin.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let c = caixa(CaixaKind::Biblioteca);
        layout.verify(&c, &root).expect("template must pass");
    }

    #[test]
    fn etiquetas_violation_on_non_chart_keyword_shape() {
        // Canonical CSV-list-separator-confusion footgun: the author
        // confused the CSV-style separator with the `:etiquetas` list
        // grammar. The shape gate fires past the empty + duplicate
        // arms via [`Caixa::validate_etiquetas`]'s new
        // `is_chart_keyword_shape` cascade, and the layout envelope
        // wraps [`ManifestError::EtiquetaInvalid`]'s Display through
        // verbatim — the issue string names both the offending slot
        // and the offending value (debug-escaped). Peer with the
        // `autores_violation_on_non_chart_maintainer_shape` pin on
        // the sibling universal-axis `Vec<String>` surface — the
        // second layout pin on the Vec<String> per-entry shape
        // cascade.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.etiquetas = vec!["mesh,http,grpc".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::EtiquetasViolation { caixa, issue } = err else {
            panic!("expected LayoutError::EtiquetasViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":etiquetas"),
            "issue must name the offending slot: {issue}",
        );
        assert!(
            issue.contains("mesh,http,grpc"),
            "issue must quote the offending value: {issue}",
        );
    }

    // ── autores universal-axis gate wired into verify ───────────────────
    //
    // Pins the layout-pipeline wire-up of [`Caixa::validate_autores`]:
    // the fifth universal-axis Caixa-level value-shape gate (peer of
    // `validate_nome` / `validate_versao` / `validate_deps` /
    // `validate_etiquetas` / `validate_code_paths`), wired immediately
    // after `validate_etiquetas` so the two Vec-shaped universal
    // metadata axes sit adjacent in the cascade. Until this wire-up
    // landed `:autores` had no shape gate at any layer — the
    // maintainer-axis was the second largest universal authoring
    // surface on the typed Caixa surface with no validate discipline,
    // and unlike `:etiquetas` (caixa-helm dedups the rendered
    // `keywords:` array via `BTreeSet` collect at chart render),
    // `maintainers:` has *no* renderer-side dedup, so duplicate
    // `:autores` entries render verbatim as two identical
    // `Maintainer { name, email: None }` records — a strictly worse
    // footgun than the peer `:etiquetas` shape.

    #[test]
    fn autores_violation_on_empty_entry() {
        // Canonical paste-from-blank-doc footgun on every kind. The
        // wrap envelope wraps [`ManifestError::AutorEmpty`]'s Display
        // through verbatim, so the issue string names the offending
        // `:autores` axis at the source — the author can grep their
        // caixa.lisp for `:autores` and fix the empty entry in one
        // edit. Mirrors the peer `etiquetas_violation_on_empty_entry`
        // shape (360a499) on the `:etiquetas` axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.autores = vec!["".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::AutoresViolation { caixa, issue } = err else {
            panic!("expected LayoutError::AutoresViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":autores"),
            "issue must name the offending slot: {issue}",
        );
    }

    #[test]
    fn autores_violation_on_duplicate_entry() {
        // Canonical copy-paste-the-wrong-author footgun. Unlike the
        // peer `:etiquetas` axis (silently dedup'd by caixa-helm's
        // `BTreeSet` collect at chart render), `:autores` duplicates
        // stack verbatim in the rendered `maintainers:` — the gate
        // closes the footgun at validate time before any renderer
        // sees it. The wrap envelope names the offending author
        // verbatim through the inner [`ManifestError::AutorDuplicate`]'s
        // Display.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.autores = vec!["pleme-io".into(), "pleme-io".into()];
        // The servicos path doesn't exist in this fixture, but the
        // `:autores` gate fires before the existence loop (universal
        // axis dominates kind-specific existence checks). Wire is
        // intact iff the wrap envelope surfaces first.
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::AutoresViolation { caixa, issue } = err else {
            panic!("expected LayoutError::AutoresViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("pleme-io"),
            "issue must quote the offending author: {issue}",
        );
    }

    #[test]
    fn autores_violation_fires_before_kind_coherence_mesh_slot() {
        // Cross-axis precedence pin: a Biblioteca with malformed
        // `:autores` *and* declared mesh slots (`:membros`) surfaces
        // the universal `:autores` diagnostic first, not the
        // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
        // `:autores` is universal (every kind owns the slot), so its
        // shape diagnostic is more fundamental than the partition-on-
        // kind diagnostic. Mirrors the peer
        // `etiquetas_violation_fires_before_kind_coherence_mesh_slot`
        // pin (360a499) on the `:etiquetas` axis vs the same kind-
        // coherence gates.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.autores = vec!["".into()];
        c.membros = vec![crate::aplicacao::Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::AutoresViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn autores_violation_fires_after_etiquetas_violation() {
        // Cross-axis precedence pin (inside the Vec-shaped universal
        // metadata pair): a caixa with both a malformed `:etiquetas`
        // entry *and* a malformed `:autores` entry surfaces
        // `EtiquetasViolation` first — `:etiquetas` is the fourth
        // universal axis in the cascade and runs before `:autores`,
        // peer with the canonical identity-axis-first cascade the
        // peer gates establish. Mirrors the peer
        // `etiquetas_violation_fires_after_deps_violation` precedence
        // pin (360a499) on the dep-axis-before-tag-axis pair.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.etiquetas = vec!["".into()];
        c.autores = vec!["".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::EtiquetasViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn autores_violation_accepts_canonical_template() {
        // Positive control sanity pin: the canonical `Caixa::template`
        // shape (`:autores ()` — empty list) passes the gate trivially.
        // Mirrors the peer `etiquetas_violation_accepts_canonical_template`
        // pin (360a499).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let c = caixa(CaixaKind::Biblioteca);
        layout.verify(&c, &root).expect("template must pass");
    }

    #[test]
    fn autores_violation_on_non_chart_maintainer_shape() {
        // Canonical paste-from-multiline-doc footgun: the author
        // pasted a multi-line block of author records into one
        // `:autores` entry instead of splitting into one entry per
        // author. The shape gate fires past the empty + duplicate arms
        // via [`Caixa::validate_autores`]'s new
        // `is_chart_maintainer_name_shape` cascade, and the layout
        // envelope wraps [`ManifestError::AutorInvalid`]'s Display
        // through verbatim — the issue string names both the offending
        // slot and the offending value (debug-escaped). Peer with the
        // `descricao_violation_on_non_chart_shape` pin on the sibling
        // universal-axis `Option<String>` surface and the
        // `licenca_violation_on_non_spdx_shape` /
        // `edicao_violation_on_non_year_shape` peers — and the first
        // layout pin on the Vec<String> per-entry shape cascade.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.autores = vec!["alice\nbob".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::AutoresViolation { caixa, issue } = err else {
            panic!("expected LayoutError::AutoresViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":autores"),
            "issue must name the offending slot: {issue}",
        );
        assert!(
            issue.contains("alice\\nbob"),
            "issue must quote the offending value (debug-escaped): {issue}",
        );
    }

    // ── repositorio universal-axis gate wired into verify ────────────────
    //
    // Pins the layout-pipeline wire-up of [`Caixa::validate_repositorio`]:
    // the sixth universal-axis Caixa-level value-shape gate (peer of
    // `validate_nome` / `validate_versao` / `validate_deps` /
    // `validate_etiquetas` / `validate_autores` / `validate_code_paths`),
    // wired immediately after `validate_autores` so the universal
    // git-URL axis sits adjacent to the two Vec-shaped universal
    // metadata axes (`:etiquetas`, `:autores`) in the cascade. Until
    // this wire-up landed `:repositorio` had no shape gate at any
    // layer — the universal git-shaped homepage axis was the third
    // largest universal authoring surface on the typed Caixa with no
    // validate discipline, routing the same string through two
    // load-bearing substrate consumers (`caixa-helm`'s `Chart.yaml
    // home:` field and `caixa-flux`'s FluxCD `GitRepository.spec.url`)
    // via `Option::unwrap_or_else` fallbacks that only fire on `None` —
    // a `Some("")` silently passed every fallback and rendered as an
    // empty URL in both consumers, breaking at `helm template` /
    // FluxCD reconcile time far from the source `caixa.lisp`. The
    // gate closes the divergence and makes the two `git URL`-shaped
    // surfaces on the typed Caixa (`:repositorio` here, `:deps :fonte
    // :repo` peer routed through the same shared
    // `crate::render::is_git_repo_url` predicate) structurally
    // equivalent by construction.

    #[test]
    fn repositorio_violation_on_empty_some() {
        // Canonical paste-from-blank-doc footgun on every kind. The
        // wrap envelope wraps [`ManifestError::RepositorioEmpty`]'s
        // Display through verbatim, so the issue string names the
        // offending `:repositorio` axis at the source — the author
        // can grep their caixa.lisp for `:repositorio ""` and fix the
        // empty value in one edit. Mirrors the peer
        // `autores_violation_on_empty_entry` shape (86c769b) on the
        // `:autores` axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.repositorio = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::RepositorioViolation { caixa, issue } = err else {
            panic!("expected LayoutError::RepositorioViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":repositorio"),
            "issue must name the offending slot: {issue}",
        );
    }

    #[test]
    fn repositorio_violation_on_malformed_shape() {
        // Canonical CLI-argument-injection footgun: a leading `-`
        // value (`-upload-pack=evil`) escapes the `git clone <repo>`
        // subprocess argument boundary at clone time. The shared
        // `is_git_repo_url` predicate — the same parser the peer
        // `:deps :fonte :repo` axis routes through via
        // `DepSource::validate` — refuses every leading-`-` shape at
        // validate time. The wrap envelope names the offending value
        // verbatim through the inner [`ManifestError::RepositorioInvalid`]'s
        // Display.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.repositorio = Some("-upload-pack=evil".into());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::RepositorioViolation { caixa, issue } = err else {
            panic!("expected LayoutError::RepositorioViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("-upload-pack=evil"),
            "issue must quote the offending value: {issue}",
        );
    }

    #[test]
    fn repositorio_violation_fires_before_kind_coherence_mesh_slot() {
        // Cross-axis precedence pin: a Biblioteca with malformed
        // `:repositorio` *and* declared mesh slots (`:membros`)
        // surfaces the universal `:repositorio` diagnostic first, not
        // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
        // `:repositorio` is universal (every kind owns the slot), so
        // its shape diagnostic is more fundamental than the
        // partition-on-kind diagnostic. Mirrors the peer
        // `autores_violation_fires_before_kind_coherence_mesh_slot`
        // pin (86c769b) on the `:autores` axis vs the same
        // kind-coherence gates.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.repositorio = Some(String::new());
        c.membros = vec![crate::aplicacao::Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::RepositorioViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn repositorio_violation_fires_after_autores_violation() {
        // Cross-axis precedence pin (inside the universal metadata
        // trio): a caixa with both a malformed `:autores` entry *and*
        // a malformed `:repositorio` value surfaces `AutoresViolation`
        // first — `:autores` is the fifth universal axis in the
        // cascade and runs before `:repositorio`, peer with the
        // canonical identity-axis-first cascade the peer gates
        // establish. Mirrors the peer
        // `autores_violation_fires_after_etiquetas_violation`
        // precedence pin (86c769b) on the tag-axis-before-author-axis
        // pair.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.autores = vec![String::new()];
        c.repositorio = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::AutoresViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn repositorio_violation_accepts_canonical_template() {
        // Positive control sanity pin: the canonical `Caixa::template`
        // shape (omits `:repositorio` entirely → `None` on the typed
        // surface) passes the gate trivially — the gate is a no-op
        // when the author didn't author a value. Mirrors the peer
        // `autores_violation_accepts_canonical_template` pin (86c769b).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let c = caixa(CaixaKind::Biblioteca);
        layout.verify(&c, &root).expect("template must pass");
    }

    #[test]
    fn repositorio_violation_accepts_canonical_github_shorthand() {
        // Positive control pin on the canonical pleme-io `:repositorio`
        // shape: the `github:org/repo` shorthand the README quickstart
        // and the `caixa-helm` / `caixa-mesh` / `caixa-flux` fixtures
        // all use passes the gate end-to-end. Closes the structural
        // equivalence between this surface and the peer `:deps :fonte
        // :repo` axis — both consume `crate::render::is_git_repo_url`
        // and both must agree on the same accepted shape set.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.repositorio = Some("github:pleme-io/hello-rio".into());
        layout.verify(&c, &root).expect("canonical shape must pass");
    }

    // ── descricao universal-axis gate wired into verify ──────────────────
    //
    // Pins the layout-pipeline wire-up of [`Caixa::validate_descricao`]:
    // the seventh universal-axis Caixa-level value-shape gate (peer of
    // `validate_nome` / `validate_versao` / `validate_deps` /
    // `validate_etiquetas` / `validate_autores` / `validate_repositorio` /
    // `validate_code_paths`), wired immediately after `validate_repositorio`
    // so the universal free-form-prose axis sits adjacent to the
    // universal git-URL axis in the cascade. Until this wire-up landed
    // `:descricao` had no shape gate at any layer — the empty
    // `Some("")` silently passed both `caixa-helm` consumers'
    // `Option::unwrap_or_else(|| <fallback>)` (which only fire on
    // `None`) and rendered as `Chart.yaml description: ""` plus a
    // blank `README.md` header, breaking at `helm lint` time
    // (`WARNING [chart.metadata.description]: description is required`
    // on `apiVersion: v2` charts) far from the source `caixa.lisp`.
    // Closes the same `Some("")` skips-`unwrap_or_else` footgun the
    // peer `:repositorio` gate (577b0a9) closed, on the universal
    // free-form-prose summary axis.

    #[test]
    fn descricao_violation_on_empty_some() {
        // Canonical paste-from-blank-doc footgun on every kind. The
        // wrap envelope wraps [`ManifestError::DescricaoEmpty`]'s
        // Display through verbatim, so the issue string names the
        // offending `:descricao` axis at the source — the author can
        // grep their caixa.lisp for `:descricao ""` and fix the empty
        // value in one edit. Mirrors the peer
        // `repositorio_violation_on_empty_some` shape (577b0a9) on
        // the sibling `Option<String>` `:repositorio` axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.descricao = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DescricaoViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DescricaoViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":descricao"),
            "issue must name the offending slot: {issue}",
        );
    }

    #[test]
    fn descricao_violation_fires_before_kind_coherence_mesh_slot() {
        // Cross-axis precedence pin: a Biblioteca with empty
        // `:descricao` *and* declared mesh slots (`:membros`)
        // surfaces the universal `:descricao` diagnostic first, not
        // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
        // `:descricao` is universal (every kind owns the slot), so
        // its shape diagnostic is more fundamental than the
        // partition-on-kind diagnostic. Mirrors the peer
        // `repositorio_violation_fires_before_kind_coherence_mesh_slot`
        // pin (577b0a9) on the `:repositorio` axis vs the same
        // kind-coherence gates.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.descricao = Some(String::new());
        c.membros = vec![crate::aplicacao::Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::DescricaoViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn descricao_violation_fires_after_repositorio_violation() {
        // Cross-axis precedence pin (inside the universal metadata
        // cascade): a caixa with both a malformed `:repositorio` *and*
        // an empty `:descricao` surfaces `RepositorioViolation`
        // first — `:repositorio` is the sixth universal axis in the
        // cascade and runs before `:descricao`, peer with the
        // canonical identity-axis-first cascade the peer gates
        // establish. Mirrors the peer
        // `repositorio_violation_fires_after_autores_violation`
        // precedence pin (577b0a9) on the autores-axis-before-
        // repositorio-axis pair.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.repositorio = Some(String::new());
        c.descricao = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::RepositorioViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn descricao_violation_accepts_none() {
        // Positive control sanity pin: a caixa that omits
        // `:descricao` entirely (the canonical `Caixa::template` shape
        // carries `Some("FIXME — describe this caixa")`, but the
        // layout-test fixture defaults to `None`) passes the gate
        // trivially — the gate is a no-op when the author didn't
        // author a value. Mirrors the peer
        // `repositorio_violation_accepts_canonical_template` pin
        // (577b0a9).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let c = caixa(CaixaKind::Biblioteca);
        layout.verify(&c, &root).expect("None must pass");
    }

    #[test]
    fn descricao_violation_accepts_canonical_summary() {
        // Positive control pin on the canonical pleme-io `:descricao`
        // shape: a short free-form prose summary the `caixa-helm` /
        // `caixa-flux` / `caixa-mesh` fixtures all carry passes the
        // gate end-to-end.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.descricao = Some("Canonical Rust→wasm32-wasip2 caixa Servico.".into());
        layout
            .verify(&c, &root)
            .expect("canonical summary must pass");
    }

    #[test]
    fn descricao_violation_on_non_chart_shape() {
        // Shape-predicate wire-up pin: a malformed `:descricao` value
        // that's a non-empty `Some(s)` but carries a paste-from-
        // multiline-doc embedded newline surfaces the
        // `DescricaoViolation` envelope via the manifest-layer
        // `ManifestError::DescricaoInvalid` arm. Mirrors the peer
        // `descricao_violation_on_empty_some` shape on the empty arm
        // of the same axis and the peer
        // `licenca_violation_on_non_spdx_shape` shape on the sibling
        // `:licenca` axis. Until this gate landed a value like
        // `"Checkout\nflow."` (an embedded newline) or `"Checkout
        // flow. "` (a trailing whitespace) silently passed
        // `StandardLayout::verify` and landed in the rendered
        // Chart.yaml `description:` field as a YAML-illegal
        // multi-line scalar or a silently-trimmed whitespace
        // round-trip far from the source caixa.lisp.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.descricao = Some("Checkout\nflow.".into());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DescricaoViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DescricaoViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":descricao"),
            "issue must name the offending slot: {issue}",
        );
        // The wrapped `ManifestError::DescricaoInvalid` Display uses
        // `{descricao:?}` (Debug) so the embedded newline surfaces
        // debug-escaped as `\n` in the issue string.
        assert!(
            issue.contains("Checkout\\nflow."),
            "issue must quote the offending value (debug-escaped): {issue}",
        );
    }

    // ── :licenca empty-Some shape wired into verify (universal axis) ──
    //
    // Until this wire-up landed `Caixa::validate_licenca` did not
    // exist — the universal SPDX-shaped license-expression axis had
    // no shape gate at any layer, so an empty `Some("")` silently
    // passed `Caixa::from_lisp` and `StandardLayout::verify` and
    // landed as a bare trailing period in the rendered
    // `lareira-<nome>` chart's `README.md` `## License` section via
    // the `caixa-helm` consumer's `caixa.licenca.clone().unwrap_or_else(||
    // "MIT".into())` (which only fires on `None`) at
    // `caixa-helm/src/lib.rs:361`. Closes the same `Some("")`
    // skips-`unwrap_or_else` footgun the peer `:repositorio`
    // (577b0a9) and `:descricao` (4e6db38) gates closed, on the
    // universal license-expression axis.

    #[test]
    fn licenca_violation_on_empty_some() {
        // Canonical paste-from-blank-doc footgun on every kind. The
        // wrap envelope wraps [`ManifestError::LicencaEmpty`]'s
        // Display through verbatim, so the issue string names the
        // offending `:licenca` axis at the source — the author can
        // grep their caixa.lisp for `:licenca ""` and fix the empty
        // value in one edit. Mirrors the peer
        // `descricao_violation_on_empty_some` shape (4e6db38) on
        // the sibling `Option<String>` `:licenca` axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.licenca = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::LicencaViolation { caixa, issue } = err else {
            panic!("expected LayoutError::LicencaViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":licenca"),
            "issue must name the offending slot: {issue}",
        );
    }

    #[test]
    fn licenca_violation_fires_before_kind_coherence_mesh_slot() {
        // Cross-axis precedence pin: a Biblioteca with empty
        // `:licenca` *and* declared mesh slots (`:membros`)
        // surfaces the universal `:licenca` diagnostic first, not
        // the kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
        // `:licenca` is universal (every kind owns the slot), so
        // its shape diagnostic is more fundamental than the
        // partition-on-kind diagnostic. Mirrors the peer
        // `descricao_violation_fires_before_kind_coherence_mesh_slot`
        // pin (4e6db38) on the `:descricao` axis vs the same
        // kind-coherence gates.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.licenca = Some(String::new());
        c.membros = vec![crate::aplicacao::Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::LicencaViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn licenca_violation_fires_after_descricao_violation() {
        // Cross-axis precedence pin (inside the universal metadata
        // cascade): a caixa with both an empty `:descricao` *and*
        // an empty `:licenca` surfaces `DescricaoViolation`
        // first — `:descricao` is the seventh universal axis in the
        // cascade and runs before `:licenca`, peer with the
        // canonical identity-axis-first cascade the peer gates
        // establish. Mirrors the peer
        // `descricao_violation_fires_after_repositorio_violation`
        // precedence pin (4e6db38) on the repositorio-axis-before-
        // descricao-axis pair.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.descricao = Some(String::new());
        c.licenca = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::DescricaoViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn licenca_violation_accepts_none() {
        // Positive control sanity pin: a caixa that omits `:licenca`
        // entirely (the layout-test fixture defaults to `None`)
        // passes the gate trivially — the gate is a no-op when the
        // author didn't author a value. Mirrors the peer
        // `descricao_violation_accepts_none` pin (4e6db38).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let c = caixa(CaixaKind::Biblioteca);
        layout.verify(&c, &root).expect("None must pass");
    }

    #[test]
    fn licenca_violation_accepts_canonical_expression() {
        // Positive control pin on the canonical pleme-io `:licenca`
        // shape: a non-empty SPDX expression the `caixa-helm` /
        // `caixa-flux` / `caixa-mesh` fixtures all carry (`"MIT"`)
        // passes the gate end-to-end.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.licenca = Some("Apache-2.0 OR MIT".into());
        layout
            .verify(&c, &root)
            .expect("canonical SPDX expression must pass");
    }

    #[test]
    fn licenca_violation_on_non_spdx_shape() {
        // Shape-predicate wire-up pin: a malformed `:licenca` value
        // that's a non-empty `Some(s)` but falls outside the SPDX
        // expression alphabet floor surfaces the `LicencaViolation`
        // envelope via the manifest-layer `ManifestError::LicencaInvalid`
        // arm. Mirrors the peer `licenca_violation_on_empty_some`
        // shape on the empty arm of the same axis and the peer
        // `edicao_violation_on_non_year_shape` shape on the sibling
        // `:edicao` axis. Until this gate landed a value like
        // `"Apache_2.0"` (an underscore-instead-of-hyphen typo) or
        // `"MIT, Apache-2.0"` (a comma-instead-of-`OR`-keyword
        // colloquial idiom) silently passed `StandardLayout::verify`
        // and landed in the rendered chart `README.md` `## License`
        // section + a future SPDX-aware Chart.yaml `license:`
        // emitter would refuse the value at `helm lint` time far
        // from the source caixa.lisp.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.licenca = Some("Apache_2.0".into());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::LicencaViolation { caixa, issue } = err else {
            panic!("expected LayoutError::LicencaViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":licenca"),
            "issue must name the offending slot: {issue}",
        );
        assert!(
            issue.contains("Apache_2.0"),
            "issue must quote the offending value: {issue}",
        );
    }

    // ── :edicao empty-Some shape wired into verify (universal axis) ──
    //
    // Until this wire-up landed `Caixa::validate_edicao` did not
    // exist — the universal language-edition axis had no shape gate
    // at any layer, so an empty `Some("")` silently passed
    // `Caixa::from_lisp` and `StandardLayout::verify` and landed as a
    // bare `(:edicao "")` line in the rendered caixa.lisp, ready for
    // a future renderer-side consumer's `Option::unwrap_or_else`
    // (which only fires on `None`) to skip its fallback. Closes the
    // same `Some("")`-skips-`unwrap_or_else` footgun the peer
    // `:repositorio` (577b0a9), `:descricao` (4e6db38), and
    // `:licenca` (3d1e535) gates closed, on the universal language-
    // edition axis — the last un-gated universal-axis
    // `Option<String>` Caixa-level value-shape surface.

    #[test]
    fn edicao_violation_on_empty_some() {
        // Canonical paste-from-blank-doc footgun on every kind. The
        // wrap envelope wraps [`ManifestError::EdicaoEmpty`]'s
        // Display through verbatim, so the issue string names the
        // offending `:edicao` axis at the source — the author can
        // grep their caixa.lisp for `:edicao ""` and fix the empty
        // value in one edit. Mirrors the peer
        // `licenca_violation_on_empty_some` shape (3d1e535) on the
        // sibling `Option<String>` `:edicao` axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.edicao = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::EdicaoViolation { caixa, issue } = err else {
            panic!("expected LayoutError::EdicaoViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":edicao"),
            "issue must name the offending slot: {issue}",
        );
    }

    #[test]
    fn edicao_violation_fires_before_kind_coherence_mesh_slot() {
        // Cross-axis precedence pin: a Biblioteca with empty
        // `:edicao` *and* declared mesh slots (`:membros`) surfaces
        // the universal `:edicao` diagnostic first, not the
        // kind-coherence `MeshSlotsOnNonAplicacao` diagnostic.
        // `:edicao` is universal (every kind owns the slot), so
        // its shape diagnostic is more fundamental than the
        // partition-on-kind diagnostic. Mirrors the peer
        // `licenca_violation_fires_before_kind_coherence_mesh_slot`
        // pin (3d1e535) on the `:licenca` axis vs the same
        // kind-coherence gates.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.edicao = Some(String::new());
        c.membros = vec![crate::aplicacao::Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::EdicaoViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn edicao_violation_fires_after_licenca_violation() {
        // Cross-axis precedence pin (inside the universal metadata
        // cascade): a caixa with both an empty `:licenca` *and* an
        // empty `:edicao` surfaces `LicencaViolation` first —
        // `:licenca` is the eighth universal axis in the cascade
        // and runs before `:edicao`, peer with the canonical
        // identity-axis-first cascade the peer gates establish.
        // Mirrors the peer
        // `licenca_violation_fires_after_descricao_violation`
        // precedence pin (3d1e535) on the descricao-axis-before-
        // licenca-axis pair.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.licenca = Some(String::new());
        c.edicao = Some(String::new());
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::LicencaViolation { .. }),
            "got {err:?}",
        );
    }

    #[test]
    fn edicao_violation_accepts_none() {
        // Positive control sanity pin: a caixa that omits `:edicao`
        // entirely (the layout-test fixture defaults to `None`)
        // passes the gate trivially — the gate is a no-op when the
        // author didn't author a value. Mirrors the peer
        // `licenca_violation_accepts_none` pin (3d1e535).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let c = caixa(CaixaKind::Biblioteca);
        layout.verify(&c, &root).expect("None must pass");
    }

    #[test]
    fn edicao_violation_accepts_canonical_value() {
        // Positive control pin on the canonical pleme-io `:edicao`
        // shape: the `"2026"` edition every `caixa-helm` /
        // `caixa-flux` / `caixa-mesh` / `caixa-core/src/render.rs`
        // fixture carries by construction passes the gate end-to-end.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.edicao = Some("2026".into());
        layout
            .verify(&c, &root)
            .expect("canonical edition must pass");
    }

    #[test]
    fn edicao_violation_on_non_year_shape() {
        // Shape-predicate wire-up pin: a malformed `:edicao` value
        // that's a non-empty `Some(s)` but not a 4-digit ASCII
        // decimal year surfaces the `EdicaoViolation` envelope via
        // the manifest-layer `ManifestError::EdicaoInvalid` arm.
        // Mirrors the peer `edicao_violation_on_empty_some` shape
        // on the empty arm of the same axis. Until this gate landed
        // a value like `"v2026"` (a familiar git-tag idiom that
        // doesn't apply to the year-shaped edition axis) silently
        // passed `StandardLayout::verify` and broke at the
        // substrate's build-time edition selector far from the
        // source caixa.lisp.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.edicao = Some("v2026".into());
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::EdicaoViolation { caixa, issue } = err else {
            panic!("expected LayoutError::EdicaoViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":edicao"),
            "issue must name the offending slot: {issue}",
        );
        assert!(
            issue.contains("v2026"),
            "issue must quote the offending value: {issue}",
        );
    }

    // ── Caixa-identity gates (`:nome`, `:versao`) wired into verify ────
    //
    // Until this wire-up landed `Caixa::validate_nome` and
    // `Caixa::validate_versao` lived as `pub fn` on `Caixa` with full
    // per-arm unit coverage in `manifest::tests`, but no production
    // path called them — `feira build` silently accepted malformed
    // `:nome` / `:versao` and the failure surfaced at `helm install` /
    // `kubectl apply` / `feira publish` / lacre-resolve / `:upgrade-from
    // :from` matching time, far from the source `caixa.lisp`. The
    // following pins fence the layout-pipeline wire-up: every layout
    // verify on a structurally-invalid Caixa identity axis surfaces
    // the per-axis `*Violation { caixa, issue }` envelope before any
    // kind-coherence, code-path, or downstream gate sees it.

    #[test]
    fn nome_violation_on_uppercase() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = "MyApp".into();
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::NomeViolation { caixa, issue } = err else {
            panic!("expected LayoutError::NomeViolation, got {err:?}");
        };
        assert_eq!(caixa, "MyApp");
        assert!(
            issue.contains("MyApp"),
            "issue must quote the offending nome: {issue}",
        );
    }

    #[test]
    fn nome_violation_on_underscore() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = "my_app".into();
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::NomeViolation { ref caixa, .. } if caixa == "my_app"),
            "got {err:?}",
        );
    }

    #[test]
    fn nome_violation_on_empty() {
        // Empty `:nome` surfaces NomeViolation wrapping the narrower
        // `ManifestError::NomeEmpty` arm — the empty-first cascade the
        // peer per-axis name gates already use.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = String::new();
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::NomeViolation { caixa, issue } = err else {
            panic!("expected LayoutError::NomeViolation, got {err:?}");
        };
        assert!(caixa.is_empty());
        assert!(
            issue.contains(":nome is empty"),
            "issue must surface the empty-arm diagnostic: {issue}",
        );
    }

    #[test]
    fn versao_violation_on_missing_patch() {
        // `"0.1"` — the canonical "I shortened it" footgun. Helm /
        // OCI / lacre-resolve / `:upgrade-from :from` all strict-parse
        // through `semver::Version::parse`, which refuses a two-part
        // shape.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.versao = "0.1".into();
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::VersaoViolation { caixa, issue } = err else {
            panic!("expected LayoutError::VersaoViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("0.1"),
            "issue must quote the offending versao: {issue}",
        );
    }

    #[test]
    fn versao_violation_on_git_tag_shape() {
        // `"v0.1.0"` — the git-tag-shape-leaking-into-versao typo.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.versao = "v0.1.0".into();
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::VersaoViolation { ref issue, .. }
                if issue.contains("v0.1.0")),
            "got {err:?}",
        );
    }

    #[test]
    fn versao_violation_on_empty() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.versao = String::new();
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::VersaoViolation { caixa, issue } = err else {
            panic!("expected LayoutError::VersaoViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":versao is empty"),
            "issue must surface the empty-arm diagnostic: {issue}",
        );
    }

    #[test]
    fn nome_violation_fires_before_versao_violation() {
        // Precedence pin: when both `:nome` and `:versao` are malformed,
        // `:nome` surfaces first — the canonical declaration-order
        // precedence the `ManifestError` family establishes, the same
        // grep-order the author follows when fixing in `caixa.lisp`.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = "MyApp".into();
        c.versao = "0.1".into();
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::NomeViolation { .. }),
            "got {err:?} — nome must fire before versao",
        );
    }

    #[test]
    fn nome_violation_fires_before_kind_coherence() {
        // Precedence pin: a Biblioteca caixa with a malformed `:nome`
        // AND a declared mesh slot surfaces NomeViolation, not
        // MeshSlotsOnNonAplicacao — the identity-axis gate is more
        // fundamental than the kind-coherence gate (which carries
        // `caixa.nome` verbatim in its diagnostic, and so depends on the
        // name being structurally valid to render a useful message).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = "MyApp".into();
        c.membros = vec![crate::aplicacao::Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::NomeViolation { .. }),
            "got {err:?} — nome must fire before MeshSlotsOnNonAplicacao",
        );
    }

    #[test]
    fn nome_violation_fires_before_owncode() {
        // Precedence pin: a Supervisor with a malformed `:nome` AND
        // declared `:bibliotecas` surfaces NomeViolation, not
        // SupervisorOwnsCode — same rationale as above.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Supervisor);
        c.nome = "MyApp".into();
        c.bibliotecas = vec!["lib/x.lisp".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::NomeViolation { .. }),
            "got {err:?} — nome must fire before SupervisorOwnsCode",
        );
    }

    #[test]
    fn versao_violation_fires_before_kind_coherence() {
        // Precedence pin: a Biblioteca with a valid `:nome` but a
        // malformed `:versao` AND a declared servico slot surfaces
        // VersaoViolation before ServicoSlotsOnNonServico.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.versao = "v0.1.0".into();
        c.limits = Some(crate::LimitsSpec {
            memory: Some(64 * 1024 * 1024),
            ..Default::default()
        });
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::VersaoViolation { .. }),
            "got {err:?} — versao must fire before ServicoSlotsOnNonServico",
        );
    }

    #[test]
    fn nome_violation_fires_before_missing_lib() {
        // Precedence pin: a Biblioteca with a malformed `:nome` and no
        // lib entry surfaces NomeViolation, not MissingLib — the
        // identity-axis gate is more fundamental than the layout's
        // `lib/<nome>.lisp` default-path check (which derives the
        // expected path from `:nome` itself, so would surface a
        // misleading "expected lib/MyApp.lisp" diagnostic against an
        // unrecoverable name).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = "MyApp".into();
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::NomeViolation { .. }),
            "got {err:?} — nome must fire before MissingLib",
        );
    }

    #[test]
    fn nome_versao_violations_fire_after_missing_manifest() {
        // Precedence pin: `MissingManifest` still dominates — there's
        // no caixa to identity-check when the manifest is missing.
        let root = PathBuf::from("/tmp/x");
        let layout = StandardLayout::new().with_path_exists(|_| false);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = "MyApp".into();
        c.versao = "0.1".into();
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::MissingManifest(_)),
            "got {err:?} — MissingManifest must dominate identity gates",
        );
    }

    #[test]
    fn valid_nome_versao_passes_to_downstream_gates() {
        // Sanity pin: the canonical "demo" / "0.1.0" identity passes
        // both axes; downstream gates (MissingLib here) take over.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let err = layout
            .verify(&caixa(CaixaKind::Biblioteca), &root)
            .unwrap_err();
        assert!(
            matches!(err, LayoutError::MissingLib { .. }),
            "got {err:?} — valid identity must pass to MissingLib",
        );
    }

    // ── :deps / :deps-dev shape gate (lifted to layout-level verify) ─────
    //
    // Until this wire-up landed `Caixa::validate_deps` lived as `pub fn`
    // on `Caixa` with full per-arm unit coverage in `manifest::tests` +
    // `dep::tests` but no production path called it — `feira build`
    // silently accepted a malformed `:deps` / `:deps-dev` entry and the
    // failure surfaced at lacre-resolve / `git clone` / `cargo metadata`
    // / `helm install` time on the *first* downstream consumer to
    // strict-parse the value, far from the source `caixa.lisp` and
    // without any field naming the offending `:deps` axis. The following
    // pins fence the layout-pipeline wire-up: every layout verify on a
    // structurally-invalid `:deps` value-shape surfaces the per-axis
    // `DepsViolation { caixa, issue }` envelope (peer of
    // `NomeViolation` / `VersaoViolation` / `CodePathViolation` /
    // `LimitsViolation` / `BehaviorViolation` / `UpgradeViolation` /
    // `SupervisorViolation` / `AplicacaoViolation`) before any kind-
    // coherence, code-path, or downstream gate sees it.

    #[test]
    fn deps_violation_on_empty_dep_nome() {
        // Empty `:nome` on a `:deps` entry surfaces the narrower
        // `DepError::NomeEmpty` arm through the wrap envelope.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![Dep::simple("", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":deps") && issue.contains(":nome"),
            "issue must name the offending slot + axis: {issue}",
        );
    }

    #[test]
    fn deps_violation_on_uppercase_dep_nome() {
        // Uppercase `:nome` on a `:deps` entry surfaces
        // `DepError::NomeInvalid` (DNS-1123 violation) through the wrap.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![Dep::simple("Caixa-Teia", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("Caixa-Teia"),
            "issue must quote the offending dep nome verbatim: {issue}",
        );
    }

    #[test]
    fn deps_violation_on_unparseable_dep_versao() {
        // Unparseable `:versao` requirement on a `:deps` entry surfaces
        // `DepError::VersaoInvalid` through the wrap — the canonical
        // "the semver::Error reached the resolver, far from the source"
        // footgun closed at author time.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![Dep::simple("caixa-teia", "not-a-req")];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("caixa-teia") && issue.contains("not-a-req"),
            "issue must quote the dep nome + offending versao: {issue}",
        );
    }

    #[test]
    fn deps_violation_on_duplicate_nome_in_deps() {
        // Within-list `:deps :nome` duplicate surfaces
        // `DepError::DuplicateNome { list: ":deps" }` through the wrap.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![
            Dep::simple("caixa-teia", "^0.1"),
            Dep::simple("caixa-teia", "^0.2"),
        ];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("caixa-teia") && issue.contains(":deps"),
            "issue must quote the duplicated nome + list: {issue}",
        );
    }

    #[test]
    fn deps_violation_on_duplicate_nome_in_deps_dev() {
        // Within-list `:deps-dev :nome` duplicate surfaces the same
        // diagnostic on the dev-only axis — neither list is a
        // second-class citizen of the typed surface.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps_dev = vec![
            Dep::simple("caixa-teia", "^0.1"),
            Dep::simple("caixa-teia", "^0.2"),
        ];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":deps-dev"),
            "issue must name the offending list: {issue}",
        );
    }

    #[test]
    fn deps_violation_in_deps_fires_before_deps_dev() {
        // Precedence pin: when *both* `:deps` and `:deps-dev` carry a
        // malformed entry, the `:deps` walk fires first — the canonical
        // declaration-order precedence `Caixa::validate_deps` establishes
        // (the same author-grep ordering the typed-graph peers use on
        // every other Vec-shaped surface).
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![Dep::simple("Bad-In-Deps", "^0.1")];
        c.deps_dev = vec![Dep::simple("Bad-In-Deps-Dev", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa: _, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert!(
            issue.contains("Bad-In-Deps") && !issue.contains("Bad-In-Deps-Dev"),
            "issue must name the :deps offender, not :deps-dev: {issue}",
        );
    }

    #[test]
    fn deps_violation_fires_after_versao_violation() {
        // Precedence pin: when both the top-level `:versao` and a `:deps`
        // entry are malformed, the Caixa-identity gate fires first — the
        // canonical declaration order on `Caixa` (`:nome` → `:versao` →
        // ... → `:deps`) and the same identity-axis-dominates-content-
        // axis discipline the peer `validate_nome` / `validate_versao`
        // wire-up established (1f74a5f). A malformed `:versao` would
        // otherwise quote `caixa.nome` against a downstream-shaped
        // diagnostic.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.versao = "v0.1.0".into();
        c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::VersaoViolation { .. }),
            "got {err:?} — versao must fire before DepsViolation",
        );
    }

    #[test]
    fn deps_violation_fires_before_kind_coherence() {
        // Precedence pin: a Supervisor with a malformed `:deps` entry
        // AND declared `:bibliotecas` (the canonical SupervisorOwnsCode
        // shape) surfaces DepsViolation, not SupervisorOwnsCode — the
        // dep surface is universal across all kinds and its shape gate
        // is more fundamental than the kind-coherence partitions on
        // `:bibliotecas` / `:exe` / `:servicos`. The author can fix the
        // dep typo without first being told to move their `:bibliotecas`
        // off a Supervisor.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Supervisor);
        c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
        c.bibliotecas = vec!["lib/x.lisp".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::DepsViolation { .. }),
            "got {err:?} — DepsViolation must fire before SupervisorOwnsCode",
        );
    }

    #[test]
    fn deps_violation_fires_after_missing_manifest() {
        // Precedence pin: `MissingManifest` still dominates — there's no
        // caixa to deps-check when the manifest is missing.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let layout = StandardLayout::new().with_path_exists(|_| false);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![Dep::simple("Bad-Dep", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::MissingManifest(_)),
            "got {err:?} — MissingManifest must dominate the deps gate",
        );
    }

    #[test]
    fn deps_violation_on_self_dep_in_deps() {
        // Cross-slot self-edge: a caixa whose `:deps` lists its own
        // `:nome` is rejected at the layout wire-up, the diagnostic
        // surfaces through the `DepsViolation` envelope with both the
        // offending list tag (`":deps"`) and the parent's `:nome`
        // verbatim. Until this wire-up landed the self-dep silently
        // passed `feira build` and the resolver's lacre-pipeline
        // closure walk either rejected mid-traversal (infinite
        // recursion detected far from the source caixa.lisp) or, on
        // the unbounded path, recursed until it exhausted its stack.
        // Mirrors the supervision-tree
        // [`supervisor_violation_on_self_supervision`] and the
        // Aplicacao-membership self-edge wire-up tests on the peer
        // typed-name-graph axes.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![Dep::simple("demo", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":deps") && issue.contains("demo"),
            "issue must name the offending list + parent :nome: {issue}",
        );
    }

    #[test]
    fn deps_violation_on_self_dep_in_deps_dev() {
        // Same cross-slot self-edge gate on the `:deps-dev` axis —
        // neither dep list is a second-class citizen of the typed
        // surface. The diagnostic names `:deps-dev` so the author can
        // grep their caixa.lisp for the offending block directly.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps_dev = vec![Dep::simple("demo", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(":deps-dev"),
            "issue must name the offending list: {issue}",
        );
    }

    #[test]
    fn self_dep_fires_after_per_entry_dep_shape() {
        // Precedence pin: the per-entry shape gates of
        // [`Caixa::validate_deps`] (DNS-1123 / SemVer / fonte / etc.)
        // fire first on a self-dep entry whose `:nome` is malformed.
        // Same ordering posture every peer cross-slot gate uses
        // (`validate_no_self_supervision` after `SupervisorSpec::validate`,
        // `validate_no_self_membership` after `AplicacaoSpec::validate`).
        // A malformed self-dep `:nome` surfaces the narrower
        // per-entry diagnostic (which already names the parser-side
        // reason) before the self-edge gate sees the entry.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        // The parent is "demo" (DNS-1123 valid); the dep is "DEMO"
        // (DNS-1123 invalid). The per-entry shape gate fires on the
        // upper-case nome, masking the self-edge gate (and that's the
        // canonical precedence — fix the dep shape first, then the
        // structural self-edge becomes the next live diagnostic).
        c.deps = vec![Dep::simple("DEMO", "^0.1")];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa: _, issue } = err else {
            panic!("expected LayoutError::DepsViolation, got {err:?}");
        };
        assert!(
            issue.contains("DNS-1123"),
            "issue must be the per-entry shape diagnostic, not the self-edge gate: {issue}",
        );
    }

    #[test]
    fn valid_deps_pass_to_downstream_gates() {
        // Positive control pin: the canonical authoring shape (one
        // `:deps` entry naming a DNS-1123 nome + Cargo-shaped requirement,
        // one `:deps-dev` entry on a distinct nome) passes the dep gate;
        // downstream gates (MissingLib here) take over. Drift here =
        // a future tighten that rejects any canonical shape surfaces as
        // a regression at this layout-level pin.
        use crate::Dep;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.deps = vec![Dep::simple("caixa-teia", "^0.1")];
        c.deps_dev = vec![Dep::simple("caixa-lint", "^0.2")];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::MissingLib { .. }),
            "got {err:?} — valid deps must pass to MissingLib",
        );
    }

    #[test]
    fn code_path_gate_runs_after_foreign_code_slot_gate() {
        // Precedence pin: a Servico that declares `:exe` (foreign code
        // surface) surfaces ForeignCodeSlot, *not* a per-entry path
        // shape diagnostic, even when the `:exe` entry is itself
        // malformed. The kind-coherence gate is the load-bearing
        // diagnostic at this site — once the slot is moved off the
        // wrong kind, the per-entry shape gate becomes the next live
        // diagnostic.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/ok.yaml".into()];
        c.exe = vec!["/etc/foreign".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::ForeignCodeSlot { .. }),
            "expected ForeignCodeSlot (kind-coherence wins over per-entry shape), got {err:?}",
        );
    }

    // ── M2 typed-substrate invariants ────────────────────────────────────

    #[test]
    fn behavior_callback_path_must_exist() {
        use crate::BehaviorSpec;
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        let svc = root.join("servicos/demo.computeunit.yaml");
        c.behavior = Some(BehaviorSpec {
            on_init: Some(PathBuf::from("lib/init.lisp")),
            ..Default::default()
        });
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(
            err,
            LayoutError::MissingEntry { kind, .. }
                if kind == crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK
        ));

        // Now declare the path exists — passes.
        let init = root.join("lib/init.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc || p == init);
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn behavior_absolute_callback_is_violation_not_missing() {
        // An absolute path silently subverts `root.join(p)` (Path::join
        // replaces the base when the right side is absolute). Before
        // BehaviorSpec::validate ran, an `:on-init "/etc/passwd"` would
        // surface as a confusing "missing behavior-callback /etc/passwd"
        // — or, worse, pass when /etc/passwd happens to exist. Now it's
        // a value-shape error naming the slot.
        use crate::BehaviorSpec;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.behavior = Some(BehaviorSpec {
            on_init: Some(PathBuf::from("/etc/passwd")),
            ..Default::default()
        });
        // Path exists check would *succeed* on /etc/passwd (proving the
        // sandbox bypass) — value-shape pass must fire first.
        let layout = StandardLayout::new()
            .with_path_exists(move |p| p == manifest || p == svc || p == Path::new("/etc/passwd"));
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::BehaviorViolation { ref caixa, .. } if caixa == "demo"),
            "got {err:?}",
        );
    }

    #[test]
    fn behavior_empty_callback_is_violation() {
        use crate::BehaviorSpec;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.behavior = Some(BehaviorSpec {
            on_call: Some(PathBuf::new()),
            ..Default::default()
        });
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::BehaviorViolation { .. }));
    }

    #[test]
    fn upgrade_from_duplicate_surfaces_as_upgrade_violation() {
        // Wiring pin: the cross-entry duplicate-`:from` gate in
        // `validate_upgrade_from` lands on the same
        // `LayoutError::UpgradeViolation` axis the per-entry
        // `UpgradeFromEntry::validate` already does (26da2c7), so a
        // caixa.lisp with two `(:from "0.1.0" …)` blocks surfaces at
        // `feira build` time naming the offending caixa rather than
        // silently passing into the wasm-operator's non-deterministic
        // dispatch. Mirrors `behavior_empty_callback_is_violation` on
        // the peer M2 typed slot.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![
            UpgradeFromEntry {
                from: "0.1.0".into(),
                instructions: vec![UpgradeInstruction::Restart],
            },
            UpgradeFromEntry {
                from: "0.1.0".into(),
                instructions: vec![UpgradeInstruction::Restart],
            },
        ];
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!("expected LayoutError::UpgradeViolation for duplicate `:from`, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("0.1.0"),
            "UpgradeViolation issue must name the offending `:from` verbatim, got {issue:?}"
        );
    }

    #[test]
    fn upgrade_from_downgrade_surfaces_as_upgrade_violation() {
        // Wiring pin: the cross-slot precedence gate in
        // `validate_upgrade_from_against_versao` lands on the same
        // `LayoutError::UpgradeViolation` axis the per-entry and
        // cross-entry gates already do (26da2c7, 7c6aef2), so a
        // caixa.lisp whose `:upgrade-from :from` is greater than the
        // caixa's own `:versao` surfaces at `feira build` time
        // naming the offending caixa rather than silently passing
        // into the wasm-operator's `:from`-match dispatch where the
        // entry would sit dormant forever. Mirrors
        // `upgrade_from_duplicate_surfaces_as_upgrade_violation` on
        // the peer cross-entry gate.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.versao = "0.1.5".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.2.0".into(),
            instructions: vec![UpgradeInstruction::Restart],
        }];
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!(
                "expected LayoutError::UpgradeViolation for downgrade-shaped `:from`, got {err:?}"
            );
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("0.2.0") && issue.contains("0.1.5"),
            "UpgradeViolation issue must name both `:from` and `:versao` verbatim, got {issue:?}"
        );
    }

    #[test]
    fn upgrade_from_equal_to_versao_surfaces_as_upgrade_violation() {
        // Self-upgrade no-op arm: `:from "0.1.0"` while
        // `:versao "0.1.0"` declares "upgrade from myself to
        // myself", which the operator's dispatch either skips
        // silently or trivially "succeeds" with no observable
        // transition. Surfaces at validate time naming both values
        // so the author can fix in one edit.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.versao = "0.1.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::Restart],
        }];
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!(
                "expected LayoutError::UpgradeViolation for self-upgrade `:from == :versao`, got \
                 {err:?}"
            );
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("0.1.0"),
            "UpgradeViolation issue must name the equal `:from`/`:versao` verbatim, got {issue:?}"
        );
    }

    #[test]
    fn upgrade_from_strict_upgrade_passes_layout() {
        // Positive control for the precedence gate at the
        // LayoutInvariants level: a valid `:from < :versao` chain
        // (`0.1.0 → 0.2.0`) must not regress into a false-positive
        // `UpgradeViolation`. Mirrors `behavior_callback_path_must_exist`'s
        // positive-control arm.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.versao = "0.2.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::Restart],
        }];
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn upgrade_script_path_must_exist() {
        use crate::{BehaviorSpec, UpgradeFromEntry, UpgradeInstruction};
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let on_state_change = root.join("lib/migrations.lisp");
        let mut c = caixa(CaixaKind::Servico);
        // `:versao` past the entry's `:from` so the cross-slot
        // precedence gate (`FromNotBeforeVersao`) lets this case
        // through to the path-existence pass under test.
        c.versao = "0.2.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        // `:on-state-change` declared so the cross-slot composition
        // gate (`validate_upgrade_from_against_behavior`) lets the
        // `:state-change` entry through to the path-existence pass
        // under test. Without the callback the missing-callback gate
        // would surface first and the path-existence pass wouldn't be
        // exercised.
        c.behavior = Some(BehaviorSpec {
            on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
            ..Default::default()
        });
        // A `:load-module` precedes the `:state-change` so the entry
        // satisfies the within-entry state-change-ordering gate
        // (`StateChangeWithoutPriorLoad`) and the path-existence pass
        // under test is the gate actually exercised. `:load-module`
        // carries no on-disk path, so it adds no existence requirement.
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![
                UpgradeInstruction::LoadModule {
                    module: "demo".into(),
                },
                UpgradeInstruction::StateChange {
                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
                },
            ],
        }];
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let on_state_change_clone = on_state_change.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| {
            p == manifest_clone || p == svc_clone || p == on_state_change_clone
        });
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(
            err,
            LayoutError::MissingEntry { kind, .. }
                if kind == crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT
        ));
    }

    #[test]
    fn layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels() {
        // Byte-identity pin: the two per-M2-slot leaf-kind labels the
        // [`LayoutError::MissingEntry`] `kind: &'static str`
        // discriminator surfaces under (the M2 `:behavior` per-callback
        // on-disk-leaf axis, the M2 `:upgrade-from :instructions`
        // per-`:state-change` script-path on-disk-leaf axis) route
        // through the lifted [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`]
        // / [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`]
        // consts, so a future rebrand that reaches the const but not
        // the production emit / test probe (or vice versa) surfaces
        // here at build time rather than at runtime as a downstream
        // [`LayoutError::MissingEntry`] `kind: <stale-label>`
        // diagnostic mismatch far from the rename's commit. Mirror of
        // the peer
        // [`crate::aplicacao::tests::contrato_author_key_consts_pin_canonical_kebab_case_labels`]
        // (f50c875) and
        // [`crate::upgrade::tests::upgrade_instruction_kind_consts_pin_canonical_kebab_case_tags`]
        // (56120ef) byte-identity pins on the sibling M3 `:contratos`
        // per-entry endpoint-label + M2 `:upgrade-from :instructions`
        // per-variant kind-tag axes.
        assert_eq!(
            crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
            "behavior-callback"
        );
        assert_eq!(
            crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
            "upgrade-script"
        );
    }

    #[test]
    fn layout_missing_entry_kind_m0_consts_pin_canonical_code_slot_labels() {
        // Byte-identity pin: the three per-M0-code-slot leaf-kind
        // labels the [`LayoutError::MissingEntry`] `kind: &'static
        // str` discriminator surfaces under (the `:bibliotecas`
        // per-entry axis, the `:exe` per-entry axis, the `:servicos`
        // per-entry axis) route through the lifted
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] consts,
        // so a future rebrand that reaches the const but not the
        // production emit (or vice versa) surfaces here at build time
        // rather than at runtime as a downstream
        // [`LayoutError::MissingEntry`] `kind: <stale-label>`
        // diagnostic mismatch far from the rename's commit. Mirror of
        // the peer M2-tier pin
        // [`layout_missing_entry_kind_m2_consts_pin_canonical_kebab_case_labels`]
        // (95c9c4c) on the sibling `:behavior` / `:upgrade-from`
        // per-slot leaf-kind axes.
        assert_eq!(
            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
            "biblioteca"
        );
        assert_eq!(crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE, "exe");
        assert_eq!(crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO, "servico");
    }

    #[test]
    fn layout_missing_entry_kind_m0_consts_align_with_caixa_kind_as_str() {
        // Cross-axis byte-identity pin: the two `:kind`-namesake M0
        // leaf-kind labels ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`]
        // = `"biblioteca"`,
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] =
        // `"servico"`) must equal [`crate::CaixaKind::Biblioteca`] /
        // [`crate::CaixaKind::Servico`]'s
        // [`crate::CaixaKind::as_str`] outputs verbatim — the
        // substrate's canonical human-readable-kind axis and the
        // layout diagnostic's per-slot leaf-kind axis share one
        // vocabulary for these two arms by design (both label the
        // caixa's code-producing shape by its Portuguese-native
        // idiom), so drift between the two lands as a build-time
        // pattern-arm miss here rather than as a runtime diagnostic
        // that reads inconsistently across `feira build`'s
        // per-invocation output.
        //
        // The third M0 arm ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`]
        // = `"exe"`) is deliberately *distinct* from
        // [`crate::CaixaKind::Binario`]'s [`crate::CaixaKind::as_str`]
        // output (`"binario"`) — the `:exe` code slot names the
        // per-directory leaf-kind at the `exe/` subtree, whereas
        // [`crate::CaixaKind::Binario`] names the caixa's own runtime
        // kind. Two axes, two labels — the inequality assertion here
        // pins the split so a future accidental collapse of the two
        // onto one scalar (a rebrand that reroutes either axis to
        // match the other) trips at build time.
        assert_eq!(
            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
            CaixaKind::Biblioteca.as_str()
        );
        assert_eq!(
            crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
            CaixaKind::Servico.as_str()
        );
        assert_ne!(
            crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
            CaixaKind::Binario.as_str(),
            "`exe` leaf-kind label names the per-directory code-slot \
             axis; `binario` names the caixa-kind axis — the two must \
             not silently collapse onto one scalar"
        );
    }

    #[test]
    fn layout_missing_entry_kind_consts_are_pairwise_distinct() {
        // Distinctness pin: the five [`LayoutError::MissingEntry`]
        // `kind: &'static str` accept-set members
        // ([`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`] /
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] /
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`] on the
        // M0 code-slot arms plus
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK`]
        // / [`crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT`]
        // on the M2 slot arms) must be pairwise distinct — an
        // accidental copy-paste flip that reroutes one label's byte-
        // string to also match another silently collapses two
        // per-slot diagnostics onto one, so an operator running
        // `feira build` reads `kind: "biblioteca"` for what should
        // have surfaced as a `:behavior :on-init` script-not-found
        // diagnostic (or vice versa). This pin catches any such
        // flip at build time. Mirror of the peer
        // [`crate::render::tests::m2_limits_key_consts_are_pairwise_distinct`]
        // / peer distinctness pins on other closed-set typed axes.
        let entries: &[(&str, &str)] = &[
            (
                "LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA",
                crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
            ),
            (
                "LAYOUT_MISSING_ENTRY_KIND_EXE",
                crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
            ),
            (
                "LAYOUT_MISSING_ENTRY_KIND_SERVICO",
                crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
            ),
            (
                "LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK",
                crate::render::LAYOUT_MISSING_ENTRY_KIND_BEHAVIOR_CALLBACK,
            ),
            (
                "LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT",
                crate::render::LAYOUT_MISSING_ENTRY_KIND_UPGRADE_SCRIPT,
            ),
        ];
        for (i, (name_a, value_a)) in entries.iter().enumerate() {
            for (name_b, value_b) in entries.iter().skip(i + 1) {
                assert_ne!(
                    value_a, value_b,
                    "LAYOUT_MISSING_ENTRY_KIND_* consts must be \
                     pairwise-distinct byte-strings — {name_a} and \
                     {name_b} both resolve to {value_a:?}"
                );
            }
        }
    }

    #[test]
    fn layout_dir_consts_pin_canonical_directory_names() {
        // Scalar-value pin for the three [`crate::render::LAYOUT_DIR_*`]
        // consts naming the CSE-invariant per-[`CaixaKind`]
        // on-disk-directory-name axes the substrate's layout invariants
        // pin (`lib/` for [`CaixaKind::Biblioteca`], `exe/` for
        // [`CaixaKind::Binario`], `servicos/` for [`CaixaKind::Servico`]).
        // A future rebrand of any of the three on-disk directory landing
        // conventions must reach this pin — the const-edit lands on one
        // arm, the assertion here re-pins the new byte-string, and every
        // downstream consumer (the caixa-feira `init` / `fmt` / `lint` /
        // `tofu` scaffolders, the [`crate::LayoutInvariants::verify`]
        // sandbox reconstruction, the future
        // `feira app deploy`-cluster scaffolder) picks up the new
        // directory name at build time. Mirror of the peer
        // [`layout_missing_entry_kind_m0_consts_pin_canonical_code_slot_labels`]
        // (fe2a898) on the sibling
        // [`crate::LayoutError::MissingEntry`] `kind:` discriminator
        // axis this on-disk-directory axis composes with.
        assert_eq!(crate::render::LAYOUT_DIR_LIB, "lib");
        assert_eq!(crate::render::LAYOUT_DIR_EXE, "exe");
        assert_eq!(crate::render::LAYOUT_DIR_SERVICOS, "servicos");
    }

    #[test]
    fn layout_dir_consts_are_pairwise_distinct() {
        // Distinctness pin: the three per-[`CaixaKind`]
        // on-disk-directory-name arms must resolve to pairwise-distinct
        // byte-strings — a future accidental copy-paste flip that
        // reroutes any one of the three onto another's value silently
        // collapses two per-kind on-disk sandboxes onto one, so
        // [`crate::LayoutInvariants::verify`] would gate a
        // [`CaixaKind::Binario`] caixa's `:exe` entries against the
        // wrong sub-tree (or a `:kind Servico` caixa's `:servicos`
        // entries against `lib/` and pass every entry `feira build`
        // should have rejected as [`crate::LayoutError::ServicoOutsideDir`]).
        // Mirror of the peer
        // [`layout_missing_entry_kind_consts_are_pairwise_distinct`]
        // (fe2a898) on the sibling leaf-kind label accept-set.
        let entries: &[(&str, &str)] = &[
            ("LAYOUT_DIR_LIB", crate::render::LAYOUT_DIR_LIB),
            ("LAYOUT_DIR_EXE", crate::render::LAYOUT_DIR_EXE),
            ("LAYOUT_DIR_SERVICOS", crate::render::LAYOUT_DIR_SERVICOS),
        ];
        for (i, (name_a, value_a)) in entries.iter().enumerate() {
            for (name_b, value_b) in entries.iter().skip(i + 1) {
                assert_ne!(
                    value_a, value_b,
                    "LAYOUT_DIR_* consts must be pairwise-distinct \
                     byte-strings — {name_a} and {name_b} both resolve \
                     to {value_a:?}"
                );
            }
        }
    }

    #[test]
    fn layout_dir_exe_matches_layout_missing_entry_kind_exe() {
        // Cross-axis byte-identity pin: [`crate::render::LAYOUT_DIR_EXE`]
        // (the on-disk-directory-name arm) equals
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`] (the
        // [`LayoutError::MissingEntry`] `kind:` leaf-kind categorization
        // arm) verbatim — the M0 `:kind Binario` on-disk-directory axis
        // and the [`crate::LayoutError::MissingEntry`] `kind:` leaf-kind
        // discriminator name the same three-byte sub-tree (`exe/`), a
        // coincidence [`crate::LayoutInvariants::verify`] itself relies
        // on: it joins `root` with [`crate::render::LAYOUT_DIR_EXE`] to
        // reconstruct `exe_dir` and emits [`crate::LayoutError::MissingEntry
        // { kind: LAYOUT_MISSING_ENTRY_KIND_EXE, path: <under exe_dir> }`]
        // for every non-resolving entry. Making the coincidence
        // load-bearing means a future rebrand touching either axis
        // without the other (a per-consumer disambiguation collapsing
        // the leaf-kind label onto `"binary"` while the directory stays
        // `"exe"`, or vice versa) trips at caixa-core build time rather
        // than surfacing at runtime as a mismatched
        // [`crate::LayoutInvariants::verify`] diagnostic whose `kind:`
        // reads one label while the `path:` sits under a differently-named
        // sub-tree.
        assert_eq!(
            crate::render::LAYOUT_DIR_EXE,
            crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE,
            "LAYOUT_DIR_EXE must equal LAYOUT_MISSING_ENTRY_KIND_EXE — \
             both name the M0 `:kind Binario` sub-tree by the same \
             three-byte scalar"
        );
    }

    #[test]
    fn layout_dir_bib_is_distinct_from_layout_missing_entry_kind_bib() {
        // Cross-axis distinctness pin: [`crate::render::LAYOUT_DIR_LIB`]
        // (`"lib"`, the Cargo-style abbreviated on-disk directory name)
        // is *deliberately* distinct from
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA`]
        // (`"biblioteca"`, the full-form Portuguese-native leaf-kind
        // label) — the substrate splits the on-disk convention terse
        // (`lib/`) from the diagnostic vocabulary full (`biblioteca`),
        // matching Cargo's `src/lib.rs` abbreviation of the `library`
        // crate-type discriminator. A future accidental collapse of the
        // two axes onto one scalar (a rebrand aligning either arm with
        // the other for schema-clarity, an English-uniformity pass that
        // renames `LAYOUT_DIR_LIB` to `LAYOUT_DIR_BIBLIOTECA` or the
        // diagnostic label to `"lib"`) would silently reroute either
        // consumer onto the other's byte-string. This pin catches the
        // collapse at build time. Peer of the sibling
        // [`layout_missing_entry_kind_m0_consts_align_with_caixa_kind_as_str`]
        // (fe2a898) that pins the analogous *equality* between the M0
        // `:kind Biblioteca` diagnostic-label arm and
        // [`crate::CaixaKind::Biblioteca`]'s [`crate::CaixaKind::as_str`]
        // output — the two pins jointly encode the "which of the three
        // Biblioteca-related scalars are load-bearing-equal, which are
        // load-bearing-distinct" invariant across the substrate's
        // per-kind vocabulary.
        assert_ne!(
            crate::render::LAYOUT_DIR_LIB,
            crate::render::LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA,
            "LAYOUT_DIR_LIB (`\"lib\"`) and LAYOUT_MISSING_ENTRY_KIND_BIBLIOTECA \
             (`\"biblioteca\"`) name two distinct axes — the on-disk \
             directory convention (Cargo-style abbreviated) and the \
             layout-diagnostic leaf-kind label (full-form Portuguese) — \
             and must not silently collapse onto one scalar"
        );
    }

    #[test]
    fn layout_dir_servicos_is_distinct_from_layout_missing_entry_kind_servico() {
        // Cross-axis distinctness pin: [`crate::render::LAYOUT_DIR_SERVICOS`]
        // (`"servicos"`, the Portuguese-*plural* on-disk directory
        // name) is *deliberately* distinct from
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO`]
        // (`"servico"`, the singular leaf-kind label) — the on-disk
        // sub-tree houses one-or-more ComputeUnit YAML descriptors per
        // caixa (hence the plural), the diagnostic label names the
        // caixa's own kind (singular). A future accidental collapse
        // onto one scalar (a per-consumer disambiguation aligning the
        // two, a hypothetical English-uniformity pass renaming
        // `"servicos"` → `"services"` while retaining `"servico"` on
        // the diagnostic arm — or vice versa) would silently reroute
        // either consumer onto the other's byte-string. Peer of the
        // sibling [`layout_dir_bib_is_distinct_from_layout_missing_entry_kind_bib`]
        // pin on the M0 `:kind Biblioteca` split axis; two of the three
        // per-kind on-disk / leaf-kind splits carry a distinctness
        // pin here, the third ([`crate::render::LAYOUT_DIR_EXE`] vs
        // [`crate::render::LAYOUT_MISSING_ENTRY_KIND_EXE`]) carries an
        // equality pin under
        // [`layout_dir_exe_matches_layout_missing_entry_kind_exe`].
        assert_ne!(
            crate::render::LAYOUT_DIR_SERVICOS,
            crate::render::LAYOUT_MISSING_ENTRY_KIND_SERVICO,
            "LAYOUT_DIR_SERVICOS (`\"servicos\"`, plural on-disk sub-tree) \
             and LAYOUT_MISSING_ENTRY_KIND_SERVICO (`\"servico\"`, singular \
             leaf-kind label) name two distinct axes and must not silently \
             collapse onto one scalar"
        );
    }

    #[test]
    fn layout_invariants_reconstruct_sandbox_roots_through_lifted_layout_dir_consts() {
        // Production-through-const pin: [`LayoutInvariants::verify`]
        // routes its three per-kind sandbox-root joins
        // (`root.join(LAYOUT_DIR_LIB)` for the `:kind Biblioteca`
        // default `lib/<nome>.lisp` reconstruction, `root.join(LAYOUT_DIR_EXE)`
        // for the [`LayoutError::ExeOutsideDir`] gate,
        // `root.join(LAYOUT_DIR_SERVICOS)` for the
        // [`LayoutError::ServicoOutsideDir`] gate) through the three
        // lifted consts, not through inline `"lib"` / `"exe"` /
        // `"servicos"` `&str` literals. This test drives the
        // [`LayoutError::ExeOutsideDir`] arm through a `:kind Binario`
        // caixa whose declared `:exe` entry deliberately escapes
        // `root.join(LAYOUT_DIR_EXE)` (a sibling `bin/tool` path) —
        // if the production emit reads the wrong const (or reverts to
        // an inline literal that drifts from the const) the diagnostic
        // arm surfaces the wrong variant, catching the drift at build
        // time rather than as a per-invocation runtime mismatch.
        //
        // Mirror of the peer production-through-const pin
        // [`crate::dep::tests::validate_no_self_dep_deps_field_routes_through_dep_author_key`]
        // (4da6fba) on the sibling M0 `:deps` `list:` diagnostic axis.
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let bin_entry_outside = root.join("bin/tool");
        let mut c = caixa(CaixaKind::Binario);
        c.exe = vec!["bin/tool".into()];
        let manifest_clone = manifest.clone();
        let outside_clone = bin_entry_outside.clone();
        let layout = StandardLayout::new()
            .with_path_exists(move |p| p == manifest_clone || p == outside_clone);
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ExeOutsideDir(path) => {
                assert_eq!(
                    path, bin_entry_outside,
                    "ExeOutsideDir must carry the resolved `:exe` entry that \
                     escapes `root.join(LAYOUT_DIR_EXE)`"
                );
                // Byte-identity check: the escape must be against the
                // lifted `LAYOUT_DIR_EXE` sub-tree, not a stale inline
                // literal — a future const-edit that drifts from `"exe"`
                // reroutes `exe_dir` off the sandbox `bin/tool` escapes
                // from, and this pattern-arm miss re-surfaces here.
                assert!(
                    !path.starts_with(root.join(crate::render::LAYOUT_DIR_EXE)),
                    "resolved `:exe` entry {path:?} must escape the \
                     `root.join(LAYOUT_DIR_EXE)` sub-tree the production \
                     emit uses to gate the [`LayoutError::ExeOutsideDir`] arm"
                );
            }
            other => panic!("expected ExeOutsideDir, got {other:?}"),
        }
    }

    #[test]
    fn upgrade_state_change_without_behavior_callback_surfaces_as_upgrade_violation() {
        // Wiring pin for the cross-slot composition gate
        // (`validate_upgrade_from_against_behavior`): a caixa whose
        // `:upgrade-from` declares a `(:state-change "lib/m.lisp")`
        // instruction but does not declare `:behavior :on-state-change`
        // surfaces at `feira build` time as a `LayoutError::UpgradeViolation`
        // naming the offending caixa + the entry's `:from` + the
        // offending script — not at hot-upgrade dispatch when the
        // operator reaches for the missing callback. Mirrors
        // `upgrade_from_downgrade_surfaces_as_upgrade_violation` on the
        // peer `:from` ↔ `:versao` cross-slot precedence gate.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.versao = "0.2.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        // `:behavior` is None (the canonical "I added the upgrade path
        // but never declared :behavior" footgun the gate closes); a
        // peer arm covers the BehaviorSpec-Some-but-on-state-change-
        // None shape in `upgrade::tests::behavior_gate_rejects_state_
        // change_when_on_state_change_is_none`.
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![
                UpgradeInstruction::LoadModule {
                    module: "demo".into(),
                },
                UpgradeInstruction::StateChange {
                    script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
                },
            ],
        }];
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::UpgradeViolation { caixa, issue } => {
                assert_eq!(caixa, "demo", "diagnostic must name the offending caixa");
                assert!(
                    issue.contains(crate::render::M2_BEHAVIOR_AUTHOR_KEY_ON_STATE_CHANGE),
                    "diagnostic must name the missing callback slot for self-locating fix, \
                     got {issue:?}"
                );
                assert!(
                    issue.contains("0.1.0"),
                    "diagnostic must name the offending entry's :from, got {issue:?}"
                );
                assert!(
                    issue.contains("v01-to-v02.lisp"),
                    "diagnostic must name the offending :script for self-locating fix, \
                     got {issue:?}"
                );
            }
            other => panic!("expected UpgradeViolation, got {other:?}"),
        }
    }

    #[test]
    fn supervisor_must_have_children() {
        use crate::RestartStrategy;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        // No children → should fail
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::SupervisorViolation { .. }));
    }

    #[test]
    fn supervisor_self_referential_child_is_violation() {
        // A Supervisor whose `:children` names its own `:nome` is a
        // one-node supervision cycle. The cross-slot gate fires at
        // verify time, surfacing as a SupervisorViolation that names the
        // offending supervisor — not at the cluster apply far from
        // source. The `caixa()` helper's `:nome` is "demo".
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        c.children = vec![
            ChildSpec {
                caixa: "worker".into(),
                versao: "^0.1".into(),
                restart: RestartPolicy::Permanent,
            },
            ChildSpec {
                caixa: "demo".into(),
                versao: "^0.1".into(),
                restart: RestartPolicy::Permanent,
            },
        ];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::SupervisorViolation { caixa, issue } = err else {
            panic!("expected SupervisorViolation for self-referential child, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("demo") && issue.contains("itself"),
            "issue must name the self-supervising caixa, got {issue:?}"
        );
    }

    #[test]
    fn supervisor_distinct_children_pass_self_supervision_gate() {
        // Positive control: a Supervisor whose children are all distinct
        // from its own `:nome` verifies cleanly.
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        c.children = vec![ChildSpec {
            caixa: "worker".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor() {
        // Composition pin: every cross-slot self-edge gate fired from
        // `LayoutInvariants::verify` — the supervision-tree arm's
        // `crate::supervisor::validate_no_self_supervision` call, the
        // Aplicacao arm's `crate::aplicacao::validate_no_self_membership`
        // call, and the dep-graph arm's
        // `crate::dep::validate_no_self_dep` call — must key its
        // `parent_nome` arg off the typed [`Caixa::nome`] accessor, not
        // the raw `&caixa.nome` `&String`-borrow of the underlying
        // field.
        //
        // Structurally: a rename of the storage field or a hypothetical
        // accessor rebrand (a per-cluster alias table pinned through a
        // future `:placement`-scoped slot, the M4 CR materializer's
        // per-CR namespace-qualified rewrite, a `:nome-suffix` overlay
        // the MESH-COMPOSITION §III.2 roadmap acknowledges) would land
        // through the accessor by construction; a raw-borrow bypass
        // would silently disagree with every peer consumer that already
        // routes through `caixa.nome()` (the caixa-mesh 980c059,
        // caixa-helm 22461ef, caixa-flux 162e2e2, caixa-crd 61d3429,
        // caixa-feira ef83332 raw-borrow converges), reintroducing the
        // drift surface the sibling converges closed. Each arm fires
        // its per-kind `LayoutError` variant (`SupervisorViolation` /
        // `AplicacaoViolation` / `DepsViolation`) whose `caixa` field
        // carries the offending parent name verbatim through
        // `caixa.nome().clone()`; asserting the field equals
        // `caixa.nome()` on the mutated fixture pins the accessor-
        // routed parent-nome projection at every call site — a future
        // silent detour that had the gate observe a stale / aliased
        // name at the arg boundary would surface here as a
        // `caixa != "demo"` inequality.
        //
        // Peer of the sibling per-caixa-crate `nome`-arg raw-borrow
        // convergence pin discipline (54bf2f3 / 22461ef / 162e2e2 on the
        // renderer crates; ef83332 on the CLI) — extends the "one typed
        // dispatch per `:nome` consumer" discipline onto the substrate's
        // own [`LayoutInvariants::verify`] cross-slot self-edge gate
        // wire-up on all three typed-name-graph kinds.
        use crate::{
            ChildSpec, Dep, Membro, Placement, PlacementStrategy, RestartPolicy, RestartStrategy,
        };
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);

        // Supervisor arm — the `caixa()` helper's `:nome` is "demo",
        // and the accessor's return `caixa.nome()` must equal the
        // parent-nome that the self-supervision gate observes.
        let mut sup = caixa(CaixaKind::Supervisor);
        sup.estrategia = Some(RestartStrategy::OneForOne);
        sup.max_restarts = Some(5);
        sup.children = vec![ChildSpec {
            caixa: "demo".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        let parent_nome_via_accessor = sup.nome();
        assert_eq!(
            parent_nome_via_accessor, "demo",
            "the caixa() fixture helper's `:nome` must be \"demo\"\
             the accessor's return is the pin's ground truth for the \
             cross-slot gate's parent-nome arg",
        );
        let err = layout.verify(&sup, &root).unwrap_err();
        let LayoutError::SupervisorViolation { caixa: c_nome, .. } = err else {
            panic!("expected SupervisorViolation for self-referential child, got {err:?}");
        };
        assert_eq!(
            c_nome, parent_nome_via_accessor,
            "the SupervisorViolation's `caixa` field must equal \
             `sup.nome()` — the cross-slot self-supervision gate's \
             `parent_nome` arg must route through the lifted \
             [`Caixa::nome`] accessor, not the raw `&caixa.nome` \
             `&String`-borrow of the underlying field",
        );

        // Aplicacao arm — same discipline on the peer typed-name-graph
        // kind. Constructed alongside the supervisor arm so any future
        // accessor drift lands on both arms in the same pin.
        let mut app = caixa(CaixaKind::Aplicacao);
        app.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        app.membros = vec![Membro {
            caixa: "demo".into(),
            versao: "^0.1".into(),
        }];
        let parent_nome_via_accessor = app.nome();
        assert_eq!(
            parent_nome_via_accessor, "demo",
            "the caixa() fixture helper's `:nome` must be \"demo\" on \
             the Aplicacao arm too — same accessor-ground-truth as the \
             sibling supervisor arm above",
        );
        let err = layout.verify(&app, &root).unwrap_err();
        let LayoutError::AplicacaoViolation { caixa: c_nome, .. } = err else {
            panic!("expected AplicacaoViolation for self-referential membro, got {err:?}");
        };
        assert_eq!(
            c_nome, parent_nome_via_accessor,
            "the AplicacaoViolation's `caixa` field must equal \
             `app.nome()` — the cross-slot self-membership gate's \
             `parent_nome` arg must route through the lifted \
             [`Caixa::nome`] accessor, not the raw `&caixa.nome` \
             `&String`-borrow of the underlying field",
        );

        // Dep-graph arm — third typed-name-graph kind on the
        // `parent_nome` arg boundary. Same discipline as the peer
        // supervision-tree and Aplicacao-membership arms above.
        // Constructed alongside so any future accessor drift lands on
        // all three arms in the same pin. Needs a distinct layout
        // fixture from the supervisor / aplicacao arms above because
        // the `Biblioteca` kind's code-path existence gate demands the
        // canonical `lib/<nome>.lisp` path also `exists`, so the shim
        // covers both `caixa.lisp` and `lib/demo.lisp`.
        let default_lib = root.join("lib").join("demo.lisp");
        let manifest_dep = manifest.clone();
        let default_lib_clone = default_lib.clone();
        let layout_dep = StandardLayout::new()
            .with_path_exists(move |p| p == manifest_dep || p == default_lib_clone);
        let mut lib = caixa(CaixaKind::Biblioteca);
        lib.deps = vec![Dep::simple("demo", "^0.1")];
        let parent_nome_via_accessor = lib.nome();
        assert_eq!(
            parent_nome_via_accessor, "demo",
            "the caixa() fixture helper's `:nome` must be \"demo\" on \
             the Biblioteca arm too — same accessor-ground-truth as the \
             sibling supervisor + Aplicacao arms above",
        );
        let err = layout_dep.verify(&lib, &root).unwrap_err();
        let LayoutError::DepsViolation { caixa: c_nome, .. } = err else {
            panic!("expected DepsViolation for self-referential :deps entry, got {err:?}");
        };
        assert_eq!(
            c_nome, parent_nome_via_accessor,
            "the DepsViolation's `caixa` field must equal \
             `lib.nome()` — the cross-slot self-dep gate's `parent_nome` \
             arg must route through the lifted [`Caixa::nome`] accessor, \
             not the raw `&caixa.nome` `&String`-borrow of the underlying \
             field",
        );
    }

    #[test]
    fn upgrade_against_versao_gate_routes_current_versao_through_lifted_accessor() {
        // Composition pin: the cross-slot `:upgrade-from :from` ↔
        // `:versao` precedence gate fired from
        // `LayoutInvariants::verify` — the
        // `crate::upgrade::validate_upgrade_from_against_versao` call —
        // must key its `versao` arg off the typed [`Caixa::versao`]
        // accessor, not the raw `&caixa.versao` `&String`-borrow of
        // the underlying field.
        //
        // Same "arg-boundary reads through the lifted accessor"
        // discipline as the sibling
        // [`cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor`]
        // pin above on the `:nome`-arg axis of the three typed-name-
        // graph self-edge gates — extended here onto the `:versao`-arg
        // axis of the substrate's remaining `LayoutInvariants::verify`
        // cross-slot arg-carrying call site. Structurally byte-equal
        // today (the accessor is `pub fn versao(&self) -> &str { &self.versao }`,
        // so both paths coerce to the same `&str`); the pin catches a
        // future silent detour (an accessor rebrand that no longer
        // shipped the raw slot verbatim — a per-`:edicao` overlay,
        // a promotion of `:versao` to a `CaixaVersion` newtype with a
        // canonicalizing accessor, an M4 CR-materializer-side pinning
        // through a resolver-annotated `:versao-resolved` slot) that
        // would silently split the substrate's own precedence gate
        // from every peer consumer already routing `:versao` reads
        // through the lifted accessor.
        //
        // The gate fires an `UpgradeViolation { caixa, issue }` when a
        // `:upgrade-from` entry's `:from` is not strictly less than
        // the top-level `:versao` — the `issue` string names both the
        // offending prior version and the current version verbatim,
        // so asserting the substring `caixa.versao()` appears in the
        // fired diagnostic pins the accessor-routed current-versao
        // projection at the arg boundary. A raw-borrow bypass would
        // still surface the same bytes today, but the presence of
        // this pin makes any future divergence between the accessor's
        // return and the raw slot's contents a build-time failure at
        // this call site.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let servico_path = root.join("servicos").join("demo.computeunit.yaml");
        let manifest_clone = manifest.clone();
        let servico_clone = servico_path.clone();
        let layout = StandardLayout::new()
            .with_path_exists(move |p| p == manifest_clone || p == servico_clone);
        let mut svc = caixa(CaixaKind::Servico);
        svc.versao = "0.1.0".into();
        svc.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        // `:from` >= current `:versao` — trips the precedence gate the
        // `validate_upgrade_from_against_versao` cross-slot call
        // enforces. `:load-module` carries no on-disk path so the
        // path-existence gate downstream stays inert; the precedence
        // gate is what fires. No `:on-state-change` needed because the
        // instruction list carries no `:state-change` entry, so the
        // sibling `validate_upgrade_from_against_behavior` gate is
        // inert too.
        svc.upgrade_from = vec![UpgradeFromEntry {
            from: "0.2.0".into(),
            instructions: vec![UpgradeInstruction::LoadModule {
                module: "demo".into(),
            }],
        }];
        let current_versao_via_accessor = svc.versao().to_string();
        assert_eq!(
            current_versao_via_accessor, "0.1.0",
            "the mutated fixture's `:versao` must be observable through \
             the accessor before layout verification fires — a drift on \
             `Caixa::versao` would surface here as a `!= \"0.1.0\"` \
             inequality",
        );
        let err = layout.verify(&svc, &root).unwrap_err();
        let LayoutError::UpgradeViolation {
            caixa: c_nome,
            issue,
        } = err
        else {
            panic!("expected UpgradeViolation for :from >= :versao, got {err:?}");
        };
        assert_eq!(c_nome, svc.nome(), "wrap envelope names the caixa");
        assert!(
            issue.contains(&current_versao_via_accessor),
            "the UpgradeViolation's `issue` must quote the current \
             `:versao` byte-string verbatim — the cross-slot precedence \
             gate's `versao` arg must route through the lifted \
             [`Caixa::versao`] accessor, not the raw `&caixa.versao` \
             `&String`-borrow of the underlying field. issue: {issue}",
        );
    }

    #[test]
    fn layout_violation_envelopes_carry_caixa_nome_through_lifted_accessor() {
        // Wrap-envelope drift-detection pin: every per-axis
        // `LayoutError::*Violation { caixa, issue }` envelope fired
        // from `LayoutInvariants::verify` must key its offending-caixa
        // field off the typed [`Caixa::nome`] accessor's
        // `.to_string()` extension, not the raw
        // `caixa.nome.clone()` `String::clone()` of the underlying
        // field. Structurally byte-equal today (each accessor is
        // `pub fn nome(&self) -> &str { &self.nome }`, so
        // `caixa.nome().to_string()` and `caixa.nome.clone()` produce
        // the same bytes); the pin catches a future silent detour
        // (an accessor rebrand that no longer shipped the raw slot
        // verbatim — a per-cluster alias table pinned through a
        // future `:placement`-scoped slot, the M4 CR materializer's
        // per-CR namespace-qualified rewrite, a `:nome-suffix`
        // overlay the MESH-COMPOSITION §III.2 roadmap acknowledges)
        // that would silently split the substrate's own layout
        // invariant verifier's diagnostic surface from every peer
        // caixa-crate consumer that already routes `:nome` reads
        // through the lifted accessor (the caixa-mesh 980c059,
        // caixa-helm 22461ef, caixa-flux 162e2e2, caixa-crd 61d3429,
        // caixa-feira ef83332 raw-borrow converges).
        //
        // Exercises a representative variant on each of the three
        // wrap-envelope arm shapes the substrate's per-axis fan-out
        // carries: (1) `LayoutError::NomeViolation` (the leading arm
        // in the `verify` order — the `:nome` axis's DNS-1123 shape
        // gate fires immediately after the manifest-existence gate),
        // (2) `LayoutError::BinarioWithoutExe` (a tuple-variant on
        // the kind-coherence family — different envelope shape than
        // the struct-variant `*Violation { caixa, issue }` family
        // but the same converge target on the `caixa.nome().to_string()`
        // arg), and (3) `LayoutError::ServicoWithoutServicos` (the
        // sibling tuple-variant on the same kind-coherence family).
        // Together they cover the two `LayoutError` envelope shapes
        // (struct-variant + tuple-variant) the layout invariants file
        // emits on `:nome`-carrying arms.
        //
        // Peer of the sibling
        // [`cross_slot_self_edge_gates_route_parent_nome_through_lifted_accessor`]
        // pin above — extends the "wrap-envelope `caixa:` field
        // reads through the lifted accessor" discipline from the
        // cross-slot self-edge gates' `parent_nome` arg boundary
        // onto the per-axis `LayoutError::*Violation` envelope's
        // `caixa:` field boundary.

        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);

        // (1) `NomeViolation` on the struct-variant envelope: force a
        // DNS-1123-invalid `:nome` (uppercase byte — `is_dns_1123_label`
        // rejects) and assert the fired envelope's `caixa:` field
        // byte-equals `c.nome().to_string()`.
        let mut c = caixa(CaixaKind::Biblioteca);
        c.nome = "BAD_NAME".into();
        c.bibliotecas = vec!["lib/demo.lisp".into()];
        let expected_nome_via_accessor = c.nome().to_string();
        assert_eq!(
            expected_nome_via_accessor, "BAD_NAME",
            "the mutated fixture's `:nome` must be observable through \
             the accessor before layout verification fires — a drift \
             on `Caixa::nome` would surface here as a `!= \"BAD_NAME\"` \
             inequality",
        );
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::NomeViolation { caixa: c_nome, .. } = err else {
            panic!("expected NomeViolation for DNS-1123-invalid :nome, got {err:?}");
        };
        assert_eq!(
            c_nome, expected_nome_via_accessor,
            "the NomeViolation's `caixa` field must equal \
             `c.nome().to_string()` — the wrap envelope's per-axis \
             projection must route through the lifted [`Caixa::nome`] \
             accessor's `.to_string()` extension, not the raw \
             `caixa.nome.clone()` `String::clone()` of the underlying \
             field",
        );

        // (2) `BinarioWithoutExe` on the tuple-variant envelope: a
        // Binario-kind caixa with an empty `:exe` list fires the
        // kind-coherence gate whose payload is a bare `String`, so the
        // pattern is `LayoutError::BinarioWithoutExe(String)` rather
        // than the struct-variant `{ caixa, issue }` family. The
        // converge target is the same — `caixa.nome().to_string()` — but
        // the envelope shape is different, so the pin exercises both.
        let mut c = caixa(CaixaKind::Binario);
        // `:exe` empty is the trigger — the fixture helper defaults
        // it to `vec![]`, so no mutation is needed.
        c.nome = "binario-demo".into();
        let expected_nome_via_accessor = c.nome().to_string();
        assert_eq!(
            expected_nome_via_accessor, "binario-demo",
            "the mutated fixture's `:nome` must be observable through \
             the accessor before layout verification fires",
        );
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::BinarioWithoutExe(c_nome) = err else {
            panic!("expected BinarioWithoutExe for empty :exe list on Binario kind, got {err:?}");
        };
        assert_eq!(
            c_nome, expected_nome_via_accessor,
            "the BinarioWithoutExe's payload must equal \
             `c.nome().to_string()` — the tuple-variant envelope's \
             per-axis projection must route through the lifted \
             [`Caixa::nome`] accessor's `.to_string()` extension, not \
             the raw `caixa.nome.clone()` `String::clone()` of the \
             underlying field",
        );

        // (3) `ServicoWithoutServicos` on the sibling tuple-variant
        // envelope: same discipline on the peer kind-coherence
        // partition arm. Constructed alongside the Binario arm so any
        // future accessor drift lands on both arms in the same pin.
        let mut c = caixa(CaixaKind::Servico);
        // `:servicos` empty is the trigger — the fixture helper
        // defaults it to `vec![]`, so no mutation is needed.
        c.nome = "servico-demo".into();
        let expected_nome_via_accessor = c.nome().to_string();
        assert_eq!(
            expected_nome_via_accessor, "servico-demo",
            "the mutated fixture's `:nome` must be observable through \
             the accessor before layout verification fires",
        );
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::ServicoWithoutServicos(c_nome) = err else {
            panic!(
                "expected ServicoWithoutServicos for empty :servicos list on Servico kind, \
                 got {err:?}"
            );
        };
        assert_eq!(
            c_nome, expected_nome_via_accessor,
            "the ServicoWithoutServicos's payload must equal \
             `c.nome().to_string()` — same converge discipline as the \
             sibling `BinarioWithoutExe` tuple-variant arm above",
        );
    }

    #[test]
    fn supervisor_must_not_have_bibliotecas() {
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        c.bibliotecas = vec!["lib/code.lisp".into()];
        c.children = vec![ChildSpec {
            caixa: "worker".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::SupervisorOwnsCode(_)));
    }

    // ── Caixa::validate_restart_window wired into Supervisor verify ─────
    //
    // Until this wire-up landed `Caixa::validate_restart_window` lived as
    // `pub fn` on `Caixa` with full per-arm unit coverage in
    // `manifest::tests` (`validate_restart_window_rejects_*` — fractional,
    // decimal-shaped integer, half-unit minute, leading sign, unknown
    // unit, garbage, empty-after-trim) but no production path called it;
    // `feira build` silently accepted malformed `:restart-window` and
    // `Caixa::supervisor_view` soft-swallowed the parse failure as
    // `restart_window: None` (the canonical "no reset" sentinel), turning
    // every authoring footgun into a never-reset supervisor far from the
    // source caixa.lisp. The following pins fence the layout-pipeline
    // wire-up: every layout verify on a structurally-invalid `:restart-
    // window` axis surfaces the per-axis `RestartWindowViolation { caixa,
    // issue }` envelope before the typed `SupervisorSpec::validate` gate
    // sees the laundered `None`.

    fn supervisor_with_window(window: Option<&str>) -> Caixa {
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        c.restart_window = window.map(str::to_string);
        c.children = vec![ChildSpec {
            caixa: "worker".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        c
    }

    #[test]
    fn restart_window_violation_on_fractional_seconds() {
        // `"1.5s"` is the canonical fractional-seconds drift footgun the
        // shared integer-magnitude codec (1c55a2a) rejects: round-trips
        // through `render` as `"1500ms"` on first serialize, breaking
        // THEORY.md §V.2.7 render-determinism. Before this wire-up
        // `supervisor_view` soft-swallowed the parse error as
        // `restart_window: None`, masking the drift as a never-reset
        // supervisor.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let c = supervisor_with_window(Some("1.5s"));
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::RestartWindowViolation { caixa, issue } = err else {
            panic!("expected LayoutError::RestartWindowViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("1.5s"),
            "issue must quote the offending raw value: {issue}",
        );
    }

    #[test]
    fn restart_window_violation_on_decimal_shaped_integer() {
        // `"1.0s"` — decimal-shaped integer the codec also rejects (a
        // canonical authoring form is `"1s"`). Sibling of the fractional
        // case; same codec arm.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let c = supervisor_with_window(Some("1.0s"));
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(
                err,
                LayoutError::RestartWindowViolation { ref caixa, ref issue }
                    if caixa == "demo" && issue.contains("1.0s")
            ),
            "got {err:?}",
        );
    }

    #[test]
    fn restart_window_violation_on_leading_sign() {
        // `"+30s"` / `"-30s"` — leading-sign drift the codec rejects.
        // Canonical form is `"30s"`. Pin both signs separately because
        // a future relaxation might accept one but not the other.
        for raw in ["+30s", "-30s"] {
            let root = PathBuf::from("/tmp/x");
            let manifest = root.join("caixa.lisp");
            let manifest_clone = manifest.clone();
            let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
            let c = supervisor_with_window(Some(raw));
            let err = layout.verify(&c, &root).unwrap_err();
            assert!(
                matches!(
                    err,
                    LayoutError::RestartWindowViolation { ref caixa, ref issue }
                        if caixa == "demo" && issue.contains(raw)
                ),
                "leading-sign {raw:?} got {err:?}",
            );
        }
    }

    #[test]
    fn restart_window_violation_on_unknown_unit() {
        // `"30x"` — unknown duration unit. The codec admits only
        // `ms`/`s`/`m`/`h`.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let c = supervisor_with_window(Some("30x"));
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(
                err,
                LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"
            ),
            "got {err:?}",
        );
    }

    #[test]
    fn restart_window_violation_on_garbage() {
        // `"abc"` — pure garbage. The codec's parse fails before the
        // unit dispatch; the wrap envelope still surfaces the
        // self-locating diagnostic at the source.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let c = supervisor_with_window(Some("abc"));
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"),
            "got {err:?}",
        );
    }

    #[test]
    fn restart_window_violation_on_empty_string() {
        // `""` — empty after trim. The shared codec's digit-only gate
        // refuses an empty magnitude. Distinguished here from the
        // `None` ("omit the slot") canonical authoring shape: an empty
        // string is an authored-but-empty slot, never the author's
        // intent.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let c = supervisor_with_window(Some(""));
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::RestartWindowViolation { ref caixa, .. } if caixa == "demo"),
            "got {err:?}",
        );
    }

    #[test]
    fn verify_accepts_supervisor_without_restart_window() {
        // `None` is the canonical "omit the slot to express no reset"
        // shape — never reaches the codec, validates cleanly.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let c = supervisor_with_window(None);
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn verify_accepts_supervisor_with_canonical_restart_window() {
        // Every canonical form the shared codec round-trips losslessly
        // must pass — `"500ms"`, `"30s"`, `"60s"`, `"1m"`, `"2m"`,
        // `"1h"`. Pin every form so a future tightening of the codec's
        // accepted set surfaces here as a test failure.
        for form in ["500ms", "30s", "60s", "1m", "2m", "1h"] {
            let root = PathBuf::from("/tmp/x");
            let manifest = root.join("caixa.lisp");
            let manifest_clone = manifest.clone();
            let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
            let c = supervisor_with_window(Some(form));
            layout
                .verify(&c, &root)
                .unwrap_or_else(|e| panic!("canonical {form:?} must validate, got {e:?}"));
        }
    }

    #[test]
    fn restart_window_violation_fires_before_supervisor_view_validate() {
        // Diagnostic-precedence pin: a Supervisor with a malformed
        // `:restart-window` AND a typed-shape defect on the typed view
        // (zero `:max-restarts`, which `SupervisorSpec::validate`'s
        // `ZeroMaxRestarts` arm rejects) surfaces the raw-string
        // diagnostic first — the narrower self-locating gate wins. Until
        // this wire-up landed `supervisor_view` would silently launder
        // the malformed `:restart-window` to `None` and then the typed
        // view's `ZeroMaxRestarts` gate would surface, masking the
        // raw-string footgun.
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(0);
        c.restart_window = Some("1.5s".into());
        c.children = vec![ChildSpec {
            caixa: "worker".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::RestartWindowViolation { .. }),
            "got {err:?} — RestartWindowViolation must fire before SupervisorViolation",
        );
    }

    #[test]
    fn supervisor_slots_on_non_supervisor_fires_before_restart_window_violation() {
        // Order pin: a non-Supervisor caixa with a malformed
        // `:restart-window` surfaces `SupervisorSlotsOnNonSupervisor`
        // (the kind-coherence gate at the top of verify) before the
        // raw-string parse gate inside the Supervisor branch — because
        // `:restart-window` is foreign to non-Supervisor kinds, the
        // kind-coherence diagnostic is the load-bearing one. Mirrors
        // the existing `nome_violation_on_*` ordering tests that fence
        // the precedence between universal and kind-specific gates.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let default_lib = root.join("lib").join("demo.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == default_lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.restart_window = Some("1.5s".into());
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::SupervisorSlotsOnNonSupervisor { .. }),
            "got {err:?} — kind-coherence must fire before RestartWindowViolation",
        );
    }

    #[test]
    fn restart_window_violation_diagnostic_carries_offending_value() {
        // Diagnostic-shape pin: the wrap envelope's `issue` carries the
        // codec's parser-shaped reason verbatim (which names the
        // offending raw value), so the author can grep their caixa.lisp
        // for `:restart-window "<value>"` and fix in one edit. Mirrors
        // `nome_violation_*_carries_offending_*` shape pins.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let c = supervisor_with_window(Some("0.5m"));
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::RestartWindowViolation { caixa, issue } = err else {
            panic!("expected LayoutError::RestartWindowViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("0.5m"),
            "issue must quote the offending raw value verbatim: {issue}",
        );
        assert!(
            !issue.is_empty(),
            "issue must carry the codec's parser-shaped reason",
        );
    }

    // ── Aplicacao layout tests ──────────────────────────────────────────

    #[test]
    fn aplicacao_must_have_membros() {
        use crate::{Membro, Placement, PlacementStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        // No membros → fails
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::AplicacaoViolation { .. }));

        // With membros → passes
        c.membros = vec![Membro {
            caixa: "service-a".into(),
            versao: "^0.1".into(),
        }];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn aplicacao_self_referential_membro_is_violation() {
        // An Aplicacao whose `:membros` names its own `:nome` is a
        // one-node lacre-closure recursion. The cross-slot gate fires
        // at verify time, surfacing as an AplicacaoViolation that
        // names the offending aplicacao — not at lacre-resolve time
        // far from source. The `caixa()` helper's `:nome` is "demo".
        // Peer of `supervisor_self_referential_child_is_violation`
        // on the supervision-tree axis.
        use crate::{Membro, Placement, PlacementStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        c.membros = vec![
            Membro {
                caixa: "service-a".into(),
                versao: "^0.1".into(),
            },
            Membro {
                caixa: "demo".into(),
                versao: "^0.1".into(),
            },
        ];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::AplicacaoViolation { caixa, issue } = err else {
            panic!("expected AplicacaoViolation for self-referential membro, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("demo") && issue.contains("lists itself"),
            "issue must name the self-membering aplicacao, got {issue:?}"
        );
    }

    #[test]
    fn aplicacao_distinct_membros_pass_self_membership_gate() {
        // Positive control: an Aplicacao whose membros are all distinct
        // from its own `:nome` verifies cleanly.
        use crate::{Membro, Placement, PlacementStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        c.membros = vec![
            Membro {
                caixa: "service-a".into(),
                versao: "^0.1".into(),
            },
            Membro {
                caixa: "service-b".into(),
                versao: "^0.1".into(),
            },
        ];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn aplicacao_self_membership_fires_after_view_validate() {
        // Diagnostic-precedence pin: a self-referential membro alongside
        // a duplicate-:caixa shape surfaces the more-fundamental
        // `MembroDuplicate` (from `view.validate()`) first; only when the
        // per-membros shape diagnostics pass does the cross-slot
        // self-membership gate fire. Mirrors the ordering pin
        // `supervisor_self_referential_child_is_violation` carries on
        // the peer supervision-tree axis (`view.validate()` runs first,
        // then the cross-slot gate). Without this ordering a future
        // refactor that swaps the two calls would silently mask the
        // narrower per-membro defect.
        use crate::{Membro, Placement, PlacementStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        c.membros = vec![
            Membro {
                caixa: "service-a".into(),
                versao: "^0.1".into(),
            },
            Membro {
                caixa: "service-a".into(),
                versao: "^0.2".into(),
            },
            Membro {
                caixa: "demo".into(),
                versao: "^0.1".into(),
            },
        ];
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::AplicacaoViolation { issue, .. } = err else {
            panic!("expected AplicacaoViolation, got {err:?}");
        };
        // The per-membros duplicate diagnostic (from view.validate())
        // surfaces ahead of the cross-slot self-membership gate, so the
        // `service-a` duplicate is named — not the `demo` self-reference.
        assert!(
            issue.contains("service-a") && issue.contains("more than once"),
            "duplicate-:caixa diagnostic must surface before self-membership gate, \
             got {issue:?}"
        );
    }

    #[test]
    fn mesh_slots_on_servico_rejected() {
        // The canonical real-world footgun: an author adds :entrada to a
        // :kind Servico expecting it to expose ingress. aplicacao_view
        // returns None for Servico, so the slot is the manifest's
        // "ignored otherwise" — never validated, never rendered. The
        // kind-coherence gate rejects it at build time (before the
        // :servicos existence loop), naming the offending slot + kind.
        use crate::Entrada;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.entrada = Some(Entrada {
            host: "demo.example.com".into(),
            para: "demo".into(),
            paths: vec![],
            port: 8080,
        });
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::MeshSlotsOnNonAplicacao { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Servico);
                assert_eq!(slots, crate::render::M3_AUTHOR_KEY_ENTRADA);
            }
            other => panic!("expected MeshSlotsOnNonAplicacao, got {other:?}"),
        }
    }

    #[test]
    fn mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order() {
        // All five mesh slots declared on a Biblioteca → the diagnostic
        // enumerates them in canonical declaration order, deterministic
        // across runs. The gate fires on declared-ness only (the values
        // need not be a *valid* AplicacaoSpec — aplicacao_view is never
        // called for a non-Aplicacao kind).
        use crate::{Entrada, Membro, MeshPolicy, Placement, PlacementStrategy, WitContract};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.membros = vec![Membro {
            caixa: "a".into(),
            versao: "^0.1".into(),
        }];
        c.contratos = vec![WitContract {
            de: "a".into(),
            para: "a".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/x".into()),
            subject: None,
            slot: None,
        }];
        c.politicas = Some(MeshPolicy::default());
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        c.entrada = Some(Entrada {
            host: "x.example.com".into(),
            para: "a".into(),
            paths: vec![],
            port: 8080,
        });
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::MeshSlotsOnNonAplicacao { slots, .. } => {
                assert_eq!(
                    slots,
                    format!(
                        "{} {} {} {} {}",
                        crate::render::M3_AUTHOR_KEY_MEMBROS,
                        crate::render::M3_AUTHOR_KEY_CONTRATOS,
                        crate::render::M3_AUTHOR_KEY_POLITICAS,
                        crate::render::M3_AUTHOR_KEY_PLACEMENT,
                        crate::render::M3_AUTHOR_KEY_ENTRADA,
                    )
                );
            }
            other => panic!("expected MeshSlotsOnNonAplicacao, got {other:?}"),
        }
    }

    #[test]
    fn servico_without_mesh_slots_still_verifies() {
        // Pass-after control: a well-formed Servico carrying no mesh
        // slots must remain accepted — the gate keys off declared-ness,
        // so it must not over-fire on the common case.
        let root = PathBuf::from("/tmp/x");
        let servico = root.join("servicos/demo.computeunit.yaml");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == servico);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn supervisor_slots_on_servico_rejected() {
        // Mirror of `mesh_slots_on_servico_rejected` on the
        // supervisor-tree slot set: an author adds `:children` to a
        // `:kind Servico` expecting it to spawn workers. supervisor_view
        // returns None for Servico, so the slot is the manifest's
        // "ignored otherwise" — never validated, never reconciled. The
        // kind-coherence gate rejects it at build time (before the
        // :servicos existence loop), naming the offending slot + kind.
        use crate::{ChildSpec, RestartPolicy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.children = vec![ChildSpec {
            caixa: "worker".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::SupervisorSlotsOnNonSupervisor { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Servico);
                assert_eq!(slots, crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN);
            }
            other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
        }
    }

    #[test]
    fn supervisor_slots_on_non_supervisor_lists_slots_in_canonical_order() {
        // All four supervisor slots declared on a Biblioteca → the
        // diagnostic enumerates them in canonical declaration order
        // (`:estrategia` → `:max-restarts` → `:restart-window` →
        // `:children`), deterministic across runs. The gate fires on
        // declared-ness only (the values need not be a *valid*
        // SupervisorSpec — supervisor_view is never called for a
        // non-Supervisor kind). Mirror of
        // `mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order`.
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        c.restart_window = Some("60s".into());
        c.children = vec![ChildSpec {
            caixa: "worker".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::SupervisorSlotsOnNonSupervisor { slots, .. } => {
                assert_eq!(slots, ":estrategia :max-restarts :restart-window :children");
            }
            other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
        }
    }

    #[test]
    fn aplicacao_with_supervisor_slots_rejected() {
        // Cross-kind pin: an Aplicacao (the other no-code orchestrator
        // kind) that declares a supervisor slot is rejected by the
        // supervisor-slot gate, just as a Supervisor declaring a mesh
        // slot is rejected by the mesh-slot gate — the two kind ↔ slot
        // coherence gates are symmetric and mutually exclusive. The
        // gate fires before the Aplicacao typed-graph validation, so
        // the diagnostic names the foreign supervisor slot rather than
        // a downstream AplicacaoViolation.
        use crate::{Membro, Placement, PlacementStrategy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.membros = vec![Membro {
            caixa: "service-a".into(),
            versao: "^0.1".into(),
        }];
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        c.estrategia = Some(RestartStrategy::OneForAll);
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::SupervisorSlotsOnNonSupervisor { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Aplicacao);
                assert_eq!(slots, crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA);
            }
            other => panic!("expected SupervisorSlotsOnNonSupervisor, got {other:?}"),
        }
    }

    #[test]
    fn servico_without_supervisor_slots_still_verifies() {
        // Pass-after control: a well-formed Servico carrying no
        // supervisor slots must remain accepted — the gate keys off
        // declared-ness, so it must not over-fire on the common case.
        let root = PathBuf::from("/tmp/x");
        let servico = root.join("servicos/demo.computeunit.yaml");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == servico);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn servico_slots_on_biblioteca_rejected() {
        // Mirror of `mesh_slots_on_servico_rejected` /
        // `supervisor_slots_on_servico_rejected` on the M2
        // Servico-runtime slot set: an author adds `:limits` to a
        // `:kind Biblioteca` expecting per-process sandboxing. The
        // caixa-helm / caixa-flux renderers gate on `require_kind(_,
        // Servico)`, so the slot is the manifest's "ignored otherwise" —
        // never rendered into any artifact. The kind-coherence gate
        // rejects it at build time (before the M2 validate blocks),
        // naming the offending slot + kind.
        use crate::LimitsSpec;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let lib = root.join("lib").join("demo.lisp");
        let manifest_clone = manifest.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == lib);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.limits = Some(LimitsSpec {
            fuel: Some(1_000_000),
            ..Default::default()
        });
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ServicoSlotsOnNonServico { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Biblioteca);
                assert_eq!(slots, crate::render::M2_AUTHOR_KEY_LIMITS);
            }
            other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
        }
    }

    #[test]
    fn servico_slots_on_non_servico_lists_slots_in_canonical_order() {
        // All three M2 slots declared on a Biblioteca → the diagnostic
        // enumerates them in canonical declaration order (`:limits` →
        // `:behavior` → `:upgrade-from`), deterministic across runs. The
        // gate fires on declared-ness only (the values need not pass the
        // M2 validate blocks — those run only after the kind-coherence
        // gate, and never for a non-Servico declared-slot caixa). Mirror
        // of the mesh/supervisor `*_lists_slots_in_canonical_order` pins.
        use crate::{BehaviorSpec, LimitsSpec, UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.limits = Some(LimitsSpec {
            fuel: Some(1_000_000),
            ..Default::default()
        });
        c.behavior = Some(BehaviorSpec {
            on_init: Some(PathBuf::from("lib/init.lisp")),
            ..Default::default()
        });
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::Restart],
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ServicoSlotsOnNonServico { slots, .. } => {
                assert_eq!(
                    slots,
                    format!(
                        "{} {} {}",
                        crate::render::M2_AUTHOR_KEY_LIMITS,
                        crate::render::M2_AUTHOR_KEY_BEHAVIOR,
                        crate::render::M2_AUTHOR_KEY_UPGRADE_FROM,
                    )
                );
            }
            other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
        }
    }

    #[test]
    fn aplicacao_with_servico_slots_rejected() {
        // Cross-kind pin (mirror of `aplicacao_with_supervisor_slots_rejected`):
        // an Aplicacao that declares an M2 Servico-runtime slot is
        // rejected by the Servico-slot gate, just as a Supervisor
        // declaring a mesh slot is rejected by the mesh-slot gate — the
        // three kind ↔ slot coherence gates are symmetric and mutually
        // exclusive. The gate fires before the Aplicacao typed-graph
        // validation, so the diagnostic names the foreign M2 slot rather
        // than a downstream AplicacaoViolation about missing :membros.
        use crate::{Membro, Placement, PlacementStrategy, UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.membros = vec![Membro {
            caixa: "service-a".into(),
            versao: "^0.1".into(),
        }];
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::Restart],
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ServicoSlotsOnNonServico { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Aplicacao);
                assert_eq!(slots, crate::render::M2_AUTHOR_KEY_UPGRADE_FROM);
            }
            other => panic!("expected ServicoSlotsOnNonServico, got {other:?}"),
        }
    }

    #[test]
    fn servico_with_servico_slots_still_verifies() {
        // Pass-after control: a well-formed Servico carrying all three M2
        // slots must remain accepted — the gate is guarded by `kind !=
        // Servico`, so it must not over-fire on the kind these slots
        // exist for. Mirror of `servico_without_{mesh,supervisor}_slots_
        // still_verifies` on the legitimate-declaration axis.
        use crate::{BehaviorSpec, LimitsSpec, UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let init = root.join("lib/init.lisp");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc || p == init);
        let mut c = caixa(CaixaKind::Servico);
        c.versao = "0.2.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.limits = Some(LimitsSpec {
            fuel: Some(1_000_000),
            ..Default::default()
        });
        c.behavior = Some(BehaviorSpec {
            on_init: Some(PathBuf::from("lib/init.lisp")),
            ..Default::default()
        });
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::Restart],
        }];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn aplicacao_must_not_have_bibliotecas() {
        use crate::{Membro, Placement, PlacementStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.bibliotecas = vec!["lib/code.lisp".into()];
        c.membros = vec![Membro {
            caixa: "x".into(),
            versao: "^0.1".into(),
        }];
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::AplicacaoOwnsCode(_)));
    }

    #[test]
    fn acao_must_not_have_bibliotecas() {
        // Mirror of `supervisor_must_not_have_bibliotecas` /
        // `aplicacao_must_not_have_bibliotecas` on the third no-code
        // kind. `has_code` fires before the `:ci`-presence gates below
        // it, so this must surface `AcaoOwnsCode` even though the
        // caixa also lacks a `:ci` slot (which would otherwise surface
        // as `MissingCi`) — the more-fundamental "this kind runs no
        // code at all" diagnostic wins.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Acao);
        c.bibliotecas = vec!["lib/code.lisp".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::AcaoOwnsCode(_)));
    }

    #[test]
    fn acao_without_ci_errors() {
        // Mirror of `binario_without_exe_errors` on the fifth required-
        // slot axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let err = layout.verify(&caixa(CaixaKind::Acao), &root).unwrap_err();
        assert!(matches!(err, LayoutError::MissingCi(_)));
    }

    #[test]
    fn acao_with_ci_passes() {
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest);
        let mut c = caixa(CaixaKind::Acao);
        c.ci = Some(canteiro_types::CiRun {
            workspace: "pleme-io".into(),
            repo: "caixa".into(),
            nodes: vec![],
        });
        layout
            .verify(&c, &root)
            .expect("an Acao caixa with a declared :ci slot passes layout verify");
    }

    #[test]
    fn ci_on_non_acao_errors() {
        // Mirror of `mesh_slots_on_non_aplicacao_lists_slots_in_canonical_order`
        // on the Acao-only `:ci` axis — declaring `:ci` on any other
        // kind is the same "silently ignored" footgun the sibling
        // mesh-/supervisor-/servico-slot gates already close.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.ci = Some(canteiro_types::CiRun {
            workspace: "pleme-io".into(),
            repo: "caixa".into(),
            nodes: vec![],
        });
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::CiOnNonAcao { caixa, kind } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Biblioteca);
            }
            other => panic!("expected CiOnNonAcao, got {other:?}"),
        }
    }

    // ── ForeignCodeSlot — kind ↔ code-surface coherence ────────────────

    #[test]
    fn biblioteca_with_exe_rejected() {
        // Fail-before-pass-after pin: a `:kind Biblioteca` declaring
        // `:exe` is the "I added a CLI to my library" footgun — the nix
        // flake renderer for Binario gates on `require_kind(_, Binario)`,
        // so on a Biblioteca the `:exe` path is silently dropped past
        // the layout's path-existence check (no executable target is
        // ever generated). The diagnostic names the offending kind +
        // slot verbatim so the author can grep their caixa.lisp for
        // `:exe` and fix in one edit (drop the slot or change
        // `:kind Biblioteca` → `:kind Binario`).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let lib = root.join("lib").join("demo.lisp");
        let exe_path = root.join("exe").join("tool");
        let layout = StandardLayout::new()
            .with_path_exists(move |p| p == manifest || p == lib || p == exe_path);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.exe = vec!["exe/tool".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Biblioteca);
                assert_eq!(slots, ":exe");
            }
            other => panic!("expected ForeignCodeSlot, got {other:?}"),
        }
    }

    #[test]
    fn biblioteca_with_servicos_rejected() {
        // Symmetric to `biblioteca_with_exe_rejected` on the
        // `:servicos` axis: a `:kind Biblioteca` declaring a Servico
        // computeunit silently passed validate and the daemon's
        // ComputeUnit / lareira chart never materialized (caixa-helm /
        // caixa-flux gate emission on `require_kind(_, Servico)`).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let lib = root.join("lib").join("demo.lisp");
        let svc = root.join("servicos").join("demo.computeunit.yaml");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == lib || p == svc);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Biblioteca);
                assert_eq!(slots, ":servicos");
            }
            other => panic!("expected ForeignCodeSlot, got {other:?}"),
        }
    }

    #[test]
    fn biblioteca_with_exe_and_servicos_lists_slots_in_canonical_order() {
        // Both foreign code slots declared on a Biblioteca → the
        // diagnostic enumerates them in canonical declaration order
        // (`:exe` → `:servicos`), deterministic across runs. Mirrors the
        // mesh/supervisor/servico-slot `*_lists_slots_in_canonical_order`
        // pins on the peer kind ↔ slot algebra axes; drift in the
        // [`Caixa::declared_foreign_code_slots`] iteration order surfaces
        // here.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Biblioteca);
        c.exe = vec!["exe/tool".into()];
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ForeignCodeSlot { slots, .. } => {
                assert_eq!(slots, ":exe :servicos");
            }
            other => panic!("expected ForeignCodeSlot, got {other:?}"),
        }
    }

    #[test]
    fn binario_with_servicos_rejected() {
        // The peer footgun on the Binario kind: declaring a Servico
        // computeunit on a `:kind Binario` caixa. The caixa-helm /
        // caixa-flux renderers gate on `require_kind(_, Servico)`, so
        // the `:servicos` slot vanishes past the layout's path-
        // existence check — no ComputeUnit, no Helm chart. `:exe` stays
        // valid (Binario's native code surface), so the kind-coherence
        // diagnostic targets only `:servicos`.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let exe_path = root.join("exe").join("tool");
        let svc = root.join("servicos").join("demo.computeunit.yaml");
        let layout = StandardLayout::new()
            .with_path_exists(move |p| p == manifest || p == exe_path || p == svc);
        let mut c = caixa(CaixaKind::Binario);
        c.exe = vec!["exe/tool".into()];
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Binario);
                assert_eq!(slots, ":servicos");
            }
            other => panic!("expected ForeignCodeSlot, got {other:?}"),
        }
    }

    #[test]
    fn servico_with_exe_rejected() {
        // Symmetric to `binario_with_servicos_rejected` on the other
        // code-running peer: a `:kind Servico` declaring an `:exe` is
        // the "I added a host-side CLI to my wasm component" footgun —
        // the nix flake's Binario target gates on `require_kind(_,
        // Binario)`, so the `:exe` path vanishes past the layout's
        // path-existence check.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos").join("demo.computeunit.yaml");
        let exe_path = root.join("exe").join("tool");
        let layout = StandardLayout::new()
            .with_path_exists(move |p| p == manifest || p == svc || p == exe_path);
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.exe = vec!["exe/tool".into()];
        let err = layout.verify(&c, &root).unwrap_err();
        match err {
            LayoutError::ForeignCodeSlot { caixa, kind, slots } => {
                assert_eq!(caixa, "demo");
                assert_eq!(kind, CaixaKind::Servico);
                assert_eq!(slots, ":exe");
            }
            other => panic!("expected ForeignCodeSlot, got {other:?}"),
        }
    }

    #[test]
    fn binario_without_servicos_still_verifies() {
        // Pass-after control: a well-formed Binario carrying only its
        // native `:exe` surface must remain accepted — the gate keys off
        // declared-ness of the *foreign* slots, so it must not over-fire
        // on the legitimate same-kind case. Mirror of
        // `servico_with_servico_slots_still_verifies` on the peer axis.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let exe_path = root.join("exe").join("tool");
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest || p == exe_path);
        let mut c = caixa(CaixaKind::Binario);
        c.exe = vec!["exe/tool".into()];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn biblioteca_with_only_bibliotecas_still_verifies() {
        // Pass-after control: a well-formed Biblioteca carrying only
        // its native `:bibliotecas` surface (or the default
        // `lib/<nome>.lisp`) must remain accepted. The gate keys off
        // declared-ness of `:exe` + `:servicos` only — `:bibliotecas`
        // is deliberately excluded from the foreign-set on every
        // code-running kind (`declared_foreign_code_slots` doc), so a
        // Biblioteca with the canonical lib surface alone passes.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let lib = root.join("lib").join("demo.lisp");
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == lib);
        layout
            .verify(&caixa(CaixaKind::Biblioteca), &root)
            .expect("Biblioteca with default lib must verify");
    }

    #[test]
    fn binario_with_bibliotecas_helper_still_verifies() {
        // Pass-after control on the deliberate `:bibliotecas`-as-helper
        // shape: a `:kind Binario` may legitimately bundle a `lib/`
        // helper its nix flake build consumes (the same shape a
        // `:kind Servico` may bundle for its wasm-component source).
        // The foreign-code-slot gate must NOT fire on `:bibliotecas` for
        // either code-running kind; pinned here so a future tightening
        // that adds `:bibliotecas` to the foreign set on Binario /
        // Servico surfaces as a test failure rather than as a silent
        // over-reach.
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let exe_path = root.join("exe").join("tool");
        let lib = root.join("lib").join("helper.lisp");
        let layout = StandardLayout::new()
            .with_path_exists(move |p| p == manifest || p == exe_path || p == lib);
        let mut c = caixa(CaixaKind::Binario);
        c.exe = vec!["exe/tool".into()];
        c.bibliotecas = vec!["lib/helper.lisp".into()];
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn supervisor_with_exe_still_surfaces_owns_code() {
        // Diagnostic-precedence pin: a `:kind Supervisor` declaring
        // `:exe` is *both* "Supervisor with code" and "foreign code
        // slot". The more-fundamental `SupervisorOwnsCode` must win
        // (Supervisor doesn't run code at all — the foreign-slot
        // diagnostic would mislead the author toward changing `:kind`
        // when the underlying defect is that supervisors orchestrate
        // children, not code). Guards the call order in `verify`
        // against silent reordering.
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        c.exe = vec!["exe/tool".into()];
        c.children = vec![ChildSpec {
            caixa: "worker".into(),
            versao: "^0.1".into(),
            restart: RestartPolicy::Permanent,
        }];
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(
            matches!(err, LayoutError::SupervisorOwnsCode(_)),
            "Supervisor-with-:exe must surface as SupervisorOwnsCode (the more-fundamental \
             no-code-at-all diagnostic), got {err:?}"
        );
    }

    #[test]
    fn declared_foreign_code_slots_returns_canonical_order() {
        // Unit-level pin for the lifted method: the canonical iteration
        // order is `:exe` → `:servicos`, independent of which subset is
        // populated. Empty input + each single-slot subset + the full
        // pair are all checked so a future axis added to the method
        // (a hypothetical fifth code-surface slot) is one extension
        // point + one assertion update here, not a coordinated rewrite
        // across the layout-test sites that reach for the canonical
        // order.
        let mut c = caixa(CaixaKind::Biblioteca);
        assert!(c.declared_foreign_code_slots().is_empty());
        c.exe = vec!["exe/tool".into()];
        assert_eq!(c.declared_foreign_code_slots(), vec![":exe"]);
        c.exe.clear();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        assert_eq!(c.declared_foreign_code_slots(), vec![":servicos"]);
        c.exe = vec!["exe/tool".into()];
        assert_eq!(c.declared_foreign_code_slots(), vec![":exe", ":servicos"]);
    }

    #[test]
    fn aplicacao_with_unknown_contrato_member_fails() {
        use crate::{Membro, Placement, PlacementStrategy, WitContract};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Aplicacao);
        c.membros = vec![Membro {
            caixa: "service-a".into(),
            versao: "^0.1".into(),
        }];
        c.contratos = vec![WitContract {
            de: "service-a".into(),
            para: "phantom".into(),
            wit: "wasi:http/proxy".into(),
            endpoint: Some("/x".into()),
            subject: None,
            slot: None,
        }];
        c.placement = Some(Placement {
            estrategia: PlacementStrategy::Replicated,
            clusters: vec!["rio".into()],
            affinity: None,
            shard_key: None,
        });
        let err = layout.verify(&c, &root).unwrap_err();
        assert!(matches!(err, LayoutError::AplicacaoViolation { .. }));
    }

    #[test]
    fn limits_zero_axis_surfaces_as_layout_violation() {
        use crate::LimitsSpec;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.limits = Some(LimitsSpec {
            fuel: Some(0),
            ..Default::default()
        });
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::LimitsViolation { caixa, issue } = err else {
            panic!("expected LimitsViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(issue.contains(":fuel"), "issue must name the axis: {issue}");
    }

    #[test]
    fn limits_well_formed_passes_layout() {
        use crate::LimitsSpec;
        use std::time::Duration;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.limits = Some(LimitsSpec {
            memory: Some(64 * 1024 * 1024),
            fuel: Some(1_000_000),
            wall_clock: Some(Duration::from_secs(30)),
            cpu: Some(500),
        });
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn supervisor_with_valid_children_passes() {
        use crate::{ChildSpec, RestartPolicy, RestartStrategy};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_clone = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_clone);
        let mut c = caixa(CaixaKind::Supervisor);
        c.estrategia = Some(RestartStrategy::OneForOne);
        c.max_restarts = Some(5);
        c.children = vec![
            ChildSpec {
                caixa: "worker".into(),
                versao: "^0.1".into(),
                restart: RestartPolicy::Permanent,
            },
            ChildSpec {
                caixa: "cache".into(),
                versao: "^0.1".into(),
                restart: RestartPolicy::Transient,
            },
        ];
        layout.verify(&c, &root).unwrap();
    }

    // ── :upgrade-from entry validation pipes through layout ─────────────

    #[test]
    fn upgrade_invalid_module_surfaces_as_layout_violation() {
        // End-to-end pin that
        // [`crate::UpgradeFromEntry::validate`] runs *inside*
        // `LayoutInvariants::verify` and surfaces value-shape
        // violations through the new `UpgradeViolation` arm
        // (parallel to `BehaviorViolation`, `LimitsViolation`,
        // `SupervisorViolation`, `AplicacaoViolation`). Until this
        // wiring landed the entry validator was unreachable from any
        // build-pipeline caller — an `:upgrade-from
        // ((:from "0.1.0" :instructions ((:load-module "Hello")))` (uppercase
        // module name the K8s apiserver would reject on the per-
        // ComputeUnit `metadata.name` axis) silently passed
        // `feira lint` / `feira build` and surfaced only at wasm-engine
        // hot-upgrade time as a per-backend "module not found" /
        // `code:load_module/1` `badarg` runtime error, far from the
        // source caixa.lisp. Pinning the wiring here so a future
        // refactor that drops the `entry.validate()` call surfaces as
        // a build-pipeline regression at this test, not as a runtime
        // surprise per consumer.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::LoadModule {
                module: "Hello".into(), // uppercase — not DNS-1123
            }],
        }];
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!("expected UpgradeViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE),
            "issue must name the lisp-form of the offending instruction: {issue}"
        );
        assert!(
            issue.contains("Hello"),
            "issue must name the offending :module verbatim: {issue}"
        );
    }

    #[test]
    fn upgrade_empty_module_surfaces_as_layout_violation() {
        // Companion to the DNS-1123 footgun above on the narrower
        // empty arm. Every Module-bearing variant's empty value
        // reaches the layout pipeline through the kind-tagged
        // `ModuleEmpty` diagnostic naming its lisp-form.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::SoftPurge {
                module: String::new(),
            }],
        }];
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!("expected UpgradeViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_SOFT_PURGE),
            "issue must name the lisp-form of the empty instruction: {issue}"
        );
    }

    #[test]
    fn upgrade_invalid_state_change_script_surfaces_as_layout_violation() {
        // Pins that the b0c8389 script value-shape gates
        // (AbsoluteScript / ParentEscapeScript) — previously
        // unreachable from any build-pipeline caller — now fire
        // through the same `UpgradeViolation` arm before the path-
        // existence pass would otherwise emit the less-helpful
        // "missing upgrade-script" (or, worse, *succeed* against
        // /etc/passwd, proving the sandbox bypass — same defect
        // the b0c8389 BehaviorSpec wiring closed on the peer M2
        // slot).
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let etc_passwd = PathBuf::from("/etc/passwd");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::StateChange {
                script: PathBuf::from("/etc/passwd"),
            }],
        }];
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let etc_passwd_clone = etc_passwd.clone();
        // Critically: /etc/passwd "exists" in our mock — without the
        // value-shape pre-check, the existence loop would *succeed*
        // and the path-traversal exit from the project sandbox would
        // pass `feira build` silently.
        let layout = StandardLayout::new().with_path_exists(move |p| {
            p == manifest_clone || p == svc_clone || p == etc_passwd_clone
        });
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!("expected UpgradeViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("absolute") || issue.contains("Absolute"),
            "issue must name the violation kind (absolute): {issue}"
        );
    }

    #[test]
    fn upgrade_well_formed_passes_layout() {
        // Positive control — every documented authoring shape
        // (`:load-module`, `:state-change` with a relative path,
        // `:soft-purge`, `:purge`, sole `:restart`) passes the wired
        // gate. The typed sequence (`:load-module` → `:state-change`
        // → `:soft-purge` → `:purge`) lives in one entry; the sole
        // `:restart` fallback lives in a *separate* entry on a
        // different `:from` (the within-entry restart-exclusivity
        // gate added in this commit rejects mixing the fallback with
        // the typed sequence — per the UpgradeInstruction::Restart
        // doc, `:restart` is terminal and any other instructions in
        // the same entry are dead code). Drift here = a future
        // tighten that rejects any canonical shape surfaces as a
        // regression at this layout-level pin, not piecemeal across
        // per-renderer call sites.
        //
        // `:soft-purge` and `:purge` target *distinct* old-version
        // modules (`hello-rio-old` and `hello-rio-oldest`) so the
        // within-entry cleanup-singularity gate
        // (`UpgradeError::DuplicateCleanup`) passes — that gate
        // rejects more than one cleanup per module per entry (one
        // semantic per old version; mixing drain + discard on one
        // module is the soft-then-hard fallback footgun the author
        // shouldn't write because the operator handles cleanup
        // failure escalation itself). The two distinct names cover
        // the legitimate "drain a recent old, hard-discard an
        // older-still" shape — both authoring forms remain load-
        // bearing in this positive-control enumeration.
        use crate::{BehaviorSpec, UpgradeFromEntry, UpgradeInstruction};
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let migration = root.join("lib/migrations/v01-to-v02.lisp");
        let on_state_change = root.join("lib/migrations.lisp");
        let mut c = caixa(CaixaKind::Servico);
        // `:versao` past both entries' `:from` so the cross-slot
        // precedence gate (`FromNotBeforeVersao`) lets this canonical
        // authoring shape through to the positive-control assertion.
        c.versao = "0.2.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        // `:on-state-change` declared alongside the `(:state-change …)`
        // instruction below — the cross-slot composition gate
        // (`validate_upgrade_from_against_behavior`) rejects a
        // `:state-change` without the callback, so the canonical
        // authoring shape this positive control pins now includes the
        // runtime delivery hook (the `gen_server:code_change/3` analog
        // that the per-version script is invoked through during hot
        // upgrade per the upgrade.rs module doc "Composes with"
        // promise).
        c.behavior = Some(BehaviorSpec {
            on_state_change: Some(PathBuf::from("lib/migrations.lisp")),
            ..Default::default()
        });
        c.upgrade_from = vec![
            UpgradeFromEntry {
                from: "0.1.0".into(),
                instructions: vec![
                    UpgradeInstruction::LoadModule {
                        module: "hello-rio".into(),
                    },
                    UpgradeInstruction::StateChange {
                        script: PathBuf::from("lib/migrations/v01-to-v02.lisp"),
                    },
                    UpgradeInstruction::SoftPurge {
                        module: "hello-rio-old".into(),
                    },
                    UpgradeInstruction::Purge {
                        module: "hello-rio-oldest".into(),
                    },
                ],
            },
            UpgradeFromEntry {
                from: "0.0.9".into(),
                instructions: vec![UpgradeInstruction::Restart],
            },
        ];
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let migration_clone = migration.clone();
        let on_state_change_clone = on_state_change.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| {
            p == manifest_clone
                || p == svc_clone
                || p == migration_clone
                || p == on_state_change_clone
        });
        layout.verify(&c, &root).unwrap();
    }

    #[test]
    fn upgrade_from_restart_mixed_surfaces_as_upgrade_violation() {
        // Wiring pin: the within-entry `(:restart)`-exclusivity gate
        // (`UpgradeFromEntry::validate_restart_exclusive`) lands on
        // the same `LayoutError::UpgradeViolation` axis the per-entry
        // shape gate (26da2c7), the cross-entry duplicate-`:from`
        // gate (7c6aef2), and the cross-slot `:from < :versao`
        // precedence gate (de7ab1a) already do. A caixa.lisp whose
        // `:upgrade-from` entry mixes `(:restart)` with a typed
        // instruction surfaces at `feira build` time naming the
        // offending caixa + the entry's `:from` rather than silently
        // passing into the wasm-operator with semantically dead code
        // in the operator's dispatch table. Mirrors
        // `upgrade_from_duplicate_surfaces_as_upgrade_violation` on
        // the peer cross-entry gate.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.versao = "0.2.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![
                UpgradeInstruction::LoadModule {
                    module: "hello-rio".into(),
                },
                UpgradeInstruction::Restart,
            ],
        }];
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!("expected LayoutError::UpgradeViolation for restart-mixed entry, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("0.1.0"),
            "UpgradeViolation issue must name the offending entry's `:from` verbatim, got \
             {issue:?}"
        );
        assert!(
            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART),
            "UpgradeViolation issue must name the `:restart` axis verbatim, got {issue:?}"
        );
        assert!(
            issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_LOAD_MODULE),
            "UpgradeViolation issue must name the non-:restart peer instruction's lisp-form \
             verbatim, got {issue:?}"
        );
    }

    #[test]
    fn upgrade_from_restart_duplicated_surfaces_as_upgrade_violation() {
        // Companion arm: the duplicate-`(:restart)` mode of
        // `RestartNotExclusive` (no typed peers, just multiple
        // `Restart` variants) surfaces through the same wiring as the
        // mixed-with-typed mode above. The diagnostic still names the
        // offending entry's `:from` verbatim even when `other_kinds`
        // is empty.
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.versao = "0.2.0".into();
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "0.1.0".into(),
            instructions: vec![UpgradeInstruction::Restart, UpgradeInstruction::Restart],
        }];
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest || p == svc);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!(
                "expected LayoutError::UpgradeViolation for duplicate-restart entry, got \
                 {err:?}"
            );
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("0.1.0"),
            "UpgradeViolation issue must name the offending entry's `:from` verbatim, got \
             {issue:?}"
        );
        assert!(
            issue.contains("(:restart)")
                || issue.contains(crate::render::M2_UPGRADE_INSTRUCTION_KIND_RESTART),
            "UpgradeViolation issue must name the `:restart` axis verbatim, got {issue:?}"
        );
    }

    #[test]
    fn upgrade_from_invalid_surfaces_as_layout_violation() {
        // The `:from` semver gate (`UpgradeError::FromInvalid`)
        // was likewise unreachable before this wiring landed — a
        // typo-shaped `:from "v0.1.0"` (git-tag-shape leaking into
        // the semver slot) silently passed `feira build` and
        // surfaced only when the operator's hot-upgrade decision
        // engine tried to match against the version key it couldn't
        // parse. Now wired through `UpgradeViolation` with the
        // peer-shaped `{ from, reason }` payload — the
        // parser-shaped `reason` flows through `Display` so the
        // wrapped issue string carries both the offending value
        // *and* the SemVer-2 parser's wording (peer with the
        // `VersaoInvalid` / `MembroVersaoInvalid` envelopes on the
        // sibling SemVer-2 axes).
        use crate::{UpgradeFromEntry, UpgradeInstruction};
        use std::path::PathBuf;
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let svc = root.join("servicos/demo.computeunit.yaml");
        let mut c = caixa(CaixaKind::Servico);
        c.servicos = vec!["servicos/demo.computeunit.yaml".into()];
        c.upgrade_from = vec![UpgradeFromEntry {
            from: "v0.1.0".into(), // git-tag-shape, not semver
            instructions: vec![UpgradeInstruction::Restart],
        }];
        let manifest_clone = manifest.clone();
        let svc_clone = svc.clone();
        let layout =
            StandardLayout::new().with_path_exists(move |p| p == manifest_clone || p == svc_clone);
        let err = layout.verify(&c, &root).unwrap_err();
        let LayoutError::UpgradeViolation { caixa, issue } = err else {
            panic!("expected UpgradeViolation, got {err:?}");
        };
        assert_eq!(caixa, "demo");
        assert!(
            issue.contains("v0.1.0"),
            "UpgradeViolation issue must name the offending :from value verbatim, got {issue:?}"
        );
        assert!(
            issue.contains(":from"),
            "UpgradeViolation issue must name the :from slot verbatim, got {issue:?}"
        );
        // Pin the parser-shaped reason flow-through: the renamed
        // `FromInvalid { from, reason }` carries the SemVer-2 parser's
        // wording verbatim, and the [`UpgradeError`] Display routes it
        // into the wrapped `issue` string so the layout envelope
        // surfaces both the offending value *and* the parser's
        // diagnosis. Mirrors the peer flow-through on
        // `ManifestError::VersaoInvalid` (top-level `:versao`) and
        // `AplicacaoError::MembroVersaoInvalid` (`:membros :versao`).
        assert!(
            issue.contains("SemVer-2"),
            "UpgradeViolation issue must carry the parser-shaped reason (\"SemVer-2\"), got {issue:?}"
        );
    }

    #[test]
    fn missing_lib_gate_routes_through_kind_requires_lib_and_caixa_nome() {
        // Fail-before-pass-after pin on the two-part converge landed
        // at layout.rs:844-847:
        //   (a) `caixa.kind().is_biblioteca()` →
        //       `caixa.kind().requires_lib()` — routes the biblioteca
        //       required-slot gate onto the same `requires_*()`
        //       predicate family the three sibling required-slot
        //       gates (`requires_exe()` at :856, `requires_servicos()`
        //       at :860, `requires_ci()` at :874) already key off.
        //       All four gates in the block now share one convention;
        //       a future kind that gains its own required-slot gate
        //       (an M4/M5 typed arm the CAIXA-SDLC §I six-kind roster
        //       may grow) reaches for the same predicate family and
        //       inherits the accessor discipline for free.
        //   (b) raw `caixa.nome` → `caixa.nome()` — routes the
        //       `expected` path composition through the typed
        //       [`crate::Caixa::nome`] accessor, closing the last
        //       unlifted raw `caixa.nome` production field-access
        //       site in `caixa-core/src/layout.rs` (every peer
        //       diagnostic in the file already routes through
        //       `caixa.nome().to_string()`).
        //
        // The behavioral pin: for a Biblioteca kind with no fallback
        // `lib/<nome>.lisp` file, MissingLib fires and its `expected`
        // path composes through `Caixa::nome()`; for every other
        // kind, MissingLib does NOT fire (the gate short-circuits on
        // kinds where `requires_lib()` returns false), even when the
        // fallback file is likewise absent. A future regression that
        // reroutes the gate off `requires_lib()` (e.g. onto
        // `is_biblioteca()` again, or onto a hand-authored
        // `matches!(caixa.kind(), CaixaKind::Biblioteca)`) that
        // *happens* to agree byte-for-byte on today's arm-set trips
        // this test the moment a future kind's `requires_lib()`
        // returns true for a non-`Biblioteca` arm (or the sibling
        // required-slot gates diverge from the same convention).
        let root = PathBuf::from("/tmp/x");
        let manifest = root.join("caixa.lisp");
        let manifest_only = manifest.clone();
        let layout = StandardLayout::new().with_path_exists(move |p| p == manifest_only);

        // Biblioteca kind + no lib fallback → MissingLib fires with
        // the expected path composed through `Caixa::nome()`.
        let bib = caixa(CaixaKind::Biblioteca);
        assert!(
            bib.kind().requires_lib(),
            "requires_lib() must return true for Biblioteca — the four-required-\
             slot-gate family's routing depends on this arm's assignment"
        );
        let err = layout.verify(&bib, &root).unwrap_err();
        let LayoutError::MissingLib {
            caixa: cname,
            expected,
        } = err
        else {
            panic!("expected MissingLib for Biblioteca kind with no lib fallback, got {err:?}");
        };
        assert_eq!(
            cname,
            bib.nome(),
            "MissingLib `caixa:` carrier must byte-equal Caixa::nome()"
        );
        assert_eq!(
            expected,
            root.join(crate::render::LAYOUT_DIR_LIB)
                .join(format!("{}.lisp", bib.nome())),
            "MissingLib `expected:` path must compose through Caixa::nome() \
             verbatim — a raw-field-access regression would silently drift \
             the composed path on any future `:nome` axis extension \
             (namespace-qualified rewrite, per-cluster alias overlay)"
        );

        // Non-Biblioteca kinds → the MissingLib gate short-circuits.
        // Different kinds fail on their own required-slot gate
        // (BinarioWithoutExe, ServicoWithoutServicos, MissingCi) or
        // on downstream M2/M3 invariants; none of them may surface as
        // MissingLib, because `requires_lib()` returns false for each.
        for kind in [
            CaixaKind::Binario,
            CaixaKind::Servico,
            CaixaKind::Supervisor,
            CaixaKind::Aplicacao,
            CaixaKind::Acao,
        ] {
            assert!(
                !kind.requires_lib(),
                "requires_lib() must return false for {kind:?} — the \
                 four-required-slot-gate family's arm assignment pins \
                 exactly one kind (Biblioteca) as the arm that requires \
                 a `lib/` entry"
            );
            let c = caixa(kind);
            let result = layout.verify(&c, &root);
            assert!(
                !matches!(result, Err(LayoutError::MissingLib { .. })),
                "MissingLib gate at layout.rs:844 must short-circuit for \
                 kinds where requires_lib() returns false; unexpectedly \
                 fired for {kind:?}: {result:?}"
            );
        }
    }
}