helm-schema-gen 0.0.6

Generate an accurate JSON schema for any helm chart
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
use super::*;
use color_eyre::eyre;
use indoc::indoc;
use test_util::prelude::sim_assert_eq;

/// A `regexMatch` fail whose subject reached the match through `tpl` (a
/// raw template PROGRAM, not the rendered text) constrains only the
/// output: a values string carrying a template action is admitted (its
/// render may match), a matching literal is accepted, and an action-free
/// non-matching literal still terminates. redis-ha's `masterGroupName`
/// helper is the driving case.
#[test]
fn post_tpl_regex_admits_template_programs() {
    let helpers = indoc! {r#"
        {{- define "repro.masterGroupName" -}}
        {{- $name := tpl (.Values.masterGroupName | default "") . -}}
        {{- if regexMatch "^[\w.-]+$" $name -}}
        {{ $name }}
        {{- else -}}
        {{ required "a valid masterGroupName is required" "" }}
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: {{ include "repro.masterGroupName" . }}
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), None);

    for (instance, want, label) in [
        (
            serde_json::json!({ "masterGroupName": "mymaster" }),
            true,
            "a literal matching the pattern renders",
        ),
        (
            serde_json::json!({ "masterGroupName": "{{ .Release.Name }}" }),
            true,
            "a template program is admitted (its render may match)",
        ),
        (
            serde_json::json!({ "masterGroupName": "bad group" }),
            false,
            "an action-free non-matching literal terminates",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// The grafana `assertNoLeakedSecrets` traversal: a folded literal table
/// of sensitive paths is ranged with per-item bindings, an indexed inner
/// range advances a traversal local under `hasKey` guards, and the last
/// segment applies a `regexMatch`-guarded `fail`. The traversal must
/// interpret to exact values paths: non-strings and plain strings at a
/// sensitive path reject while variable-expansion syntax and disabled
/// assertion render.
#[test]
fn literal_table_traversal_binds_pattern_validators() {
    let helpers = indoc! {r#"
        {{- define "repro.assertNoLeakedSecrets" -}}
          {{- $sensitiveKeysYaml := `
        sensitiveKeys:
        - path: ["database", "password"]
        - path: ["auth.basic", "password"]
        ` | fromYaml -}}
          {{- if .Values.assertNoLeakedSecrets -}}
            {{- $ini := index .Values "app.ini" -}}
            {{- range $_, $secret := $sensitiveKeysYaml.sensitiveKeys -}}
              {{- $currentMap := $ini -}}
              {{- $shouldContinue := true -}}
              {{- range $index, $elem := $secret.path -}}
                {{- if and $shouldContinue (hasKey $currentMap $elem) -}}
                  {{- if eq (len $secret.path) (add1 $index) -}}
                    {{- if not (regexMatch "\$(?:__(?:env|file|vault))?{[^}]+}" (index $currentMap $elem)) -}}
                      {{- fail (printf "Sensitive key '%s' should use variable expansion" (join "." $secret.path)) -}}
                    {{- end -}}
                  {{- else -}}
                    {{- $currentMap = index $currentMap $elem -}}
                  {{- end -}}
                {{- else -}}
                    {{- $shouldContinue = false -}}
                {{- end -}}
              {{- end -}}
            {{- end -}}
          {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        {{- include "repro.assertNoLeakedSecrets" . }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: probe
    "#};
    let values_yaml = indoc! {"
        assertNoLeakedSecrets: true
        app.ini: {}
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    for (instance, want, label) in [
        (serde_json::json!({}), true, "defaults render"),
        (
            serde_json::json!({ "assertNoLeakedSecrets": true, "app.ini": { "database": { "password": 7 } } }),
            false,
            "regexMatch rejects a non-string sensitive value",
        ),
        (
            serde_json::json!({ "assertNoLeakedSecrets": true, "app.ini": { "database": { "password": "hunter2" } } }),
            false,
            "a plaintext sensitive value hits the fail",
        ),
        (
            serde_json::json!({ "app.ini": { "database": { "password": "$__env{PW}" } } }),
            true,
            "variable expansion renders",
        ),
        (
            serde_json::json!({ "assertNoLeakedSecrets": true, "app.ini": { "auth.basic": { "password": "leak" } } }),
            false,
            "dotted path segments stay atomic",
        ),
        (
            serde_json::json!({ "app.ini": { "database": { "host": "ok" } } }),
            true,
            "non-sensitive members render",
        ),
        (
            serde_json::json!({
                "assertNoLeakedSecrets": false,
                "app.ini": { "database": { "password": "hunter2" } },
            }),
            true,
            "the outer flag gates the whole validator",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// A literal YAML table decoded with `fromYaml` constant-folds into a
/// typed abstract dict: membership
/// probes over it decode to exact live/dead branches, so a `fail` behind
/// a present key binds its validator while one behind an absent key
/// never fires.
#[test]
fn literal_from_yaml_table_folds_into_exact_membership_branches() {
    let src = indoc! {r#"
        {{- $removed := `
        legacyMode:
          since: "1.16"
        ` | fromYaml }}
        {{- if hasKey $removed "legacyMode" }}
        {{- if .Values.legacyMode }}
        {{ fail "legacyMode has been removed" }}
        {{- end }}
        {{- end }}
        {{- if hasKey $removed "activeMode" }}
        {{- if .Values.activeMode }}
        {{ fail "unreachable: activeMode is not in the table" }}
        {{- end }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: probe
    "#};
    let values_yaml = indoc! {"
        legacyMode: false
        activeMode: false
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (instance, want, label) in [
        (
            serde_json::json!({ "legacyMode": true }),
            false,
            "the folded table contains legacyMode, so its fail binds",
        ),
        (
            serde_json::json!({ "legacyMode": false }),
            true,
            "falsy legacyMode renders",
        ),
        (
            serde_json::json!({ "activeMode": true }),
            true,
            "the dead absent-key branch must not bind its fail",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// An explicit `fail` branch is a VALIDATOR: rendering aborts whenever its
/// guards hold, so valid inputs must falsify the failing test wherever the
/// outer conditions hold (kyverno fails on non-string image tags inside a
/// helper; traefik fails on plugins missing moduleName/version while
/// ranging them; sealed-secrets fails on non-string annotation map values).
#[test]
fn fail_branches_bind_validator_requirements() {
    let helpers = indoc! {r#"
        {{- define "repro.image" -}}
        {{- $tag := default .defaultTag .image.tag -}}
        {{- if not (typeIs "string" $tag) -}}
          {{ fail "Image tags must be strings." }}
        {{- end -}}
        {{- print "img:" $tag -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: Pod
        metadata:
          name: probe
        spec:
          containers:
          - name: main
            image: {{ include "repro.image" (dict "image" .Values.image "defaultTag" .Chart.AppVersion) | quote }}
            args:
            {{- range $name, $plugin := .Values.plugins }}
            {{- if or (ne (typeOf $plugin) "map[string]interface {}") (not (hasKey $plugin "moduleName")) }}
              {{- fail (printf "plugin %s is missing moduleName" $name) }}
            {{- end }}
            - "--plugin={{ $name }}"
            {{- end }}
            env:
            {{- range $k, $v := .Values.annotations }}
              {{- if not (and $v (kindIs "string" $v)) }}
                {{ fail "Annotation values have to be strings" }}
              {{- end }}
            {{- end }}
            - name: PROBE
              value: "set"
    "#};
    let values_yaml = indoc! {"
        image:
          tag: latest
        plugins: {}
        annotations: {}
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    for (instance, want, label) in [
        (
            serde_json::json!({ "image": { "tag": 7 } }),
            false,
            "non-string tag fails",
        ),
        (
            serde_json::json!({ "image": { "tag": "v1" } }),
            true,
            "string tag renders",
        ),
        (
            serde_json::json!({ "image": { "tag": null } }),
            true,
            "null tag takes the default",
        ),
        // The helper's own call dict binds `image` to `.Values.image`, so
        // its body's `.image.tag` demands the key of every coalesced
        // document: the rows below isolate the plugin and annotation
        // validators by keeping it.
        (
            serde_json::json!({ "plugins": { "ok": { "moduleName": "m" } } }),
            false,
            "a deleted image aborts the helper's own navigation",
        ),
        (
            serde_json::json!({ "image": { "tag": "v1" }, "plugins": { "bad": 7 } }),
            false,
            "scalar plugin fails",
        ),
        (
            serde_json::json!({ "image": { "tag": "v1" }, "plugins": { "bad": {} } }),
            false,
            "plugin without moduleName fails",
        ),
        (
            serde_json::json!({
                "image": { "tag": "v1" },
                "plugins": { "ok": { "moduleName": "m" } }
            }),
            true,
            "complete plugin renders",
        ),
        (
            serde_json::json!({ "image": { "tag": "v1" }, "annotations": { "bad": 7 } }),
            false,
            "non-string annotation fails",
        ),
        (
            serde_json::json!({ "image": { "tag": "v1" }, "annotations": { "ok": "v" } }),
            true,
            "string annotation renders",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// `.Values.AsMap` is Go-template METHOD resolution on Helm's typed root
/// values object, returning the receiver map itself — never a user path
/// named `AsMap`. Literal-key `dig` probes through it must bind their fail
/// validators to the real root paths (cilium's `validate.yaml` deprecation
/// checks), and no `AsMap` property may be fabricated.
#[test]
fn values_asmap_method_digs_bind_root_fail_validators() {
    let src = indoc! {r#"
        {{- if (dig "removed" "" .Values.AsMap) }}
          {{ fail "removed has been removed" }}
        {{- end }}
        {{- if (dig "legacy" "mode" "" .Values.AsMap) }}
          {{ fail "legacy.mode has been removed" }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: probe
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), None);

    assert!(
        schema["properties"].get("AsMap").is_none(),
        "AsMap is a method on the typed root, not a values path; schema={schema}"
    );
    for (instance, want, label) in [
        (
            serde_json::json!({ "removed": true }),
            false,
            "truthy removed option fails rendering",
        ),
        (
            serde_json::json!({ "removed": false }),
            true,
            "falsy removed option renders",
        ),
        (
            serde_json::json!({ "legacy": { "mode": "audit" } }),
            false,
            "truthy nested removed option fails rendering",
        ),
        (
            serde_json::json!({ "legacy": { "mode": "" } }),
            true,
            "falsy nested removed option renders",
        ),
        (serde_json::json!({}), true, "defaults render"),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// Only the ROOT receiver is Helm's typed values object: nested values are
/// plain maps, so a nested `AsMap` segment stays an ordinary key, and a
/// genuine uppercase root key that is not a method name stays a normal
/// path. Selecting a derived-text method (`.Values.YAML`) claims no path.
#[test]
fn values_typed_method_resolution_keeps_genuine_keys() {
    let src = indoc! {r"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: probe
        data:
          upper: {{ .Values.Upper | quote }}
          nested: {{ .Values.foo.AsMap | quote }}
          derived: {{ .Values.YAML | quote }}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), None);

    assert!(
        schema["properties"].get("Upper").is_some(),
        "a genuine uppercase root key stays a values path; schema={schema}"
    );
    assert!(
        schema["properties"]["foo"]["properties"]
            .get("AsMap")
            .is_some(),
        "nested values are plain maps, so AsMap is an ordinary key there; schema={schema}"
    );
    assert!(
        schema["properties"].get("YAML").is_none(),
        "derived-text Values methods claim no user path; schema={schema}"
    );
}

/// A `fail` guarded by a condition the lowering can only APPROXIMATE on
/// the tested path must not become a requirement: kyverno's replicas
/// helper fails only when `eq (int .) 0`, which does not decode, so
/// negating the decodable remainder would reject every normal count.
#[test]
fn approximate_fail_guards_abstain() {
    let helpers = indoc! {r#"
        {{- define "repro.replicas" -}}
        {{- if and (not (kindIs "invalid" .)) (not (kindIs "string" .)) -}}
        {{- if eq (int .) 0 -}}
          {{- fail "0 replicas is not supported" -}}
        {{- end -}}
        {{- end -}}
        {{- . -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: probe
        spec:
          replicas: {{ include "repro.replicas" .Values.replicas }}
    "#};
    let values_yaml = indoc! {"
        replicas: 1
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    assert!(
        schema_accepts_instance(&schema, &serde_json::json!({ "replicas": 3 })),
        "a normal replica count renders; the undecodable zero-check must not manufacture a requirement: {schema}"
    );
}

/// Helm's `required(message, subject)` terminates rendering when the
/// subject is Helm-empty (absent, null, or ""): a direct subject binds a
/// document-level requirement under the ambient guards, and a ranged
/// member subject requires the member on every entry.
#[test]
fn required_subjects_bind_nonempty_requirements() {
    let src = indoc! {r#"
        apiVersion: example.com/v1
        kind: Probe
        metadata:
          name: {{ required "a cluster name is required" .Values.clusterName }}
        spec:
          {{- range $name, $item := .Values.envSecrets }}
          - name: {{ $name }}
            key: {{ required "key is required" $item.key }}
          {{- end }}
          {{- if .Values.gate.enabled }}
          - name: guarded
            key: {{ required "target required when gated" .Values.gate.target }}
          {{- end }}
    "#};
    let values_yaml = indoc! {r#"
        clusterName: ""
        envSecrets: {}
        gate:
          enabled: false
          target: ""
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    // Cases compose over the declared defaults: `.Values.gate.enabled` is
    // navigated on every render, so a document without `gate` is the
    // null-deleted state helm aborts on.
    for (overrides, want, label) in [
        (
            serde_json::json!({ "clusterName": "" }),
            false,
            "empty subject fails",
        ),
        (
            serde_json::json!({ "clusterName": null }),
            false,
            "null subject fails",
        ),
        (
            serde_json::json!({ "clusterName": "prod" }),
            true,
            "nonempty renders",
        ),
        (
            serde_json::json!({ "clusterName": "prod", "envSecrets": { "A": { "name": "s" } } }),
            false,
            "ranged member missing key fails",
        ),
        (
            serde_json::json!({ "clusterName": "prod", "envSecrets": { "A": { "key": "k" } } }),
            true,
            "ranged member with key renders",
        ),
        (
            serde_json::json!({ "clusterName": "prod", "gate": { "enabled": true, "target": "" } }),
            false,
            "guarded empty subject fails when the guard holds",
        ),
        (
            serde_json::json!({ "clusterName": "prod", "gate": { "enabled": false, "target": "" } }),
            true,
            "guarded subject stays free when the guard is off",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// A guarded `required` subject with a declared non-null default rejects
/// the ABSENT document state: helm validates the coalesced values — the
/// same document the templates render from — so the key can only be
/// missing there when the user's explicit `null` deleted the declared
/// default, and the live branch then aborts at the `required` call (the
/// AWS Load Balancer Controller HPA's `maxReplicas`). A document carrying
/// the key stays accepted, and the dormant guard keeps every spelling
/// open.
#[test]
fn guarded_required_rejects_null_deleted_declared_defaults() {
    let src = indoc! {r#"
        {{- if .Values.autoscaling.enabled }}
        apiVersion: autoscaling/v2
        kind: HorizontalPodAutoscaler
        metadata:
          name: example
        spec:
          maxReplicas: {{ required "a valid maxReplicas value is required" .Values.autoscaling.maxReplicas }}
        {{- end }}
    "#};
    let values_yaml = indoc! {"
        autoscaling:
          enabled: false
          maxReplicas: 5
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (instance, want, label) in [
        (
            serde_json::json!({ "autoscaling": { "enabled": true } }),
            false,
            "null-deleted subject fails under the live guard",
        ),
        (
            serde_json::json!({ "autoscaling": { "enabled": true, "maxReplicas": "" } }),
            false,
            "empty subject fails under the live guard",
        ),
        (
            serde_json::json!({ "autoscaling": { "enabled": true, "maxReplicas": 5 } }),
            true,
            "filled subject renders",
        ),
        (
            serde_json::json!({ "autoscaling": { "enabled": false } }),
            true,
            "dormant guard keeps the absent state open",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// A terminating validator over SEVERAL paths (mutual exclusion,
/// conditional requirements) lowers as a whole formula: no valid document
/// may satisfy all of its guards (external-dns forbids txtPrefix+txtSuffix
/// together; coredns requires dnsConfig when dnsPolicy is "None").
#[test]
fn cross_path_fail_formulas_lower_as_terminal_clauses() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: config
        data:
          {{- if and .Values.txtPrefix .Values.txtSuffix }}
          {{- fail "'txtPrefix' and 'txtSuffix' are mutually exclusive" }}
          {{- end }}
          {{- if and (eq .Values.dnsPolicy "None") (not .Values.dnsConfig) }}
          {{- fail "dnsConfig is required when dnsPolicy is set to None" }}
          {{- end }}
          ok: "true"
    "#};
    let values_yaml = indoc! {r#"
        txtPrefix: ""
        txtSuffix: ""
        dnsPolicy: ClusterFirst
        dnsConfig: {}
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (instance, want, label) in [
        (
            serde_json::json!({ "txtPrefix": "a", "txtSuffix": "b" }),
            false,
            "mutually exclusive pair fails",
        ),
        (
            serde_json::json!({ "txtPrefix": "a" }),
            true,
            "one of the pair renders",
        ),
        (
            serde_json::json!({ "dnsPolicy": "None" }),
            false,
            "None without dnsConfig fails",
        ),
        (
            serde_json::json!({ "dnsPolicy": "None", "dnsConfig": { "nameservers": ["1.1.1.1"] } }),
            true,
            "None with dnsConfig renders",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// A vacuous terminal still rejects a missing shared object, but a present
/// object's failure is reported at that object instead of at the document
/// root.
#[test]
fn vacuous_terminal_clauses_keep_present_failures_local() -> eyre::Result<()> {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: config
        data:
          {{- if and (not .Values.check.disabled) (ne .Values.check.value "ok") }}
          {{- fail "invalid check value" }}
          {{- end }}
          ok: "true"
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), None);
    let validator = jsonschema::validator_for(&schema)?;
    let invalid = serde_json::json!({ "check": { "value": "bad" } });
    let paths = validator
        .iter_errors(&invalid)
        .map(|error| error.instance_path().to_string())
        .collect::<Vec<_>>();

    assert!(
        paths.iter().any(|path| path == "/check"),
        "the present-object failure stays local: paths={paths:#?}; schema={schema}"
    );
    assert!(
        !paths.iter().any(String::is_empty),
        "the present-object failure must not also report at the root: paths={paths:#?}"
    );
    assert!(
        !validator.is_valid(&serde_json::json!({})),
        "the split root clause still covers the missing object"
    );
    assert!(
        validator.is_valid(&serde_json::json!({ "check": { "value": "ok" } })),
        "the non-failing value renders"
    );

    Ok(())
}

#[test]
fn localized_terminal_clauses_preserve_negated_presence_semantics() -> eyre::Result<()> {
    let signals = ContractSchemaSignals::new(
        BTreeMap::new(),
        vec![vec![
            helm_schema_core::ConditionalGuard::Not(Box::new(
                helm_schema_core::ConditionalGuard::Truthy {
                    path: "tags.feature".to_string(),
                },
            )),
            helm_schema_core::ConditionalGuard::Not(Box::new(
                helm_schema_core::ConditionalGuard::Absent {
                    path: "tags.feature".to_string(),
                },
            )),
        ]],
    );
    let schema = schema_for_values_yaml(signals, None);
    let validator = jsonschema::validator_for(&schema)?;

    assert!(
        validator.is_valid(&serde_json::json!({})),
        "a missing parent also makes the negated presence conjunct false"
    );
    assert!(
        !validator.is_valid(&serde_json::json!({ "tags": { "feature": false } })),
        "an explicitly disabled feature reaches the failure"
    );
    assert!(
        validator.is_valid(&serde_json::json!({ "tags": { "feature": true } })),
        "an enabled feature skips the failure"
    );

    Ok(())
}

/// Range domains compose with their consumers: a single-variable direct
/// range admits integer counts, a loop body reading item members removes
/// them, a nested range over each member value requires rangeable members,
/// and literal member reads elsewhere make a truthy value an object.
#[test]
fn range_domains_compose_with_body_and_sibling_contracts() {
    let src = indoc! {r"
        apiVersion: example.com/v1
        kind: Probe
        metadata:
          name: probe
        spec:
          plain:
          {{- range .Values.plain }}
          - {{ . | quote }}
          {{- end }}
          structured:
          {{- range .Values.structured }}
          - name: {{ .name }}
          {{- end }}
          nested:
          {{- range $group, $members := .Values.nested }}
          {{- range $name, $key := $members }}
          - {{ $group }}/{{ $name }}: {{ $key }}
          {{- end }}
          {{- end }}
          {{- if .Values.lookup }}
          lookup: {{ .Values.lookup.TARGET }}
          {{- end }}
          also-ranged:
          {{- range $k, $v := .Values.lookup }}
          - {{ $k }}
          {{- end }}
    "};
    let values_yaml = indoc! {"
        plain: []
        structured: []
        nested: {}
        lookup: {}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (instance, want, label) in [
        (
            serde_json::json!({ "plain": 2 }),
            true,
            "single-variable ranges iterate integer counts",
        ),
        (
            serde_json::json!({ "plain": false }),
            false,
            "a bare range cannot iterate false",
        ),
        (
            serde_json::json!({ "plain": "" }),
            false,
            "a bare range cannot iterate strings",
        ),
        (
            serde_json::json!({ "structured": 2 }),
            false,
            "item member reads exclude integer iteration",
        ),
        (
            serde_json::json!({ "structured": [{ "name": "a" }] }),
            true,
            "structured items render",
        ),
        (
            serde_json::json!({ "nested": { "g": "x" } }),
            false,
            "nested ranges need rangeable members",
        ),
        (
            serde_json::json!({ "nested": { "g": { "a": "k" } } }),
            true,
            "rangeable members render",
        ),
        (
            serde_json::json!({ "lookup": ["x"] }),
            false,
            "a truthy value with literal member reads must be an object",
        ),
        (
            serde_json::json!({ "lookup": [] }),
            true,
            "an empty (falsy) collection skips the member template",
        ),
        (
            serde_json::json!({ "lookup": { "TARGET": "v" } }),
            true,
            "object lookups render",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

/// a JSON roundtrip changes integer values into non-iterable JSON
/// numbers, while a direct Helm range retains integer-count semantics.
#[test]
fn json_decoded_range_excludes_integer_without_changing_raw_range() {
    let helpers = indoc! {r#"
        {{- define "normalize" -}}
        {{- $values := get (dict "doc" .Values | toJson | fromJson) "doc" -}}
        {{- $_ := set . "Values" $values -}}
        {{- end -}}
    "#};
    let decoded_source = indoc! {r#"
        {{- include "normalize" . }}
        apiVersion: v1
        kind: List
        items:
        {{- range .Values.extraResources }}
        - {{ . | toYaml | nindent 2 }}
        {{- end }}
    "#};
    let decoded_ir = parse_ir_with_helpers(decoded_source, helpers);
    let decoded_signals = schema_signals_for(&decoded_ir);
    let decoded_facts = &decoded_signals
        .schema_evidence_by_value_path()
        .get("extraResources")
        .expect("decoded range source evidence")
        .facts;
    assert!(
        decoded_facts.has_json_decoded_range_use,
        "the range source must retain its decoded runtime representation: facts={decoded_facts:#?}; ir={decoded_ir:#?}"
    );
    let decoded_schema = schema_for_values_yaml(decoded_ir, Some("extraResources: []\n"));

    for (value, want, label) in [
        (serde_json::json!([]), true, "decoded lists iterate"),
        (
            serde_json::json!({ "one": { "apiVersion": "v1", "kind": "ConfigMap" } }),
            true,
            "decoded maps iterate",
        ),
        (
            serde_json::json!(7),
            false,
            "decoded numbers do not iterate",
        ),
    ] {
        assert!(
            schema_accepts_instance(
                &decoded_schema,
                &serde_json::json!({ "extraResources": value })
            ) == want,
            "{label}: {decoded_schema}"
        );
    }

    let guarded_source = indoc! {r#"
        {{- include "normalize" . }}
        {{- if .Values.enabled }}
        {{- range .Values.extraResources }}
        {{ . | toYaml }}
        {{- end }}
        {{- end }}
    "#};
    let guarded_schema = schema_for_values_yaml(
        parse_ir_with_helpers(guarded_source, helpers),
        Some(indoc! {"
            enabled: false
            extraResources: []
        "}),
    );
    assert!(
        schema_accepts_instance(
            &guarded_schema,
            &serde_json::json!({ "enabled": false, "extraResources": 7 })
        ),
        "a dead decoded range does not constrain its collection: {guarded_schema}"
    );
    assert!(
        !schema_accepts_instance(
            &guarded_schema,
            &serde_json::json!({ "enabled": true, "extraResources": 7 })
        ),
        "a live decoded range rejects JSON numbers: {guarded_schema}"
    );

    let raw_schema = schema_for_values_yaml(
        parse_ir("{{- range .Values.count }}{{ . }}{{- end }}"),
        Some("count: null\n"),
    );
    for count in [-1, 0, 2] {
        assert!(
            schema_accepts_instance(&raw_schema, &serde_json::json!({ "count": count })),
            "raw Helm integer counts must remain rangeable: {raw_schema}"
        );
    }
}

#[test]
fn root_values_merge_defaults_activate_live_consumer_contracts() {
    let mutation = indoc! {r#"
        {{- $defaults := .Values._internal_defaults -}}
        {{- $_ := set $ "Values" (mustMergeOverwrite $defaults $.Values) -}}
    "#};
    let consumers = indoc! {r#"
        {{- if or (eq .Values.global.resourceScope "all") (eq .Values.global.resourceScope "namespace") }}
        {{- $_ := pick .Values.gateways "securityContext" }}
        {{- if .Values.remotePilotAddress }}
        {{- $_ := regexMatch "^[0-9.]+$" .Values.remotePilotAddress }}
        {{- end }}
        {{- end }}
    "#};
    let mut contract = parse_ir(mutation);
    contract.append(parse_ir(consumers));
    let schema = schema_for_values_yaml(
        contract,
        Some(indoc! {r#"
            _internal_defaults:
              global:
                resourceScope: all
              gateways: {}
              remotePilotAddress: ""
        "#}),
    );

    for (instance, want, label) in [
        (
            serde_json::json!({ "gateways": 7 }),
            false,
            "the effective default activates the object consumer",
        ),
        (
            serde_json::json!({ "remotePilotAddress": { "host": "1.2.3.4" } }),
            false,
            "the effective default activates the string consumer",
        ),
        (
            serde_json::json!({
                "global": { "resourceScope": "cluster" },
                "gateways": 7,
                "remotePilotAddress": { "host": "1.2.3.4" }
            }),
            true,
            "an explicit inactive scope skips both consumers",
        ),
        (
            serde_json::json!({
                "global": {},
                "gateways": {},
                "remotePilotAddress": "1.2.3.4"
            }),
            true,
            "valid live-branch operands render",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

#[test]
fn root_values_merge_keeps_the_pre_rewrite_source_presence_alternative() -> eyre::Result<()> {
    let mutation = indoc! {r#"
        {{- $defaults := .Values._internal_defaults -}}
        {{- $_ := unset .Values "_internal_defaults" -}}
        {{- $_ := set $ "Values" (mustMergeOverwrite $defaults $.Values) -}}
    "#};
    let consumer = indoc! {r#"
        {{- if eq .Values.global.resourceScope "all" }}
        live
        {{- end }}
    "#};
    let mut contract = parse_ir(mutation);
    contract.append(parse_ir(consumer));
    let signals = schema_signals_for(contract);
    let clauses = signals
        .terminal_clauses()
        .iter()
        .filter(|clause| {
            clause
                .iter()
                .any(|guard| guard.value_paths().iter().any(|path| path == "global"))
        })
        .cloned()
        .collect::<Vec<_>>();

    sim_assert_eq!(
        have: clauses,
        want: vec![vec![helm_schema_core::ConditionalGuard::Absent {
            path: "global".to_string(),
        }]]
    );

    let schema = schema_for_values_yaml(
        signals,
        Some(indoc! {"
            _internal_defaults:
              global:
                resourceScope: all
        "}),
    );
    for (instance, want, label) in [
        (
            serde_json::json!({
                "_internal_defaults": {
                    "global": { "resourceScope": "all" }
                }
            }),
            true,
            "the pre-rewrite source supplies the host",
        ),
        (
            serde_json::json!({}),
            false,
            "removing both host spellings aborts",
        ),
        (
            serde_json::json!({ "_internal_defaults": {} }),
            false,
            "the surviving source root must still supply the host",
        ),
        (
            serde_json::json!({ "global": { "resourceScope": "all" } }),
            true,
            "an explicit effective host replaces the removed source",
        ),
        (
            serde_json::json!({ "global": {} }),
            true,
            "the accessed host may exist without the optional leaf",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
    let expected: Value = serde_json::from_str(include_str!(
        "fixtures/root_values_merge_source_presence.schema.json"
    ))?;
    sim_assert_eq!(have: schema, want: expected);
    Ok(())
}

#[test]
fn multiple_default_sources_for_one_values_target_abstain() {
    let first = indoc! {r#"
        {{- $defaults := .Values.first_defaults -}}
        {{- $_ := set $ "Values" (mustMergeOverwrite $defaults $.Values) -}}
    "#};
    let second = indoc! {r#"
        {{- $defaults := .Values.second_defaults -}}
        {{- $_ := set $ "Values" (mustMergeOverwrite $defaults $.Values) -}}
    "#};
    let consumer = indoc! {r#"
        {{- if eq .Values.mode "live" }}
        {{- $_ := pick .Values.payload "name" }}
        {{- end }}
    "#};
    let mut contract = parse_ir(first);
    contract.append(parse_ir(second));
    contract.append(parse_ir(consumer));
    let schema = schema_for_values_yaml(
        contract,
        Some(indoc! {"
            first_defaults:
              mode: live
              payload: {}
            second_defaults:
              mode: inactive
              payload: {}
        "}),
    );

    assert!(
        schema_accepts_instance(&schema, &serde_json::json!({ "payload": 7 })),
        "order-sensitive default sources must abstain instead of selecting lexical set order: {schema}"
    );
}

/// airflow's celery-broker sentinel accumulates a Boolean while ranging
/// `env` and terminates when neither `brokerUrlSecretName` nor an item
/// named `BROKER_URL_CMD` exists. The flag's truthiness is the existential
/// "some ranged item's member equals the literal", which Draft-07 encodes
/// with `contains`.
#[test]
fn existential_range_sentinel_lowers_to_contains() {
    let src = indoc! {r#"
        {{- if .Values.redis.enabled }}
        {{- $found := false }}
        {{- range .Values.env }}
        {{- if eq .name "BROKER_URL_CMD" }}
        {{- $found = true }}
        {{- break -}}
        {{- end }}
        {{- end }}
        {{- if not (or .Values.brokerUrlSecretName $found) }}
        {{ required "set brokerUrlSecretName or BROKER_URL_CMD in env" nil }}
        {{- end }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data: {}
    "#};
    let values_yaml = indoc! {r#"
        redis:
          enabled: true
        brokerUrlSecretName: ""
        env: []
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (instance, want) in [
        (serde_json::json!({ "redis": { "enabled": true } }), false),
        (
            serde_json::json!({ "redis": { "enabled": true }, "env": [{ "name": "OTHER" }] }),
            false,
        ),
        (
            serde_json::json!({ "redis": { "enabled": true }, "brokerUrlSecretName": "s" }),
            true,
        ),
        (
            serde_json::json!({ "redis": { "enabled": true }, "env": [{ "name": "BROKER_URL_CMD" }] }),
            true,
        ),
        (serde_json::json!({ "redis": { "enabled": false } }), true),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "existential sentinel: instance={instance}; schema={schema}"
        );
    }
}

/// A per-member `fail` under a truthy-and-type test requires every member
/// to be a TRUTHY string: sealed-secrets aborts on empty-string
/// `privateKeyAnnotations` members, not only on non-strings.
#[test]
fn ranged_member_truthy_string_test_requires_truthy_members() {
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          args: |-
            {{- if .Values.privateKeyAnnotations }}
            {{- $flags := "" }}
            {{- range $k, $v := .Values.privateKeyAnnotations }}
              {{- if not (and $v (kindIs "string" $v)) }}
                {{ fail "Annotation values have to be strings" }}
              {{- end }}
              {{- $flags = printf "%s=%s,%s" $k $v $flags }}
            {{- end }}
            {{ trimSuffix "," $flags }}
            {{- end }}
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some("privateKeyAnnotations: {}\n"));

    for (instance, want, label) in [
        (
            serde_json::json!({ "privateKeyAnnotations": { "audit": "ok" } }),
            true,
            "truthy string member",
        ),
        (
            serde_json::json!({ "privateKeyAnnotations": {} }),
            true,
            "empty map",
        ),
        (
            serde_json::json!({ "privateKeyAnnotations": { "audit": 7 } }),
            false,
            "numeric member",
        ),
        (
            serde_json::json!({ "privateKeyAnnotations": { "audit": "" } }),
            false,
            "empty-string member is falsy",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "truthy string member {label}: instance={instance}; schema={schema}"
        );
    }
}

/// A per-member `fail` keyed on literal name equality forbids exactly those
/// member names, under the clause's live outer guard: cilium rejects
/// `extraEnv` entries colliding with its backoff variables only while the
/// backoff feature is enabled.
#[test]
fn ranged_member_name_equality_fail_forbids_the_literal_names() {
    let src = indoc! {r#"
        {{- if .Values.k8sClientExponentialBackoff.enabled }}
        {{- range .Values.extraEnv }}
        {{- if or (eq .name "KUBE_CLIENT_BACKOFF_BASE") (eq .name "KUBE_CLIENT_BACKOFF_DURATION") }}
        {{ fail "k8sClientExponentialBackoff cannot be enabled when extraEnv contains KUBE_CLIENT_BACKOFF_BASE or KUBE_CLIENT_BACKOFF_DURATION" }}
        {{- end }}
        {{- end }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data: {}
    "#};
    let values_yaml = indoc! {r"
        k8sClientExponentialBackoff:
          enabled: true
        extraEnv: []
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (instance, want, label) in [
        // The coalesced document carries the declared `enabled: true`. A
        // document MISSING the whole host aborts on the header's own member
        // read, so only the explicit `enabled: false` arm is dormant.
        (
            serde_json::json!({
                "k8sClientExponentialBackoff": { "enabled": true },
                "extraEnv": [{ "name": "KUBE_CLIENT_BACKOFF_BASE", "value": "1" }]
            }),
            false,
            "forbidden name under the live guard",
        ),
        (
            serde_json::json!({ "extraEnv": [{ "name": "KUBE_CLIENT_BACKOFF_BASE", "value": "1" }] }),
            false,
            "a null-deleted guard host aborts the header read",
        ),
        (
            serde_json::json!({ "k8sClientExponentialBackoff": { "enabled": true },
                "extraEnv": [{ "name": "OTHER", "value": "1" }] }),
            true,
            "unrelated name",
        ),
        (
            serde_json::json!({
                "k8sClientExponentialBackoff": { "enabled": false },
                "extraEnv": [{ "name": "KUBE_CLIENT_BACKOFF_BASE", "value": "1" }]
            }),
            true,
            "forbidden name in the dead arm",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "forbidden member name {label}: instance={instance}; schema={schema}"
        );
    }
}

/// A `fail` keyed on a range-KEY regex constrains the collection's key
/// domain through `propertyNames`: traefik aborts on uppercase
/// `ingressRoute` keys.
#[test]
fn range_key_regex_fail_lowers_to_property_names() {
    let src = indoc! {r#"
        {{- range $name, $config := .Values.ingressRoute }}
        {{- if regexMatch "[A-Z]" $name }}
        {{- fail (printf "ERROR: ingressRoute key %q contains uppercase characters." $name) }}
        {{- end }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data: {}
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some("ingressRoute: {}\n"));

    for (instance, want, label) in [
        (
            serde_json::json!({ "ingressRoute": { "dashboard": {} } }),
            true,
            "lowercase key",
        ),
        (serde_json::json!({ "ingressRoute": {} }), true, "empty map"),
        (
            serde_json::json!({ "ingressRoute": { "Dashboard": {} } }),
            false,
            "uppercase key",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "range key regex {label}: instance={instance}; schema={schema}"
        );
    }
}

/// cilium's validators state finite scalar domains through `fail` guards: a
/// `len` bound, an `int`-coerced inequality pair, and a negated literal
/// membership. Each conjunct lowers through its sound subset, so the
/// terminal clauses reject exactly the strengthened domains while coerced
/// spellings outside the subsets stay open.
///
/// The `len` guard also demands its own subject: "len of nil pointer"
/// aborts before the comparison, so a null-deleted `clusterName` never
/// reaches the domain question at all.
#[test]
fn scalar_domain_fail_guards_lower_through_sound_subsets() {
    let src = indoc! {r#"
        {{- if gt (len .Values.clusterName) 8 }}
        {{ fail "cluster name too long" }}
        {{- end }}
        {{- if and (ne (int .Values.maxClusters) 255) (ne (int .Values.maxClusters) 511) }}
        {{ fail "must be 255 or 511" }}
        {{- end }}
        {{- if not (list "internal" "external" | has .Values.mode) }}
        {{ fail "mode must be internal or external" }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data: {}
    "#};
    let values_yaml = indoc! {r"
        clusterName: default
        maxClusters: 255
        mode: internal
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (instance, want) in [
        (
            serde_json::json!({ "clusterName": "123456789", "maxClusters": 255, "mode": "internal" }),
            false,
        ),
        (
            serde_json::json!({ "clusterName": "12345678", "maxClusters": 255, "mode": "internal" }),
            true,
        ),
        (
            serde_json::json!({ "clusterName": "ok", "maxClusters": 300, "mode": "internal" }),
            false,
        ),
        (
            serde_json::json!({ "clusterName": "ok", "maxClusters": 511, "mode": "internal" }),
            true,
        ),
        // A numeric string coerces exactly like the raw integer: the
        // region disjunction claims spellings certainly parsing outside
        // {255, 511} while the bound spellings stay accepted.
        (
            serde_json::json!({ "clusterName": "ok", "maxClusters": "255", "mode": "internal" }),
            true,
        ),
        (
            serde_json::json!({ "clusterName": "ok", "maxClusters": "0x1ff", "mode": "internal" }),
            true,
        ),
        (
            serde_json::json!({ "clusterName": "ok", "maxClusters": "300", "mode": "internal" }),
            false,
        ),
        (
            serde_json::json!({ "clusterName": "ok", "maxClusters": "bogus", "mode": "internal" }),
            false,
        ),
        (
            serde_json::json!({ "clusterName": "ok", "mode": "bogus", "maxClusters": 255 }),
            false,
        ),
        (
            serde_json::json!({ "clusterName": "ok", "mode": "external", "maxClusters": 255 }),
            true,
        ),
        // `len` reads the subject before the bound: a null-deleted name
        // aborts rendering rather than passing the length test.
        (
            serde_json::json!({ "maxClusters": 255, "mode": "internal" }),
            false,
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "scalar-domain fail guards: instance={instance}; schema={schema}"
        );
    }
}

/// jenkins' `controller.replicas` validator binds the int cast to a LOCAL
/// (`$replicas := int (default 1 …)`) inside a helper and fails outside
/// 0..=1. The cast provenance rides the binding, so both disjuncts lower
/// through the raw-integer subsets exactly as the inline spellings would —
/// including the new below-bound direction.
#[test]
fn variable_bound_coercion_fail_guards_lower_through_sound_subsets() {
    let helpers = indoc! {r#"
        {{- define "controller.replicas" -}}
        {{- $replicas := int (default 1 .Values.controller.replicas) -}}
        {{- if or (lt $replicas 0) (gt $replicas 1) -}}
        {{- fail "controller.replicas must be 0 or 1" -}}
        {{- end -}}
        {{- .Values.controller.replicas -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          replicas: {{ include "controller.replicas" . | quote }}
    "#};
    let values_yaml = indoc! {r"
        controller:
          replicas: 1
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (instance, want) in [
        (
            serde_json::json!({ "controller": { "replicas": 2 } }),
            false,
        ),
        (
            serde_json::json!({ "controller": { "replicas": -1 } }),
            false,
        ),
        (serde_json::json!({ "controller": { "replicas": 1 } }), true),
        (serde_json::json!({ "controller": { "replicas": 0 } }), true),
        // Clean decimal spellings coerce into the failing domain at render
        // time, so the string preimage rejects them alongside raw integers.
        (
            serde_json::json!({ "controller": { "replicas": "5" } }),
            false,
        ),
        (
            serde_json::json!({ "controller": { "replicas": "-1" } }),
            false,
        ),
        (
            serde_json::json!({ "controller": { "replicas": "1" } }),
            true,
        ),
        // A leading zero flips ParseInt's base detection to octal: "09"
        // is a parse ERROR coercing to 0 — inside the domain — while
        // valid octal and hex spellings coerce beyond it and reject.
        (
            serde_json::json!({ "controller": { "replicas": "09" } }),
            true,
        ),
        (
            serde_json::json!({ "controller": { "replicas": "05" } }),
            false,
        ),
        (
            serde_json::json!({ "controller": { "replicas": "0x5" } }),
            false,
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "variable-bound coercion fail guards: instance={instance}; schema={schema}"
        );
    }
}

/// cilium `kubeProxyReplacement`: the configmap stringifies the value
/// (`toString`, a `<nil>` → `""` rewrite, `coalesce` with a literal
/// default) before comparing it against `"true"`/`"false"` and failing
/// otherwise. The equality binds the raw path through the `toString`
/// PREIMAGE, so raw Booleans render exactly like their string spellings
/// while any other truthy scalar aborts.
#[test]
fn stringified_equality_binds_the_tostring_preimage() {
    let src = indoc! {r#"
        {{- $default := "false" -}}
        {{- $string := (toString .Values.kubeProxyReplacement) -}}
        {{- if (eq $string "<nil>") }}
          {{- $string = "" -}}
        {{- end }}
        {{- $mode := (coalesce $string $default) -}}
        {{- if and (ne $mode "true") (ne $mode "false") }}
        {{ fail "kubeProxyReplacement must be true or false" }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          mode: {{ $mode | quote }}
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), None);
    for (instance, want) in [
        (serde_json::json!({ "kubeProxyReplacement": true }), true),
        (serde_json::json!({ "kubeProxyReplacement": false }), true),
        (serde_json::json!({ "kubeProxyReplacement": "true" }), true),
        (serde_json::json!({ "kubeProxyReplacement": "false" }), true),
        // An EMPTY stringification selects the coalesce's constant default
        // ("false"), so the empty and null raw spellings render too: "" is
        // Helm-empty directly, and null reaches "" through the chain's
        // `"<nil>"` rewrite.
        (serde_json::json!({ "kubeProxyReplacement": "" }), true),
        (serde_json::json!({ "kubeProxyReplacement": null }), true),
        (
            serde_json::json!({ "kubeProxyReplacement": "strict" }),
            false,
        ),
        (serde_json::json!({ "kubeProxyReplacement": 1 }), false),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "stringified equality preimage: instance={instance}; schema={schema}"
        );
    }
}

/// Pattern predicates over `toString` test rendered text for every raw
/// input kind. Their fail arms can still reject the exact raw-string subset:
/// a string that misses the pattern reaches `fail`, while a numeric value
/// whose rendering matches remains valid.
#[test]
fn stringified_pattern_fail_arms_keep_the_raw_string_mismatch_subset() {
    let src = indoc! {r#"
        {{- if not (regexMatch "^[0-9]+$" (toString .Values.regex)) }}
        {{- fail "regex mismatch" }}
        {{- end }}
        {{- if not (contains "2" (toString .Values.contains)) }}
        {{- fail "contains mismatch" }}
        {{- end }}
        {{- if not (hasPrefix "1" (toString .Values.prefix)) }}
        {{- fail "prefix mismatch" }}
        {{- end }}
        {{- if not (hasSuffix "3" (toString .Values.suffix)) }}
        {{- fail "suffix mismatch" }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
    "#};
    let values_yaml = indoc! {"
        regex: 3
        contains: 123
        prefix: 123
        suffix: 123
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (overrides, want, label) in [
        (
            serde_json::json!({ "regex": "bad" }),
            false,
            "regex string mismatch",
        ),
        (
            serde_json::json!({ "contains": "bad" }),
            false,
            "contains string mismatch",
        ),
        (
            serde_json::json!({ "prefix": "bad" }),
            false,
            "prefix string mismatch",
        ),
        (
            serde_json::json!({ "suffix": "bad" }),
            false,
            "suffix string mismatch",
        ),
        (
            serde_json::json!({
                "regex": 3,
                "contains": 123,
                "prefix": 123,
                "suffix": 123
            }),
            true,
            "matching numeric renderings",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// cilium's removed-option guards stringify a `dig` result before testing
/// truthiness: `"false"`, `"0"`, and `"<nil>"` are truthy STRINGS, so an
/// explicitly-disabled removed option still aborts the render. Only an
/// absent chain (the dig's empty-string default) or a raw empty string is
/// falsy; the sibling raw-`dig` disjunct keeps ordinary Helm truthiness.
#[test]
fn stringified_dig_truthiness_rejects_falsy_raw_spellings() {
    let src = indoc! {r#"
        {{- if or
          ((dig "proxy" "prometheus" "enabled" "" .Values.AsMap) | toString)
          (dig "proxy" "prometheus" "port" "" .Values.AsMap)
        }}
        {{ fail "proxy.prometheus.enabled and proxy.prometheus.port were removed" }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          ok: "yes"
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), None);
    for (instance, want, label) in [
        (serde_json::json!({}), true, "absent chain renders"),
        (
            serde_json::json!({ "proxy": { "prometheus": {} } }),
            true,
            "absent leaf renders",
        ),
        (
            serde_json::json!({ "proxy": { "prometheus": { "enabled": "" } } }),
            true,
            "raw empty string stringifies to the falsy empty rendering",
        ),
        (
            serde_json::json!({ "proxy": { "prometheus": { "enabled": false } } }),
            false,
            "raw false renders truthy \"false\"",
        ),
        (
            serde_json::json!({ "proxy": { "prometheus": { "enabled": true } } }),
            false,
            "raw true renders truthy \"true\"",
        ),
        (
            serde_json::json!({ "proxy": { "prometheus": { "enabled": null } } }),
            false,
            "explicit null renders truthy \"<nil>\"",
        ),
        (
            serde_json::json!({ "proxy": { "prometheus": { "enabled": 0 } } }),
            false,
            "raw zero renders truthy \"0\"",
        ),
        (
            serde_json::json!({ "proxy": { "prometheus": { "port": 9095 } } }),
            false,
            "the sibling raw-dig disjunct keeps Helm truthiness",
        ),
        (
            serde_json::json!({ "proxy": { "prometheus": { "port": "" } } }),
            true,
            "a falsy sibling value renders",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "stringified dig truthiness ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// Truthiness of a DIRECT total stringification tests the rendered text:
/// `toString nil` is the truthy `"<nil>"`, so an absent or null subject
/// passes a `not (.Values.mode | toString)` gate and only the raw empty
/// string fails it. traefik's `with .addX | toString` flag family rides
/// the same decode — its bodies run for raw `false` too.
#[test]
fn direct_tostring_truthiness_is_a_rendering_test() {
    let src = indoc! {r#"
        {{- if not (.Values.mode | toString) }}
        {{ fail "mode must not stringify empty" }}
        {{- end }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
          mode: {{ .Values.mode | toString | quote }}
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), None);
    for (instance, want, label) in [
        (
            serde_json::json!({}),
            true,
            "absent renders truthy \"<nil>\"",
        ),
        (
            serde_json::json!({ "mode": null }),
            true,
            "null renders truthy \"<nil>\"",
        ),
        (
            serde_json::json!({ "mode": false }),
            true,
            "raw false renders truthy \"false\"",
        ),
        (
            serde_json::json!({ "mode": 0 }),
            true,
            "raw zero renders truthy \"0\"",
        ),
        (
            serde_json::json!({ "mode": "" }),
            false,
            "only the raw empty string stringifies empty",
        ),
        (serde_json::json!({ "mode": "x" }), true, "text renders"),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "direct toString truthiness ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// traefik's local-plugin type helper renders each ranged member through
/// mutually exclusive arms — a `type` from a literal enum, or the legacy
/// bare `hostPath` — and `fail`s otherwise. The member requirements are
/// the DISJUNCTION of the arm negations: either documented shape renders
/// alone, while an unknown `type` (even beside a hostPath) and a member
/// with neither field abort.
#[test]
fn multi_test_fail_negations_lower_as_member_alternatives() {
    let helpers = indoc! {r#"
        {{- define "repro.pluginType" -}}
            {{- $plugin := .plugin -}}
            {{- if $plugin.type -}}
                {{- if eq $plugin.type "hostPath" -}}
                    {{- printf "hostPath" -}}
                {{- else if eq $plugin.type "inlinePlugin" -}}
                    {{- printf "inlinePlugin" -}}
                {{- else -}}
                    {{- fail (printf "plugin %s has an invalid type" .pluginName) -}}
                {{- end -}}
            {{- else if $plugin.hostPath -}}
                {{- printf "hostPath" -}}
            {{- else -}}
                {{- fail (printf "plugin %s must set hostPath or type" .pluginName) -}}
            {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        {{- if .Values.plugins }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: plugins
        data:
          {{- range $name, $plugin := .Values.plugins }}
          {{ $name }}: {{ include "repro.pluginType" (dict "plugin" $plugin "pluginName" $name) | quote }}
          {{- end }}
        {{- end }}
    "#};
    let values_yaml = indoc! {r"
        plugins: {}
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (member, want) in [
        (serde_json::json!({ "hostPath": "/plugins/x" }), true),
        (
            serde_json::json!({ "type": "hostPath", "hostPath": "/plugins/x" }),
            true,
        ),
        (serde_json::json!({ "type": "inlinePlugin" }), true),
        (serde_json::json!({ "type": "bogus" }), false),
        (
            serde_json::json!({ "type": "bogus", "hostPath": "/plugins/x" }),
            false,
        ),
        (serde_json::json!({ "moduleName": "x" }), false),
        (serde_json::json!("scalar"), false),
    ] {
        let instance = serde_json::json!({ "plugins": { "p": member } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "member alternatives: instance={instance}; schema={schema}"
        );
    }
}

/// kyverno's `kyverno.deployment.replicas` helper (called through
/// `{{ template … .Values.X.replicas }}`) fails on `eq (int .) 0` when the
/// argument is neither nil nor a string: a raw integer (or integral
/// float) zero certainly satisfies the coercing equality, so the fail arm
/// rejects it while strings and null keep the helper's own escapes. The
/// equality lowers as the [`IntGt` bound-1, `IntLt` bound+1] region pair —
/// coercible non-integers (booleans, fractional floats) stay a documented
/// sound abstention.
#[test]
fn int_cast_zero_equality_fails_reject_raw_zero() {
    let helpers = indoc! {r#"
        {{- define "repro.replicas" -}}
          {{- if and (not (kindIs "invalid" .)) (not (kindIs "string" .)) -}}
          {{- if eq (int .) 0 -}}
            {{- fail "no zero replicas" -}}
          {{- end -}}
          {{- end -}}
          {{- . -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        config:
          replicas: {{ template "repro.replicas" .Values.replicas }}
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some("replicas: 1\n"));
    for (instance, want, label) in [
        (serde_json::json!({}), true, "absent renders empty"),
        (serde_json::json!({ "replicas": null }), true, "nil escapes"),
        (
            serde_json::json!({ "replicas": 1 }),
            true,
            "nonzero renders",
        ),
        (
            serde_json::json!({ "replicas": -1 }),
            true,
            "negative renders",
        ),
        (
            serde_json::json!({ "replicas": "0" }),
            true,
            "strings escape the kind dispatch",
        ),
        (
            serde_json::json!({ "replicas": 0 }),
            false,
            "raw zero aborts",
        ),
        (
            serde_json::json!({ "replicas": 0.0 }),
            false,
            "integral float zero aborts",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "int-cast zero equality ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// The int-cast regions' STRING preimages follow `strconv.ParseInt` base
/// 0 (all polarities helm-verified): single-sign regions add the radix
/// spellings that certainly parse inside (`"0x10"`/`"017"` abort a
/// positive-bound gate like raw 16/15 do), a below-zero region keeps
/// zero-padded VALID octal while an 8/9 digit is a parse error coercing
/// to 0 (`"-018"` renders — the old pattern falsely rejected it), and a
/// MIXED-sign region (positive `lt` bound) claims the complement of the
/// parse-escape language: every unparsable, empty, or negative spelling
/// coerces to 0 inside the region while a successful parse past the
/// bound escapes.
#[test]
fn int_cast_string_preimages_cover_radix_and_complement_lanes() {
    let src = indoc! {r#"
        {{- if gt (int64 .Values.count) 0 }}
        {{- fail "count must not be positive" }}
        {{- end }}
        {{- if lt (int .Values.floor) 3 }}
        {{- fail "floor too low" }}
        {{- end }}
        {{- if lt (int .Values.neg) 0 }}
        {{- fail "neg must not be negative" }}
        {{- end }}
        config:
          ok: true
    "#};
    let schema = schema_for_values_yaml(
        parse_ir(src),
        Some(indoc! {"
            count: 0
            floor: 5
            neg: 1
        "}),
    );
    for (instance, want, label) in [
        (
            serde_json::json!({ "count": "0x10", "floor": 5 }),
            false,
            "hex above 0",
        ),
        (
            serde_json::json!({ "count": "017", "floor": 5 }),
            false,
            "legacy octal above 0",
        ),
        (
            serde_json::json!({ "count": "0", "floor": 5 }),
            true,
            "zero renders",
        ),
        (
            serde_json::json!({ "floor": "abc" }),
            false,
            "unparsable coerces to 0 below the floor",
        ),
        (
            serde_json::json!({ "floor": "" }),
            false,
            "empty coerces to 0 below the floor",
        ),
        (
            serde_json::json!({ "floor": "-5" }),
            false,
            "negative parse lands below the floor",
        ),
        (
            serde_json::json!({ "floor": "0x10" }),
            true,
            "hex parse escapes past the floor",
        ),
        (
            serde_json::json!({ "floor": "3" }),
            true,
            "boundary parse escapes",
        ),
        // "2" coerces below the floor and aborts Helm: the exact escape
        // windows see it certainly parsing below 3, so the complement
        // lane claims it (the old char-count escape widened here).
        (
            serde_json::json!({ "floor": "2" }),
            false,
            "in-language low parse is claimed exactly",
        ),
        (
            serde_json::json!({ "neg": "-018", "floor": 5 }),
            true,
            "invalid octal digit coerces to 0 and renders",
        ),
        (
            serde_json::json!({ "neg": "-09", "floor": 5 }),
            true,
            "invalid octal 9 coerces to 0 and renders",
        ),
        (
            serde_json::json!({ "neg": "-017", "floor": 5 }),
            false,
            "valid zero-padded octal parses negative",
        ),
        (
            serde_json::json!({ "neg": "-0x10", "floor": 5 }),
            false,
            "negative hex parses negative",
        ),
        (
            serde_json::json!({ "neg": "-5", "floor": 5 }),
            false,
            "clean negative decimal",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "int-cast string preimage ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// A conjunction of `ne $item.field "…"` inequalities guarding a ranged
/// fail negates to the DISJUNCTION of the equalities — the field's value
/// enum (nats' jsonpatch `op` gate, in the direct-range shape). Each
/// `FieldEquals` alternative carries presence, so a member missing the
/// field rejects too.
#[test]
fn ranged_not_equals_chains_negate_to_the_field_enum() {
    let src = indoc! {r#"
        {{- range $patch := .Values.service.patch }}
        {{- if and (ne $patch.op "add") (ne $patch.op "remove") }}
        {{- fail "patch has invalid op" }}
        {{- end }}
        {{- end }}
        config:
          ok: true
    "#};
    let schema = schema_for_values_yaml(
        parse_ir(src),
        Some(indoc! {"
            service:
              patch: []
        "}),
    );
    for (item, want, label) in [
        (serde_json::json!({ "op": "add" }), true, "add allowed"),
        (
            serde_json::json!({ "op": "remove" }),
            true,
            "remove allowed",
        ),
        (
            serde_json::json!({ "op": "bogus" }),
            false,
            "unknown op aborts",
        ),
        (serde_json::json!({}), false, "missing op aborts"),
    ] {
        let instance = serde_json::json!({ "service": { "patch": [item] } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "ranged ne-chain enum ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// A fail nested under a range over a LOCAL-DICT overlay (`$services :=
/// .Values.service.additionalServices` + `set $services "default"
/// (omit …)`) still terminates: the overlay's literal entry iterates on
/// every render, so the member gate re-decodes under that DEFINITE
/// binding as a sound subset and the inner terminal binds (traefik's
/// http3-without-tls abort under the always-present "default" service).
#[test]
fn overlay_range_member_gates_carry_definite_entry_sound_subsets() {
    let src = indoc! {r#"
        {{- $services := .Values.service.additionalServices -}}
        {{- $services = set $services "default" (omit .Values.service "additionalServices") }}
        {{- range $name, $service := $services -}}
        {{- if ne $service.enabled false -}}
        {{- range $portName, $config := $.Values.ports -}}
          {{- if $config -}}
            {{- if ($config.http3).enabled -}}
              {{- if (not ($config.http).tls.enabled) -}}
                {{- fail "ERROR: You cannot enable http3 without enabling tls" -}}
              {{- end -}}
            {{- end -}}
          {{- end -}}
        {{- end -}}
        kind: Service
        apiVersion: v1
        metadata:
          name: {{ $name }}
        {{- end }}
        {{- end }}
    "#};
    let values_yaml = indoc! {r"
        service:
          enabled: true
          additionalServices: {}
        ports:
          web:
            port: 8000
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    // Cases compose over the declared defaults: the local overlay reads
    // `.Values.service.additionalServices` on every render, so the
    // `service` host rides along.
    for (overrides, want, label) in [
        (
            serde_json::json!({}),
            true,
            "a port without an http3 block skips the terminal",
        ),
        (
            serde_json::json!({ "ports": { "web": { "http3": { "enabled": true } } } }),
            false,
            "http3 without tls aborts through the default service",
        ),
        (
            serde_json::json!({ "ports": { "web": { "http3": { "enabled": true },
                "http": { "tls": { "enabled": true } } } } }),
            true,
            "http3 with tls renders",
        ),
        (
            serde_json::json!({ "service": { "enabled": false },
                "ports": { "web": { "http3": { "enabled": true } } } }),
            true,
            "a disabled default service keeps the terminal dormant",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "overlay-range terminal ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// A ranged fail whose test CONJOINS several member conditions negates to
/// the disjunction of their negations, per member: an equality on a member
/// field flips to the absence-tolerant `FieldNotEquals`, a negated
/// truthiness over a nested field flips to `FieldHelmTruthy`, and the
/// member's own truthiness gate contributes the Helm-falsy escape
/// (traefik's HTTPS-listener certificateRefs and http3-without-tls
/// terminals).
#[test]
fn compound_ranged_terminals_negate_to_member_alternatives() {
    let src = indoc! {r#"
        {{- range $name, $config := .Values.gateway.listeners }}
        {{- if and (eq .protocol "HTTPS") (not .certificateRefs) }}
        {{- fail "ERROR: certificateRefs needs to be specified using HTTPS" }}
        {{- end }}
        {{- end }}
        {{- range $portName, $config := .Values.ports }}
        {{- if $config }}
        {{- if ($config.http3).enabled }}
        {{- if not ($config.http).tls.enabled }}
        {{- fail "ERROR: You cannot enable http3 without enabling tls" }}
        {{- end }}
        {{- end }}
        {{- end }}
        {{- end }}
        config:
          ok: true
    "#};
    let values_yaml = indoc! {r"
        gateway:
          listeners: {}
        ports: {}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (listener, want, label) in [
        (
            serde_json::json!({ "protocol": "HTTPS", "port": 443 }),
            false,
            "an HTTPS listener without certificateRefs aborts",
        ),
        (
            serde_json::json!({ "protocol": "HTTPS", "port": 443,
                "certificateRefs": [{ "name": "tls" }] }),
            true,
            "an HTTPS listener with certificateRefs renders",
        ),
        (
            serde_json::json!({ "protocol": "HTTPS", "port": 443,
                "certificateRefs": [] }),
            false,
            "an empty certificateRefs list is Helm-falsy and aborts",
        ),
        (
            serde_json::json!({ "protocol": "HTTP", "port": 80 }),
            true,
            "a non-HTTPS listener escapes the terminal",
        ),
    ] {
        let instance = serde_json::json!({ "gateway": { "listeners": { "web": listener } } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "listener terminal ({label}): instance={instance}; schema={schema}"
        );
    }
    for (port, want, label) in [
        (
            serde_json::json!({ "http3": { "enabled": true } }),
            false,
            "http3 without tls aborts",
        ),
        (
            serde_json::json!({ "http3": { "enabled": true },
                "http": { "tls": { "enabled": true } } }),
            true,
            "http3 with tls renders",
        ),
        (
            serde_json::json!({ "http3": { "enabled": false } }),
            true,
            "disabled http3 escapes",
        ),
        (
            serde_json::json!({ "port": 8000 }),
            true,
            "an absent http3 block escapes",
        ),
        (serde_json::json!(null), true, "a falsy port config escapes"),
    ] {
        // `.Values.gateway.listeners` is navigated on every render, so the
        // composed instance keeps the `gateway` host.
        let instance = serde_json::json!({ "gateway": { "listeners": {} },
            "ports": { "web": port } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "http3 terminal ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// A HELPER-SCOPE range over a JSON-roundtripped dict member carries the
/// member identity into its fail captures: the nats `jsonpatch` shape —
/// `$params := fromJson (toJson .)`, `$patches := $params.patch`,
/// `range $patch := $patches` with `hasKey`/`ne $patch.op` gates — must
/// bind the caller's `service.patch` members instead of truncating to
/// `service.patch.op` and leaking document-level terminals.
#[test]
fn helper_scope_ranges_bind_member_identities_in_fail_captures() {
    let helpers = indoc! {r#"
        {{- define "repro.jsonpatch" -}}
          {{- $params := fromJson (toJson .) -}}
          {{- $patches := $params.patch -}}
          {{- range $patch := $patches -}}
            {{- if not (hasKey $patch "op") -}}
              {{- fail "patch is missing op key" -}}
            {{- end -}}
            {{- if and (ne $patch.op "add") (ne $patch.op "remove") (ne $patch.op "replace") -}}
              {{- fail (cat "patch has invalid op" $patch.op) -}}
            {{- end -}}
          {{- end -}}
          {{- toJson . -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: t
        data:
          out: {{ include "repro.jsonpatch" (dict "doc" (dict) "patch" (.Values.service.patch | default list)) | quote }}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_helpers(src, helpers),
        Some(indoc! {"
            service:
              patch: []
        "}),
    );
    for (patch, want, label) in [
        (serde_json::json!([]), true, "an empty patch list renders"),
        (
            serde_json::json!([{ "op": "add", "path": "/a" }]),
            true,
            "a valid op renders",
        ),
        (
            serde_json::json!([{ "op": "bogus" }]),
            false,
            "an unknown op aborts",
        ),
        (
            serde_json::json!([{ "path": "/a" }]),
            false,
            "a patch without op aborts",
        ),
    ] {
        let instance = serde_json::json!({ "service": { "patch": patch } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "helper-range member identity ({label}): instance={instance}; schema={schema}"
        );
    }
    let unrelated = serde_json::json!({ "service": { "patch": [{ "op": "add" }], "extra": 1 } });
    assert!(
        schema_accepts_instance(&schema, &unrelated),
        "sibling members stay open: {schema}"
    );
}

/// cilium's provider-mode gates spell their tests through defaulted
/// pipelines and negated equality disjunctions: `ne (.Values.routingMode
/// | default "native") "native"` aborts GKE+tunnel while the unset and
/// explicit-native spellings render, and `not (or (eq P "Cluster")
/// (eq P "Local"))` aborts any other traffic policy. Both must decode
/// exactly — the truthiness weakenings accept the invalid spellings.
#[test]
fn defaulted_pipeline_and_negated_disjunction_tests_decode() {
    let src = indoc! {r#"
        config:
          {{- if .Values.gke.enabled }}
          {{- if ne (.Values.routingMode | default "native") "native" }}
          {{- fail "RoutingMode must be set to native when gke.enabled=true" }}
          {{- end }}
          endpointRoutes: true
          {{- end }}
          {{- if .Values.ingress.enabled }}
          {{- if not (or (eq .Values.ingress.policy "Cluster") (eq .Values.ingress.policy "Local")) }}
          {{- fail "policy must be Cluster or Local" }}
          {{- end }}
          policy: {{ .Values.ingress.policy }}
          {{- end }}
          ok: true
    "#};
    let values_yaml = indoc! {r#"
        gke:
          enabled: false
        routingMode: ""
        ingress:
          enabled: false
          policy: Cluster
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    // Cases compose over the chart's declared defaults: the `gke` and
    // `ingress` hosts are navigated on every render, so a document dropping
    // them is the null-deleted state, not a dormant one.
    for (overrides, want, label) in [
        (serde_json::json!({}), true, "defaults render"),
        (
            serde_json::json!({ "gke": { "enabled": true } }),
            true,
            "gke with the unset routing mode takes the default",
        ),
        (
            serde_json::json!({ "gke": { "enabled": true }, "routingMode": "native" }),
            true,
            "gke with explicit native renders",
        ),
        (
            serde_json::json!({ "gke": { "enabled": true }, "routingMode": "tunnel" }),
            false,
            "gke with tunnel aborts",
        ),
        (
            serde_json::json!({ "routingMode": "tunnel" }),
            true,
            "tunnel without gke stays open",
        ),
        (
            serde_json::json!({ "ingress": { "enabled": true, "policy": "Local" } }),
            true,
            "a listed policy renders",
        ),
        (
            serde_json::json!({ "ingress": { "enabled": true, "policy": "Foo" } }),
            false,
            "an unlisted policy aborts",
        ),
        (
            serde_json::json!({ "ingress": { "enabled": false, "policy": "Foo" } }),
            true,
            "the disabled gate keeps the policy open",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "defaulted pipeline and negated disjunction ({label}): \
             instance={instance}; schema={schema}"
        );
    }
}

/// vault's `validateRedundancyZones` helper spells every gate through a
/// `| toString` pipeline (`eq (.Values.…enabled | toString) "true"` as
/// the outer guard, `ne (.Values.server.ha.enabled | toString) "true"`
/// as the failing tests): the pipeline stringification must decode like
/// the `toString X` call form so the values-decidable combination
/// implications reach the schema. The helper's Kubernetes-version semver
/// fail is cluster-dependent and must abstain, keeping the valid
/// combination open.
#[test]
fn pipeline_tostring_gates_decode_in_helper_terminals() {
    let helpers = indoc! {r#"
        {{- define "repro.validate" -}}
        {{- if eq (.Values.zones.enabled | toString) "true" -}}
        {{- if ne (.Values.ha.enabled | toString) "true" -}}
        {{- fail "zones.enabled=true requires ha.enabled=true" -}}
        {{- end -}}
        {{- if ne (.Values.raft.enabled | toString) "true" -}}
        {{- fail "zones.enabled=true requires raft.enabled=true" -}}
        {{- end -}}
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        {{- include "repro.validate" . -}}
        replicas: {{ .Values.replicas }}
    "#};
    let values_yaml = indoc! {r"
        replicas: 1
        zones:
          enabled: false
        ha:
          enabled: false
        raft:
          enabled: false
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    // Cases compose over the declared defaults: the three gate hosts are
    // navigated on every render.
    for (overrides, want, label) in [
        (serde_json::json!({}), true, "defaults skip the gates"),
        (
            serde_json::json!({ "zones": { "enabled": true },
                "ha": { "enabled": true }, "raft": { "enabled": true } }),
            true,
            "the full combination renders",
        ),
        (
            serde_json::json!({ "zones": { "enabled": true } }),
            false,
            "zones without ha aborts",
        ),
        (
            serde_json::json!({ "zones": { "enabled": true }, "ha": { "enabled": true } }),
            false,
            "zones without raft aborts",
        ),
        (
            serde_json::json!({ "ha": { "enabled": true } }),
            true,
            "ha alone stays open",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "pipeline tostring gates ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// datadog's OTLP verify helpers are included with the dot bound to a
/// SCALAR (`include "verify-…" .grpc.endpoint` under a `with` over the
/// protocols map): their `hasPrefix "unix:" .` / `not (regexMatch
/// ":[0-9]+$" .)` fails must bind the caller's endpoint path with the
/// enabling guards retained (helm rejects the unix and portless
/// endpoints, renders the host:port one).
#[test]
fn scalar_dot_helper_terminals_bind_the_caller_argument_path() {
    let helpers = indoc! {r#"
        {{- define "repro.verifyPrefix" -}}
        {{- if hasPrefix "unix:" . }}
        {{ fail "'unix' protocol is not supported" }}
        {{- end }}
        {{- end -}}
        {{- define "repro.verifyPort" -}}
        {{- if not ( regexMatch ":[0-9]+$" . ) }}
        {{ fail "port must be set explicitly" }}
        {{- end }}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        ports:
          {{- with .Values.otlp.protocols }}
          {{- if (and .grpc .grpc.enabled) }}
          {{- include "repro.verifyPrefix" .grpc.endpoint }}
          {{- include "repro.verifyPort" .grpc.endpoint }}
          - port: 4317
          {{- end }}
          {{- end }}
    "#};
    let values_yaml = indoc! {r#"
        otlp:
          protocols:
            grpc:
              enabled: false
              endpoint: "0.0.0.0:4317"
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (endpoint, want, label) in [
        ("0.0.0.0:4317", true, "host:port renders"),
        ("unix:///tmp/otlp.sock", false, "unix protocol aborts"),
        ("0.0.0.0", false, "a portless endpoint aborts"),
        // A port-suffixed unix endpoint passes the port test, so only the
        // decoded prefix terminal can reject it (helm-verified on datadog).
        (
            "unix:///tmp/otlp.sock:4317",
            false,
            "unix protocol aborts despite a port",
        ),
    ] {
        let enabled = serde_json::json!({ "otlp": { "protocols": { "grpc": {
            "enabled": true, "endpoint": endpoint } } } });
        assert!(
            schema_accepts_instance(&schema, &enabled) == want,
            "scalar-dot helper terminal ({label}): instance={enabled}; schema={schema}"
        );
        let disabled = serde_json::json!({ "otlp": { "protocols": { "grpc": {
            "enabled": false, "endpoint": endpoint } } } });
        assert!(
            schema_accepts_instance(&schema, &disabled),
            "scalar-dot helper terminal (disabled gate keeps {label} open): \
             instance={disabled}; schema={schema}"
        );
    }
}

/// oauth2-proxy's `redis.StandaloneUrl` helper terminates rendering when
/// neither `connectionUrl` is set nor the redis subchart enabled; the
/// caller invokes it only for the `standalone` client type. The helper's
/// fail must reach the caller with BOTH its internal guards (the url
/// truthiness and the subchart-enabled include, whose helper renders a
/// single decodable boolean expression) AND the caller's live clientType
/// guard.
#[test]
fn helper_terminals_keep_caller_guards_and_boolean_include_arms() {
    let helpers = indoc! {r#"
        {{- define "repro.enabled" -}}
          {{- eq (index .Values "redis-ha" "enabled") true -}}
        {{- end -}}
        {{- define "repro.url" -}}
        {{- if .Values.session.url -}}
        {{ .Values.session.url }}
        {{- else if eq (include "repro.enabled" .) "true" -}}
        {{- printf "redis://auto" -}}
        {{- else -}}
        {{ fail "please set session.url or enable the redis subchart" }}
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        config:
          {{- if eq (default "" .Values.session.clientType) "standalone" }}
          url: {{ include "repro.url" . }}
          {{- end }}
          ok: true
    "#};
    let values_yaml = indoc! {r#"
        session:
          clientType: ""
        redis-ha:
          enabled: false
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (instance, want, label) in [
        (
            serde_json::json!({ "session": { "clientType": "" } }),
            true,
            "defaults skip the include",
        ),
        (
            serde_json::json!({ "session": { "clientType": "standalone",
                "url": "redis://myredis:6379" } }),
            true,
            "an explicit url renders",
        ),
        (
            serde_json::json!({ "session": { "clientType": "standalone" },
                "redis-ha": { "enabled": true } }),
            true,
            "the enabled subchart computes the url",
        ),
        (
            serde_json::json!({ "session": { "clientType": "standalone" } }),
            false,
            "standalone without a url aborts",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "helper terminal caller guards ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// A root-context key assigned a literal in EVERY arm of a complete
/// if/else chain (vault's five-arm `vault.mode`) joins into a value
/// dispatch: `ne .mode "external"` / `eq .mode "ha"` decode as the exact
/// disjunction of the assigning arms. Fails behind those guards reach the
/// schema, and a configuration selecting the "external" arm keeps the
/// gated documents dormant.
#[test]
fn root_set_literal_chains_decode_as_value_dispatch_guards() {
    let helpers = indoc! {r#"
        {{- define "repro.mode" -}}
          {{- if .Values.externalAddr -}}
            {{- $_ := set . "mode" "external" -}}
          {{- else if eq (.Values.ha.enabled | toString) "true" -}}
            {{- $_ := set . "mode" "ha" -}}
          {{- else -}}
            {{- $_ := set . "mode" "standalone" -}}
          {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        {{ template "repro.mode" . }}
        {{- if ne .mode "external" }}
        {{- if .Values.route.enabled }}
        {{- if not .Values.route.parentRefs }}
        {{- fail "route.parentRefs must be set when route is enabled" -}}
        {{- end }}
        {{- end }}
        {{- if eq .mode "ha" }}
        {{- if not .Values.ha.replicas }}
        {{- fail "ha mode requires ha.replicas" -}}
        {{- end }}
        {{- end }}
        kind: ConfigMap
        {{- end }}
    "#};
    let values_yaml = indoc! {r#"
        externalAddr: ""
        ha:
          enabled: false
          replicas: 0
        route:
          enabled: false
          parentRefs: []
    "#};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    // Cases compose over the declared defaults: the `ha` and `route` hosts
    // are navigated on every render.
    for (overrides, want, label) in [
        (serde_json::json!({}), true, "defaults skip every gate"),
        (
            serde_json::json!({ "route": { "enabled": true } }),
            false,
            "an enabled route without parentRefs aborts in standalone mode",
        ),
        (
            serde_json::json!({ "route": { "enabled": true,
                "parentRefs": [ { "name": "gw" } ] } }),
            true,
            "an enabled route with parentRefs renders",
        ),
        (
            serde_json::json!({ "route": { "enabled": true },
                "externalAddr": "https://vault.example.com" }),
            true,
            "the external arm keeps the gated document dormant",
        ),
        (
            serde_json::json!({ "ha": { "enabled": true } }),
            false,
            "ha mode without replicas aborts through the eq dispatch",
        ),
        (
            serde_json::json!({ "ha": { "enabled": true, "replicas": 3 } }),
            true,
            "ha mode with replicas renders",
        ),
        (
            serde_json::json!({ "ha": { "enabled": true },
                "externalAddr": "https://vault.example.com" }),
            true,
            "the external arm outranks the ha arm in the chain",
        ),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "root-set value dispatch ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// `semverCompare` over a Capabilities-defaulted version local decodes
/// against the analysis-policy Kubernetes version: with the override unset
/// the policy version decides the gate constantly, and a truthy override
/// substitutes its own exact constraint language (kube-prometheus-stack's
/// grafana dashboard document gates; helm-verified with
/// `--kube-version` / `kubeTargetVersionOverride` probes).
#[test]
fn capabilities_defaulted_semver_gates_decode_against_the_policy_version() {
    let src = indoc! {r#"
        {{- $kubeTargetVersion := default .Capabilities.KubeVersion.GitVersion .Values.versionOverride }}
        {{- if and .Values.gate (semverCompare ">=1.14.0-0" $kubeTargetVersion) }}
        {{- if not .Values.selector }}
        {{- fail "selector must be specified" }}
        {{- end }}
        kind: ConfigMap
        {{- end }}
    "#};
    let values_yaml = indoc! {r#"
        gate: false
        versionOverride: ""
        selector: {}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_kubernetes_version(src, "1.29.0"),
        Some(values_yaml),
    );
    for (instance, want, label) in [
        (serde_json::json!({}), true, "defaults keep the gate off"),
        (
            serde_json::json!({ "gate": true }),
            false,
            "the policy version satisfies the constraint, so the fail binds",
        ),
        (
            serde_json::json!({ "gate": true, "selector": { "app": "x" } }),
            true,
            "a selector satisfies the terminal",
        ),
        (
            serde_json::json!({ "gate": true, "versionOverride": "1.13.0" }),
            true,
            "an old override turns the gate off exactly",
        ),
        (
            serde_json::json!({ "gate": true, "versionOverride": "1.20.0" }),
            false,
            "a satisfying override keeps the fail bound",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "capabilities semver gate ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// Sprig `dig` splits its subject and intermediate-step contracts: the
/// SUBJECT is type-asserted before any missing-key handling (an explicit
/// null aborts; absence stays open to the caller's defaults), while an
/// INTERMEDIATE step falls back to the dig default when nil but aborts on
/// any other non-map — including Helm-falsy scalars (KPS's nulled
/// `customRules` and trivy-operator's nulled `trivy.resources`).
#[test]
fn dig_subjects_reject_null_while_intermediate_nils_fall_back() {
    let src = indoc! {r#"
        {{- if .Values.rules.create }}
        config:
          severity: {{ dig "alpha" "severity" "critical" .Values.customRules }}
          cpu: {{ dig "resources" "requests" "cpu" "100m" .Values.trivy }}
        {{- end }}
    "#};
    let values_yaml = indoc! {r"
        rules:
          create: true
        customRules: {}
        trivy: {}
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    // Instances are raw documents: the null SPELLING is what the subject's
    // even-null type assertion rejects, and a coalesced document can never
    // carry it for a declared key. They still spell every declared root the
    // template digs, because a top-level subject that goes MISSING is now
    // claimed too — the absent and null states abort the same assertion.
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "defaults render",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "customRules": null,
                "trivy": {} }),
            false,
            "a null dig subject aborts the type assertion",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "customRules": "junk",
                "trivy": {} }),
            false,
            "a scalar dig subject aborts",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "trivy": {},
                "customRules": { "alpha": { "severity": "warning" } } }),
            true,
            "a map subject renders",
        ),
        (
            serde_json::json!({ "customRules": null, "rules": { "create": false } }),
            true,
            "the create gate keeps the dig dormant",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "customRules": {},
                "trivy": { "resources": null } }),
            true,
            "a nil intermediate step falls back to the default",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "customRules": {},
                "trivy": { "resources": false } }),
            false,
            "a falsy non-nil intermediate aborts",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "customRules": {},
                "trivy": { "resources": "junk" } }),
            false,
            "a scalar intermediate aborts",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "customRules": {},
                "trivy": { "resources": { "requests": { "cpu": "1" } } } }),
            true,
            "map intermediates render",
        ),
        (
            serde_json::json!({ "rules": { "create": true }, "customRules": {} }),
            false,
            "a deleted top-level subject aborts the same assertion",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "dig subject/intermediate contract ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// A per-op requirement fail over a DIRECT range (`and (or (eq .op …))
/// (not (hasKey . "from"))` → fail) negates to the exact per-member
/// disjunction: complete patches of the gated ops render while a gated op
/// missing its companion key aborts (the nats jsonpatch engine's
/// `copy`/`move`-without-`from` shape).
#[test]
fn per_op_requirement_binds_in_a_direct_range() {
    let src = indoc! {r#"
        {{- range $patch := .Values.service.patch }}
        {{- if and (or (eq $patch.op "copy") (eq $patch.op "move")) (not (hasKey $patch "from")) }}
        {{- fail "missing from" }}
        {{- end }}
        {{- end }}
        config:
          ok: true
    "#};
    let schema = schema_for_values_yaml(
        parse_ir(src),
        Some(indoc! {"
            service:
              patch: []
        "}),
    );
    for (item, want, label) in [
        (
            serde_json::json!({ "op": "copy", "from": "/x" }),
            true,
            "copy with from",
        ),
        (
            serde_json::json!({ "op": "add" }),
            true,
            "add needs no from",
        ),
        (
            serde_json::json!({ "op": "copy" }),
            false,
            "copy without from",
        ),
        (
            serde_json::json!({ "op": "move" }),
            false,
            "move without from",
        ),
    ] {
        let instance = serde_json::json!({ "service": { "patch": [item] } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "per-op requirement direct range ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// The same per-op requirement binds through the helper JSON roundtrip
/// (`$params := fromJson (toJson .)` + `range $params.patch`): the
/// roundtripped member keeps its identity, so the `hasKey` conjuncts
/// decode instead of poisoning the capture with approximates — the
/// helper's call-dict `patch` field must not shadow the range variable of
/// the same name.
#[test]
fn per_op_requirement_binds_through_the_helper_roundtrip() {
    let helpers = indoc! {r#"
        {{- define "repro.jsonpatch" -}}
        {{- $params := fromJson (toJson .) -}}
        {{- $patches := $params.patch -}}
        {{- $docContainer := pick $params "doc" -}}
        {{- range $patch := $patches -}}
        {{- if not (hasKey $patch "op") -}}{{- fail "missing op" -}}{{- end -}}
        {{- if and (or (eq $patch.op "copy") (eq $patch.op "move")) (not (hasKey $patch "from")) -}}
        {{- fail "missing from" -}}
        {{- end -}}
        {{- end -}}
        {{- toJson $docContainer -}}
        {{- end -}}

        {{- define "repro.load" -}}
        {{- $doc := dict -}}
        {{- get (include "repro.jsonpatch" (dict "doc" $doc "patch" (.patch | default list)) | fromJson ) "doc" | toYaml -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: cm
        data:
          out: {{ include "repro.load" (dict "patch" .Values.service.patch) | quote }}
    "#};
    let schema = schema_for_values_yaml(
        parse_ir_with_helpers(src, helpers),
        Some(indoc! {"
            service:
              patch: []
        "}),
    );
    for (item, want, label) in [
        (
            serde_json::json!({ "op": "copy", "from": "/x" }),
            true,
            "copy with from",
        ),
        (
            serde_json::json!({ "op": "add" }),
            true,
            "add needs no from",
        ),
        (serde_json::json!({ "path": "/x" }), false, "missing op"),
        (
            serde_json::json!({ "op": "copy" }),
            false,
            "copy without from",
        ),
    ] {
        let instance = serde_json::json!({ "service": { "patch": [item] } });
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "per-op requirement helper roundtrip ({label}): instance={instance}; schema={schema}"
        );
    }
}

/// The loki `dig` corridor: a NESTED raw-identity subject under a
/// decodable helper-boolean gate must be PRESENT — `dig` type-asserts the
/// subject before its missing-key handling, so a null-DELETED subject
/// reads as nil and aborts exactly like an explicit null. The presence
/// claim is abort-grade and exempt from the default-supplied `required`
/// relaxation, a `| default dict` chain subject keeps every falsy state
/// open (the fallback renders), and dormant gates keep junk open.
#[test]
fn dig_subject_presence_binds_through_selection_gates() {
    let helpers = indoc! {r#"
        {{- define "test.isObj" -}}
        {{- has .Values.loki.storage.type (list "s3" "gcs") }}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        {{- if eq (include "test.isObj" .) "true" }}
        {{- if not (or (dig "aws" "s3" "" .Values.loki.storage_config) (dig "aws" "bucketnames" "" .Values.loki.storage_config)) }}
        bucket: {{ .Values.bucket }}
        {{- end }}
        {{- end }}
        chained: {{ dig "a" "b" (.Values.loki.extra | default dict) }}
    "#};
    let values_yaml = indoc! {r"
        loki:
          storage:
            type: s3
          storage_config: {}
          extra: {}
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "empty document stays dormant",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "s3" } } }),
            false,
            "a live gate demands the deleted subject",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "s3" },
                "storage_config": { "aws": { "s3": "s3://x" } } } }),
            true,
            "a live map subject renders",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "s3" }, "storage_config": null } }),
            false,
            "a live explicit-null subject aborts the assertion",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" } } }),
            true,
            "a non-member storage type keeps the digs dormant",
        ),
        // A DELETED chain subject stays open: the `| default dict`
        // fallback renders, and the raw-identity gate keeps the presence
        // claim off the chain.
        (
            serde_json::json!({ "loki": { "storage": { "type": "s3" },
                "storage_config": {} } }),
            true,
            "a deleted chain subject renders through the dict fallback",
        ),
        // The chain hands `dig` whatever is truthy, so the type assertion
        // rides the subject's own truthiness: every falsy spelling renders
        // the fallback, and a truthy non-map aborts.
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" }, "extra": "" } }),
            true,
            "an empty-string chain subject renders the fallback",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" }, "extra": [] } }),
            true,
            "an empty-list chain subject renders the fallback",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" }, "extra": 0 } }),
            true,
            "a zero chain subject renders the fallback",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" }, "extra": false } }),
            true,
            "a false chain subject renders the fallback",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" }, "extra": "junk" } }),
            false,
            "a truthy string chain subject aborts the type assertion",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" }, "extra": [1] } }),
            false,
            "a truthy list chain subject aborts the type assertion",
        ),
        (
            serde_json::json!({ "loki": { "storage": { "type": "local" },
                "extra": { "a": "dug" } } }),
            true,
            "a map chain subject digs its member",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "dig subject presence ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// A TOP-LEVEL `dig` subject aborts on absence exactly like a nested one —
/// kube-prometheus-stack's `customRules`, whose deletion makes `dig`
/// type-assert nil ("interface {} is nil, not map[string]interface {}").
/// It has no parent slot to carry a member requirement, so the claim lands
/// as a document-level absence clause, and a dormant gate keeps the
/// deletion open.
#[test]
fn root_level_dig_subjects_must_stay_present() {
    let src = indoc! {r#"
        {{- if .Values.rules.enabled }}
        for: {{ dig "Alert" "for" "10m" .Values.customRules }}
        {{- end }}
    "#};
    let values_yaml = indoc! {r"
        customRules: {}
        rules:
          enabled: true
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "the chart's own defaults render",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "customRules": { "Alert": { "for": "5m" } } }),
            ),
            true,
            "a populated subject renders",
        ),
        (
            composed_instance(values_yaml, serde_json::json!({ "customRules": null })),
            false,
            "a live deleted subject aborts the type assertion",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "customRules": null, "rules": { "enabled": false } }),
            ),
            true,
            "a dormant gate keeps the deletion open",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "root dig subject presence ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// A ranged MEMBER's nil-strict operand: the minio chart's
/// `tpl .accessKey $` runs once per visited `users` member, so every member
/// must carry the key — helm aborts with "wrong type for value; expected
/// string" on the first one that omits it. The claim's only possible host is
/// the item slot, which states it per member instead of once for the
/// collection.
#[test]
fn ranged_member_nil_strict_operands_must_be_present() {
    let src = indoc! {r"
        {{- range .Values.users }}
        key: {{ tpl .accessKey $ }}
        {{- end }}
    "};
    let values_yaml = indoc! {r"
        users:
          - accessKey: console
            policy: readonly
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "the chart's own defaults render",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "users": [{ "accessKey": "a", "policy": "p" }] }),
            ),
            true,
            "a member carrying the key renders",
        ),
        (
            composed_instance(values_yaml, serde_json::json!({ "users": [] })),
            true,
            "an empty collection visits nothing",
        ),
        (
            composed_instance(values_yaml, serde_json::json!({ "users": null })),
            true,
            "a deleted collection visits nothing",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "users": [{ "policy": "p" }] }),
            ),
            false,
            "a member omitting the key aborts the operand",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "users": [{ "accessKey": "a" }, { "policy": "p" }] }),
            ),
            false,
            "one bad member among good ones still aborts",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "ranged member presence ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// A per-member requirement scoped by a per-member GUARD: the minio chart
/// reads `.existingSecretKey` through `tpl` only for the `users` members
/// that carry a truthy `.existingSecret`, so the claim belongs inside the
/// item beside its selector — a collection-level guard cannot address "this
/// member".
#[test]
fn member_local_guards_scope_member_local_requirements() {
    let src = indoc! {r"
        {{- range .Values.users }}
        {{- if .existingSecret }}
        key: {{ tpl .existingSecretKey $ }}
        {{- end }}
        {{- end }}
    "};
    let values_yaml = indoc! {r"
        users:
          - accessKey: console
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    for (instance, want, label) in [
        (
            composed_instance(values_yaml, serde_json::json!({})),
            true,
            "the chart's own defaults render",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "users": [{ "existingSecret": "s", "existingSecretKey": "k" }] }),
            ),
            true,
            "a selected member carrying the key renders",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "users": [{ "existingSecret": "" }] }),
            ),
            true,
            "a falsy selector keeps the member dormant",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "users": [{ "existingSecret": "s" }] }),
            ),
            false,
            "a selected member omitting the key aborts the operand",
        ),
        (
            composed_instance(
                values_yaml,
                serde_json::json!({ "users": [{ "existingSecret": "s", "existingSecretKey": 7 }] }),
            ),
            false,
            "a selected member's non-string key aborts the operand",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "member-local guard ({label}): instance={instance}; want={want}; schema={schema}"
        );
    }
}

/// `required` observes the result of `coalesce`, not either source in
/// isolation: the call aborts only while every candidate is Helm-falsy.
#[test]
fn required_over_coalesce_rejects_only_the_all_falsy_state() {
    let src = indoc! {r#"
        {{- if .Values.enabled }}
        {{- $_ := required "set a value" (coalesce .Values.primary .Values.fallback) }}
        {{- end }}
    "#};
    let values_yaml = indoc! {r#"
        enabled: false
        primary: ""
        fallback: ""
    "#};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    let expected = expected_values_schema(
        [
            ("enabled".to_string(), serde_json::json!({})),
            ("fallback".to_string(), serde_json::json!({})),
            ("primary".to_string(), serde_json::json!({})),
        ]
        .into_iter()
        .collect(),
        vec![serde_json::json!({
            "if": {
                "allOf": [
                    helm_truthy_guard("enabled"),
                    {
                        "not": {
                            "anyOf": [
                                helm_truthy_guard("fallback"),
                                helm_truthy_guard("primary"),
                            ],
                        },
                    },
                ],
            },
            "then": false,
        })],
        true,
    );
    sim_assert_eq!(have: schema, want: expected);

    for (instance, want) in [
        (
            serde_json::json!({ "enabled": true, "primary": "", "fallback": "" }),
            false,
        ),
        (
            serde_json::json!({ "enabled": true, "primary": "secret", "fallback": "" }),
            true,
        ),
        (
            serde_json::json!({ "enabled": true, "primary": "", "fallback": "secret" }),
            true,
        ),
        (
            serde_json::json!({ "enabled": false, "primary": "", "fallback": "" }),
            true,
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "required(coalesce …) truth table: instance={instance}; want={want}; schema={schema}"
        );
    }
}